Skip to main content

nautilus_blockchain/contracts/
uniswap_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 std::sync::Arc;
17
18use alloy::{
19    primitives::{Address, aliases::U24},
20    sol,
21    sol_types::SolCall,
22};
23
24use super::base::BaseContract;
25use crate::rpc::{error::BlockchainRpcClientError, http::BlockchainHttpRpcClient};
26
27// The original Uniswap V3 SwapRouter interface: `exactInputSingle` carries a `deadline`
28// parameter, unlike the later SwapRouter02 whose struct drops it.
29sol! {
30    contract UniswapV3SwapRouter {
31        struct ExactInputSingleParams {
32            address tokenIn;
33            address tokenOut;
34            uint24 fee;
35            address recipient;
36            uint256 deadline;
37            uint256 amountIn;
38            uint256 amountOutMinimum;
39            uint160 sqrtPriceLimitX96;
40        }
41
42        function exactInputSingle(ExactInputSingleParams memory params) external payable returns (uint256 amountOut);
43    }
44}
45
46sol! {
47    contract UniswapV3RouterState {
48        function factory() external view returns (address);
49        function WETH9() external view returns (address);
50    }
51
52    contract UniswapV3Factory {
53        function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool);
54    }
55}
56
57/// Reads immutable deployment relationships used to authorize Uniswap V3 execution.
58#[derive(Debug)]
59pub struct UniswapV3Deployment {
60    base: BaseContract,
61}
62
63impl UniswapV3Deployment {
64    /// Creates a deployment reader with an optional per-request timeout.
65    #[must_use]
66    pub fn new(client: Arc<BlockchainHttpRpcClient>, rpc_timeout_secs: Option<u64>) -> Self {
67        Self {
68            base: BaseContract::new_with_multicall_limit_and_timeout(
69                client,
70                super::base::DEFAULT_MULTICALL_CALLS_PER_RPC_REQUEST,
71                rpc_timeout_secs,
72            ),
73        }
74    }
75
76    /// Reads the factory configured by the router.
77    ///
78    /// # Errors
79    ///
80    /// Returns an error if the RPC call fails or the result cannot be decoded as an address.
81    pub async fn router_factory(
82        &self,
83        router: &Address,
84    ) -> Result<Address, BlockchainRpcClientError> {
85        self.router_factory_with_block(router, None).await
86    }
87
88    async fn router_factory_with_block(
89        &self,
90        router: &Address,
91        block: Option<u64>,
92    ) -> Result<Address, BlockchainRpcClientError> {
93        let result = self
94            .base
95            .execute_call(
96                router,
97                &UniswapV3RouterState::factoryCall {}.abi_encode(),
98                block,
99            )
100            .await?;
101        UniswapV3RouterState::factoryCall::abi_decode_returns(&result)
102            .map_err(|e| BlockchainRpcClientError::AbiDecodingError(e.to_string()))
103    }
104
105    /// Reads the wrapped-native-token address configured by the router.
106    ///
107    /// # Errors
108    ///
109    /// Returns an error if the RPC call fails or the result cannot be decoded as an address.
110    pub async fn router_weth9(
111        &self,
112        router: &Address,
113    ) -> Result<Address, BlockchainRpcClientError> {
114        self.router_weth9_with_block(router, None).await
115    }
116
117    async fn router_weth9_with_block(
118        &self,
119        router: &Address,
120        block: Option<u64>,
121    ) -> Result<Address, BlockchainRpcClientError> {
122        let result = self
123            .base
124            .execute_call(
125                router,
126                &UniswapV3RouterState::WETH9Call {}.abi_encode(),
127                block,
128            )
129            .await?;
130        UniswapV3RouterState::WETH9Call::abi_decode_returns(&result)
131            .map_err(|e| BlockchainRpcClientError::AbiDecodingError(e.to_string()))
132    }
133
134    /// Resolves the canonical pool registered by a factory for a token pair and fee tier.
135    ///
136    /// # Errors
137    ///
138    /// Returns an error if the RPC call fails or the result cannot be decoded as an address.
139    pub async fn pool(
140        &self,
141        factory: &Address,
142        token_a: Address,
143        token_b: Address,
144        fee: U24,
145    ) -> Result<Address, BlockchainRpcClientError> {
146        self.pool_with_block(factory, token_a, token_b, fee, None)
147            .await
148    }
149
150    async fn pool_with_block(
151        &self,
152        factory: &Address,
153        token_a: Address,
154        token_b: Address,
155        fee: U24,
156        block: Option<u64>,
157    ) -> Result<Address, BlockchainRpcClientError> {
158        let call = UniswapV3Factory::getPoolCall {
159            tokenA: token_a,
160            tokenB: token_b,
161            fee,
162        };
163        let result = self
164            .base
165            .execute_call(factory, &call.abi_encode(), block)
166            .await?;
167        UniswapV3Factory::getPoolCall::abi_decode_returns(&result)
168            .map_err(|e| BlockchainRpcClientError::AbiDecodingError(e.to_string()))
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use alloy::{
175        primitives::{
176            U256, address,
177            aliases::{U24, U160},
178        },
179        sol_types::SolCall,
180    };
181    use nautilus_core::hex;
182    use rstest::rstest;
183
184    use super::*;
185
186    #[rstest]
187    fn exact_input_single_selector_matches_canonical_signature() {
188        let calldata = UniswapV3SwapRouter::exactInputSingleCall {
189            params: UniswapV3SwapRouter::ExactInputSingleParams {
190                tokenIn: address!("82aF49447D8a07e3bd95BD0d56f35241523fBab1"),
191                tokenOut: address!("af88d065e77c8cC2239327C5EDb3A432268e5831"),
192                fee: U24::try_from(500u32).unwrap(),
193                recipient: address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"),
194                deadline: U256::from(1_761_889_100u64),
195                amountIn: U256::from(1_000_000_000_000_000u64),
196                amountOutMinimum: U256::from(1_995_000u64),
197                sqrtPriceLimitX96: U160::ZERO,
198            },
199        }
200        .abi_encode();
201
202        // keccak256("exactInputSingle((address,address,uint24,address,uint256,uint256,uint256,uint160))")
203        assert_eq!(hex::encode(&calldata[..4]), "414bf389");
204    }
205
206    #[rstest]
207    fn exact_input_single_encodes_fields_in_order() {
208        let calldata = UniswapV3SwapRouter::exactInputSingleCall {
209            params: UniswapV3SwapRouter::ExactInputSingleParams {
210                tokenIn: address!("82aF49447D8a07e3bd95BD0d56f35241523fBab1"),
211                tokenOut: address!("af88d065e77c8cC2239327C5EDb3A432268e5831"),
212                fee: U24::try_from(500u32).unwrap(),
213                recipient: address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"),
214                deadline: U256::from(1_761_889_100u64),
215                amountIn: U256::from(1_000_000_000_000_000u64),
216                amountOutMinimum: U256::from(1_995_000u64),
217                sqrtPriceLimitX96: U160::ZERO,
218            },
219        }
220        .abi_encode();
221
222        let expected = concat!(
223            "414bf389",
224            "00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab1",
225            "000000000000000000000000af88d065e77c8cc2239327c5edb3a432268e5831",
226            "00000000000000000000000000000000000000000000000000000000000001f4",
227            "000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266",
228            "0000000000000000000000000000000000000000000000000000000069044b4c",
229            "00000000000000000000000000000000000000000000000000038d7ea4c68000",
230            "00000000000000000000000000000000000000000000000000000000001e70f8",
231            "0000000000000000000000000000000000000000000000000000000000000000",
232        );
233        assert_eq!(hex::encode(&calldata), expected);
234    }
235
236    #[rstest]
237    fn deployment_selectors_match_canonical_signatures() {
238        assert_eq!(
239            hex::encode(UniswapV3RouterState::factoryCall {}.abi_encode()),
240            "c45a0155"
241        );
242        assert_eq!(
243            hex::encode(UniswapV3RouterState::WETH9Call {}.abi_encode()),
244            "4aa4a4fc"
245        );
246        let calldata = UniswapV3Factory::getPoolCall {
247            tokenA: address!("82aF49447D8a07e3bd95BD0d56f35241523fBab1"),
248            tokenB: address!("af88d065e77c8cC2239327C5EDb3A432268e5831"),
249            fee: U24::try_from(500u32).unwrap(),
250        }
251        .abi_encode();
252        assert_eq!(hex::encode(&calldata[..4]), "1698ee82");
253    }
254}