Skip to main content

nautilus_blockchain/contracts/
base.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::{primitives::Address, sol, sol_types::SolCall};
19use nautilus_core::hex;
20use nautilus_model::defi::validation::validate_address;
21
22use crate::rpc::{error::BlockchainRpcClientError, http::BlockchainHttpRpcClient};
23
24sol! {
25    contract Multicall3 {
26        struct Call {
27            address target;
28            bytes callData;
29        }
30
31        struct Call3 {
32            address target;
33            bool allowFailure;
34            bytes callData;
35        }
36
37        struct Result {
38            bool success;
39            bytes returnData;
40        }
41
42        function aggregate3(Call3[] calldata calls) external payable returns (Result[] memory returnData);
43        function tryAggregate(bool requireSuccess, Call[] calldata calls) external payable returns (Result[] memory returnData);
44    }
45}
46
47/// Standard Multicall3 address (same on all EVM chains).
48pub const MULTICALL3_ADDRESS: &str = "0xcA11bde05977b3631167028862bE2a173976CA11";
49pub(crate) const DEFAULT_MULTICALL_CALLS_PER_RPC_REQUEST: u32 = 200;
50
51/// Base contract functionality for interacting with blockchain contracts.
52///
53/// This struct provides common RPC execution patterns that can be reused
54/// by specific contract implementations like ERC20, ERC721, etc.
55#[derive(Debug)]
56pub struct BaseContract {
57    /// The HTTP RPC client used to communicate with the blockchain node.
58    client: Arc<BlockchainHttpRpcClient>,
59    /// The Multicall3 contract address.
60    multicall_address: Address,
61    /// Maximum number of contract calls encoded into one Multicall RPC request.
62    multicall_calls_per_rpc_request: usize,
63    /// Per-request RPC timeout in seconds, when bounded.
64    rpc_timeout_secs: Option<u64>,
65}
66
67/// Represents a single contract call for batching in multicall.
68#[derive(Debug)]
69pub struct ContractCall {
70    /// The target contract address
71    pub target: Address,
72    /// Whether this call can fail without reverting the entire multicall.
73    pub allow_failure: bool,
74    /// The encoded call data.
75    pub call_data: Vec<u8>,
76}
77
78impl BaseContract {
79    /// Creates a new base contract interface with the specified RPC client.
80    ///
81    /// # Panics
82    ///
83    /// Panics if the multicall address is invalid (which should never happen with the hardcoded address).
84    #[must_use]
85    pub fn new(client: Arc<BlockchainHttpRpcClient>) -> Self {
86        Self::new_with_multicall_limit(client, DEFAULT_MULTICALL_CALLS_PER_RPC_REQUEST)
87    }
88
89    /// Creates a new base contract interface with an explicit Multicall request size.
90    ///
91    /// # Panics
92    ///
93    /// Panics if the multicall address is invalid (which should never happen with the hardcoded address).
94    #[must_use]
95    pub fn new_with_multicall_limit(
96        client: Arc<BlockchainHttpRpcClient>,
97        multicall_calls_per_rpc_request: u32,
98    ) -> Self {
99        Self::new_with_multicall_limit_and_timeout(client, multicall_calls_per_rpc_request, None)
100    }
101
102    /// Creates a new base contract interface with an explicit Multicall request size and
103    /// per-request RPC timeout.
104    ///
105    /// # Panics
106    ///
107    /// Panics if the multicall address is invalid (which should never happen with the hardcoded address).
108    #[must_use]
109    pub fn new_with_multicall_limit_and_timeout(
110        client: Arc<BlockchainHttpRpcClient>,
111        multicall_calls_per_rpc_request: u32,
112        rpc_timeout_secs: Option<u64>,
113    ) -> Self {
114        let multicall_address =
115            validate_address(MULTICALL3_ADDRESS).expect("Invalid multicall address");
116        let multicall_calls_per_rpc_request = (multicall_calls_per_rpc_request as usize).max(1);
117
118        Self {
119            client,
120            multicall_address,
121            multicall_calls_per_rpc_request,
122            rpc_timeout_secs,
123        }
124    }
125
126    /// Gets a reference to the RPC client.
127    #[must_use]
128    pub const fn client(&self) -> &Arc<BlockchainHttpRpcClient> {
129        &self.client
130    }
131
132    /// Executes a single contract call and returns the raw response bytes.
133    ///
134    /// # Errors
135    ///
136    /// Returns an error if the RPC call fails or response decoding fails.
137    pub async fn execute_call(
138        &self,
139        contract_address: &Address,
140        call_data: &[u8],
141        block: Option<u64>,
142    ) -> Result<Vec<u8>, BlockchainRpcClientError> {
143        let rpc_request =
144            self.client
145                .construct_eth_call(&contract_address.to_string(), call_data, block);
146
147        self.execute_call_request(rpc_request).await
148    }
149
150    async fn execute_call_request(
151        &self,
152        rpc_request: serde_json::Value,
153    ) -> Result<Vec<u8>, BlockchainRpcClientError> {
154        let encoded_response = self
155            .client
156            .execute_rpc_call_with_timeout::<String>(rpc_request, self.rpc_timeout_secs)
157            .await
158            .map_err(|e| BlockchainRpcClientError::ClientError(format!("RPC call failed: {e}")))?;
159
160        decode_hex_response(&encoded_response)
161    }
162
163    /// Executes multiple contract calls in a single multicall transaction.
164    ///
165    /// # Errors
166    ///
167    /// Returns an error if the multicall fails or decoding fails.
168    pub async fn execute_multicall(
169        &self,
170        calls: Vec<ContractCall>,
171        block: Option<u64>,
172    ) -> Result<Vec<Multicall3::Result>, BlockchainRpcClientError> {
173        if calls.is_empty() {
174            return Ok(Vec::new());
175        }
176
177        let mut results = Vec::with_capacity(calls.len());
178        for chunk in contract_call_chunks(&calls, self.multicall_calls_per_rpc_request) {
179            results.extend(self.execute_multicall_request(chunk, block).await?);
180        }
181        Ok(results)
182    }
183
184    async fn execute_multicall_request(
185        &self,
186        calls: &[ContractCall],
187        block: Option<u64>,
188    ) -> Result<Vec<Multicall3::Result>, BlockchainRpcClientError> {
189        // Convert to Multicall3 format.
190        let multicall_calls: Vec<Multicall3::Call> = calls
191            .iter()
192            .map(|call| Multicall3::Call {
193                target: call.target,
194                callData: call.call_data.clone().into(),
195            })
196            .collect();
197
198        let multicall_data = Multicall3::tryAggregateCall {
199            requireSuccess: false,
200            calls: multicall_calls,
201        }
202        .abi_encode();
203        let rpc_request = self.client.construct_eth_call(
204            &self.multicall_address.to_string(),
205            multicall_data.as_slice(),
206            block,
207        );
208
209        let encoded_response = self
210            .client
211            .execute_rpc_call_with_timeout::<String>(rpc_request, self.rpc_timeout_secs)
212            .await
213            .map_err(|e| BlockchainRpcClientError::ClientError(format!("Multicall failed: {e}")))?;
214
215        let bytes = decode_hex_response(&encoded_response)?;
216        let results = Multicall3::tryAggregateCall::abi_decode_returns(&bytes).map_err(|e| {
217            BlockchainRpcClientError::AbiDecodingError(format!(
218                "Failed to decode multicall results: {e}"
219            ))
220        })?;
221
222        Ok(results)
223    }
224}
225
226/// Decodes a hexadecimal string response from a blockchain RPC call.
227///
228/// # Errors
229///
230/// Returns an error if the hex decoding fails.
231pub fn decode_hex_response(encoded_response: &str) -> Result<Vec<u8>, BlockchainRpcClientError> {
232    // Remove the "0x" prefix if present
233    let encoded_str = encoded_response
234        .strip_prefix("0x")
235        .unwrap_or(encoded_response);
236    hex::decode(encoded_str).map_err(|e| {
237        BlockchainRpcClientError::AbiDecodingError(format!("Error decoding hex response: {e}"))
238    })
239}
240
241fn contract_call_chunks(
242    calls: &[ContractCall],
243    multicall_calls_per_rpc_request: usize,
244) -> std::slice::Chunks<'_, ContractCall> {
245    calls.chunks(multicall_calls_per_rpc_request.max(1))
246}
247
248#[cfg(test)]
249mod tests {
250    use alloy::primitives::address;
251    use rstest::rstest;
252
253    use super::*;
254
255    #[rstest]
256    fn contract_call_chunks_preserves_order_across_chunk_boundary() {
257        let target = address!("25b76A90E389bD644a29db919b136Dc63B174Ec7");
258        let calls: Vec<ContractCall> = (0u8..5)
259            .map(|value| ContractCall {
260                target,
261                allow_failure: true,
262                call_data: vec![value],
263            })
264            .collect();
265
266        let chunks: Vec<Vec<u8>> = contract_call_chunks(&calls, 2)
267            .map(|chunk| chunk.iter().map(|call| call.call_data[0]).collect())
268            .collect();
269
270        assert_eq!(chunks, vec![vec![0, 1], vec![2, 3], vec![4]]);
271    }
272
273    #[rstest]
274    fn contract_call_chunks_treats_zero_limit_as_one() {
275        let target = address!("25b76A90E389bD644a29db919b136Dc63B174Ec7");
276        let calls: Vec<ContractCall> = (0u8..3)
277            .map(|value| ContractCall {
278                target,
279                allow_failure: true,
280                call_data: vec![value],
281            })
282            .collect();
283
284        let chunks: Vec<Vec<u8>> = contract_call_chunks(&calls, 0)
285            .map(|chunk| chunk.iter().map(|call| call.call_data[0]).collect())
286            .collect();
287
288        assert_eq!(chunks, vec![vec![0], vec![1], vec![2]]);
289    }
290}