nautilus-blockchain 0.55.0

Blockchain and DeFi integration adapter for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

use std::{collections::HashMap, sync::Arc};

use alloy::{
    primitives::{Address, U256, keccak256},
    sol,
    sol_types::{SolCall, private::primitives::aliases::I24},
};
use nautilus_core::hex;
use nautilus_model::{
    defi::{
        data::block::BlockPosition,
        pool_analysis::{
            position::PoolPosition,
            snapshot::{PoolAnalytics, PoolSnapshot, PoolState},
        },
        tick_map::tick::PoolTick,
    },
    identifiers::InstrumentId,
};
use thiserror::Error;

use super::base::{BaseContract, ContractCall};
use crate::rpc::{error::BlockchainRpcClientError, http::BlockchainHttpRpcClient};

sol! {
    #[sol(rpc)]
    contract UniswapV3Pool {
        /// Packed struct containing core pool state
        struct Slot0Data {
            uint160 sqrtPriceX96;
            int24 tick;
            uint16 observationIndex;
            uint16 observationCardinality;
            uint16 observationCardinalityNext;
            uint8 feeProtocol;
            bool unlocked;
        }

        /// Tick information
        struct TickInfo {
            uint128 liquidityGross;
            int128 liquidityNet;
            uint256 feeGrowthOutside0X128;
            uint256 feeGrowthOutside1X128;
            int56 tickCumulativeOutside;
            uint160 secondsPerLiquidityOutsideX128;
            uint32 secondsOutside;
            bool initialized;
        }

        /// Position information
        struct PositionInfo {
            uint128 liquidity;
            uint256 feeGrowthInside0LastX128;
            uint256 feeGrowthInside1LastX128;
            uint128 tokensOwed0;
            uint128 tokensOwed1;
        }

        // Core state getters
        function slot0() external view returns (Slot0Data memory);
        function liquidity() external view returns (uint128);
        function feeGrowthGlobal0X128() external view returns (uint256);
        function feeGrowthGlobal1X128() external view returns (uint256);

        // Tick and position getters
        function ticks(int24 tick) external view returns (TickInfo memory);
        function positions(bytes32 key) external view returns (PositionInfo memory);
    }
}

/// Represents errors that can occur when interacting with UniswapV3Pool contract.
#[derive(Debug, Error)]
pub enum UniswapV3PoolError {
    #[error("RPC error: {0}")]
    RpcError(#[from] BlockchainRpcClientError),
    #[error("Failed to decode {field} for pool {pool}: {reason} (raw data: {raw_data})")]
    DecodingError {
        field: String,
        pool: Address,
        reason: String,
        raw_data: String,
    },
    #[error("Call failed for {field} at pool {pool}: {reason}")]
    CallFailed {
        field: String,
        pool: Address,
        reason: String,
    },
    #[error("Tick {tick} is not initialized in pool {pool}")]
    TickNotInitialized { tick: i32, pool: Address },
}

/// Interface for interacting with UniswapV3Pool contracts on a blockchain.
///
/// This struct provides methods to query pool state including slot0, liquidity,
/// fee growth, tick data, and position data. Supports both single calls and
/// batch multicalls for efficiency.
#[derive(Debug)]
pub struct UniswapV3PoolContract {
    /// The base contract providing common RPC execution functionality.
    base: BaseContract,
}

impl UniswapV3PoolContract {
    /// Creates a new UniswapV3Pool contract interface with the specified RPC client.
    #[must_use]
    pub fn new(client: Arc<BlockchainHttpRpcClient>) -> Self {
        Self {
            base: BaseContract::new(client),
        }
    }

    /// Gets all global state in a single multicall.
    ///
    /// # Errors
    ///
    /// Returns an error if the multicall fails or any decoding fails.
    pub async fn get_global_state(
        &self,
        pool_address: &Address,
        block: Option<u64>,
    ) -> Result<PoolState, UniswapV3PoolError> {
        let calls = vec![
            ContractCall {
                target: *pool_address,
                allow_failure: false,
                call_data: UniswapV3Pool::slot0Call {}.abi_encode(),
            },
            ContractCall {
                target: *pool_address,
                allow_failure: false,
                call_data: UniswapV3Pool::liquidityCall {}.abi_encode(),
            },
            ContractCall {
                target: *pool_address,
                allow_failure: false,
                call_data: UniswapV3Pool::feeGrowthGlobal0X128Call {}.abi_encode(),
            },
            ContractCall {
                target: *pool_address,
                allow_failure: false,
                call_data: UniswapV3Pool::feeGrowthGlobal1X128Call {}.abi_encode(),
            },
        ];

        let results = self.base.execute_multicall(calls, block).await?;

        if results.len() != 4 {
            return Err(UniswapV3PoolError::CallFailed {
                field: "global_state_multicall".to_string(),
                pool: *pool_address,
                reason: format!("Expected 4 results, received {}", results.len()),
            });
        }

        // Decode slot0
        let slot0 =
            UniswapV3Pool::slot0Call::abi_decode_returns(&results[0].returnData).map_err(|e| {
                UniswapV3PoolError::DecodingError {
                    field: "slot0".to_string(),
                    pool: *pool_address,
                    reason: e.to_string(),
                    raw_data: hex::encode(&results[0].returnData),
                }
            })?;

        // Decode liquidity
        let liquidity = UniswapV3Pool::liquidityCall::abi_decode_returns(&results[1].returnData)
            .map_err(|e| UniswapV3PoolError::DecodingError {
                field: "liquidity".to_string(),
                pool: *pool_address,
                reason: e.to_string(),
                raw_data: hex::encode(&results[1].returnData),
            })?;

        // Decode feeGrowthGlobal0X128
        let fee_growth_0 =
            UniswapV3Pool::feeGrowthGlobal0X128Call::abi_decode_returns(&results[2].returnData)
                .map_err(|e| UniswapV3PoolError::DecodingError {
                    field: "feeGrowthGlobal0X128".to_string(),
                    pool: *pool_address,
                    reason: e.to_string(),
                    raw_data: hex::encode(&results[2].returnData),
                })?;

        // Decode feeGrowthGlobal1X128
        let fee_growth_1 =
            UniswapV3Pool::feeGrowthGlobal1X128Call::abi_decode_returns(&results[3].returnData)
                .map_err(|e| UniswapV3PoolError::DecodingError {
                    field: "feeGrowthGlobal1X128".to_string(),
                    pool: *pool_address,
                    reason: e.to_string(),
                    raw_data: hex::encode(&results[3].returnData),
                })?;

        Ok(PoolState {
            current_tick: slot0.tick.as_i32(),
            price_sqrt_ratio_x96: slot0.sqrtPriceX96,
            liquidity,
            protocol_fees_token0: U256::ZERO,
            protocol_fees_token1: U256::ZERO,
            fee_protocol: slot0.feeProtocol,
            fee_growth_global_0: fee_growth_0,
            fee_growth_global_1: fee_growth_1,
        })
    }

    /// Gets tick data for a specific tick.
    ///
    /// # Errors
    ///
    /// Returns an error if the RPC call fails or decoding fails.
    pub async fn get_tick(
        &self,
        pool_address: &Address,
        tick: i32,
        block: Option<u64>,
    ) -> Result<PoolTick, UniswapV3PoolError> {
        let tick_i24 = I24::try_from(tick).map_err(|_| UniswapV3PoolError::CallFailed {
            field: "tick".to_string(),
            pool: *pool_address,
            reason: format!("Tick {tick} out of range for int24"),
        })?;

        let call_data = UniswapV3Pool::ticksCall { tick: tick_i24 }.abi_encode();
        let raw_response = self
            .base
            .execute_call(pool_address, &call_data, block)
            .await?;

        let tick_info =
            UniswapV3Pool::ticksCall::abi_decode_returns(&raw_response).map_err(|e| {
                UniswapV3PoolError::DecodingError {
                    field: format!("ticks({tick})"),
                    pool: *pool_address,
                    reason: e.to_string(),
                    raw_data: hex::encode(&raw_response),
                }
            })?;

        Ok(PoolTick::new(
            tick,
            tick_info.liquidityGross,
            tick_info.liquidityNet,
            tick_info.feeGrowthOutside0X128,
            tick_info.feeGrowthOutside1X128,
            tick_info.initialized,
            0, // last_updated_block - not available from RPC
        ))
    }

    /// Gets tick data for multiple ticks in a single multicall.
    ///
    /// # Errors
    ///
    /// Returns an error if the multicall fails or if any tick decoding fails.
    /// Uninitialized ticks are silently skipped (not included in the result HashMap).
    pub async fn batch_get_ticks(
        &self,
        pool_address: &Address,
        ticks: &[i32],
        block: Option<u64>,
    ) -> Result<HashMap<i32, PoolTick>, UniswapV3PoolError> {
        let calls: Vec<ContractCall> = ticks
            .iter()
            .filter_map(|&tick| {
                I24::try_from(tick).ok().map(|tick_i24| ContractCall {
                    target: *pool_address,
                    allow_failure: true,
                    call_data: UniswapV3Pool::ticksCall { tick: tick_i24 }.abi_encode(),
                })
            })
            .collect();

        let results = self.base.execute_multicall(calls, block).await?;

        let mut tick_infos = HashMap::with_capacity(ticks.len());
        for (i, &tick_value) in ticks.iter().enumerate() {
            if i >= results.len() {
                break;
            }

            let result = &results[i];
            if !result.success {
                // Skip uninitialized ticks
                continue;
            }

            let tick_info = UniswapV3Pool::ticksCall::abi_decode_returns(&result.returnData)
                .map_err(|e| UniswapV3PoolError::DecodingError {
                    field: format!("ticks({tick_value})"),
                    pool: *pool_address,
                    reason: e.to_string(),
                    raw_data: hex::encode(&result.returnData),
                })?;

            tick_infos.insert(
                tick_value,
                PoolTick::new(
                    tick_value,
                    tick_info.liquidityGross,
                    tick_info.liquidityNet,
                    tick_info.feeGrowthOutside0X128,
                    tick_info.feeGrowthOutside1X128,
                    tick_info.initialized,
                    0, // last_updated_block - not available from RPC
                ),
            );
        }

        Ok(tick_infos)
    }

    /// Computes the position key used by Uniswap V3.
    ///
    /// The key is: keccak256(abi.encodePacked(owner, tickLower, tickUpper))
    #[must_use]
    pub fn compute_position_key(owner: &Address, tick_lower: i32, tick_upper: i32) -> [u8; 32] {
        // Pack: address (20 bytes) + int24 (3 bytes) + int24 (3 bytes) = 26 bytes total
        let mut packed = Vec::with_capacity(26);

        // Add owner address (20 bytes)
        packed.extend_from_slice(owner.as_slice());

        // Add tick_lower as int24 (3 bytes, big-endian, sign-extended)
        let tick_lower_bytes = tick_lower.to_be_bytes();
        packed.extend_from_slice(&tick_lower_bytes[1..4]);

        // Add tick_upper as int24 (3 bytes, big-endian, sign-extended)
        let tick_upper_bytes = tick_upper.to_be_bytes();
        packed.extend_from_slice(&tick_upper_bytes[1..4]);

        keccak256(&packed).into()
    }

    /// Gets position data for multiple positions in a single multicall.
    ///
    /// # Errors
    ///
    /// Returns an error if the multicall fails. Individual position failures are
    /// captured in the Result values of the returned Vec.
    pub async fn batch_get_positions(
        &self,
        pool_address: &Address,
        positions: &[(Address, i32, i32)],
        block: Option<u64>,
    ) -> Result<Vec<PoolPosition>, UniswapV3PoolError> {
        let calls: Vec<ContractCall> = positions
            .iter()
            .map(|(owner, tick_lower, tick_upper)| {
                let position_key = Self::compute_position_key(owner, *tick_lower, *tick_upper);
                ContractCall {
                    target: *pool_address,
                    allow_failure: true,
                    call_data: UniswapV3Pool::positionsCall {
                        key: position_key.into(),
                    }
                    .abi_encode(),
                }
            })
            .collect();

        let results = self.base.execute_multicall(calls, block).await?;

        let position_infos: Vec<PoolPosition> = positions
            .iter()
            .enumerate()
            .filter_map(|(i, (owner, tick_lower, tick_upper))| {
                if i >= results.len() {
                    return None;
                }

                let result = &results[i];
                if !result.success {
                    return None;
                }

                UniswapV3Pool::positionsCall::abi_decode_returns(&result.returnData)
                    .ok()
                    .map(|info| PoolPosition {
                        owner: *owner,
                        tick_lower: *tick_lower,
                        tick_upper: *tick_upper,
                        liquidity: info.liquidity,
                        fee_growth_inside_0_last: info.feeGrowthInside0LastX128,
                        fee_growth_inside_1_last: info.feeGrowthInside1LastX128,
                        tokens_owed_0: info.tokensOwed0,
                        tokens_owed_1: info.tokensOwed1,
                        total_amount0_deposited: U256::ZERO,
                        total_amount1_deposited: U256::ZERO,
                        total_amount0_collected: 0,
                        total_amount1_collected: 0,
                    })
            })
            .collect();

        Ok(position_infos)
    }

    /// Fetches a complete pool snapshot directly from on-chain state.
    ///
    /// Retrieves global state, tick data, and position data from the blockchain
    /// and constructs a `PoolSnapshot` representing the current on-chain state.
    /// This snapshot can be compared against profiler state for validation.
    ///
    /// # Errors
    ///
    /// Returns error if any RPC calls fail or data cannot be decoded.
    pub async fn fetch_snapshot(
        &self,
        pool_address: &Address,
        instrument_id: InstrumentId,
        tick_values: &[i32],
        position_keys: &[(Address, i32, i32)],
        block_position: BlockPosition,
    ) -> Result<PoolSnapshot, UniswapV3PoolError> {
        // Fetch all data at the specified block
        let block = Some(block_position.number);
        let global_state = self.get_global_state(pool_address, block).await?;
        let ticks_map = self
            .batch_get_ticks(pool_address, tick_values, block)
            .await?;
        let positions = self
            .batch_get_positions(pool_address, position_keys, block)
            .await?;

        Ok(PoolSnapshot::new(
            instrument_id,
            global_state,
            positions,
            ticks_map.into_values().collect(),
            PoolAnalytics::default(),
            block_position,
        ))
    }
}