nautilus_blockchain/contracts/
base.rs1use 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
47pub const MULTICALL3_ADDRESS: &str = "0xcA11bde05977b3631167028862bE2a173976CA11";
49pub(crate) const DEFAULT_MULTICALL_CALLS_PER_RPC_REQUEST: u32 = 200;
50
51#[derive(Debug)]
56pub struct BaseContract {
57 client: Arc<BlockchainHttpRpcClient>,
59 multicall_address: Address,
61 multicall_calls_per_rpc_request: usize,
63 rpc_timeout_secs: Option<u64>,
65}
66
67#[derive(Debug)]
69pub struct ContractCall {
70 pub target: Address,
72 pub allow_failure: bool,
74 pub call_data: Vec<u8>,
76}
77
78impl BaseContract {
79 #[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 #[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 #[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 #[must_use]
128 pub const fn client(&self) -> &Arc<BlockchainHttpRpcClient> {
129 &self.client
130 }
131
132 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 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 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
226pub fn decode_hex_response(encoded_response: &str) -> Result<Vec<u8>, BlockchainRpcClientError> {
232 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}