1use std::error::Error;
15
16use alloy::primitives::{Address, B256};
17#[cfg(feature = "rfq-v2")]
18use uuid::Uuid;
19
20use crate::wallet::AccountAddress;
21
22pub type BoxClientSource = Box<dyn Error + Send + Sync + 'static>;
24
25#[derive(Debug, thiserror::Error)]
32#[displaystr::display]
33pub enum RfqInputError {
34 InvalidUuid {
35 label: &'static str,
36 #[source]
37 source: uuid::Error,
38 } = "{label}: {source}",
39 InvalidLegSize {
40 label: &'static str,
41 value: String,
42 #[source]
43 source: rust_decimal::Error,
44 } = "{label} leg size {value:?}: {source}",
45 LimitPriceOverflow = "limit_price overflow in micro-unit conversion",
46 LimitPriceConversion {
47 #[source]
48 source: BoxClientSource,
49 } = "limit_price I256 conversion: {source}",
50 NoLegs = "RFQ has no legs",
51 LegCountMismatch {
52 request_count: usize,
53 price_count: usize,
54 } = "leg count mismatch: request has {request_count} legs but {price_count} prices provided",
55 LegPriceNonPositive {
56 index: usize,
57 price: rust_decimal::Decimal,
58 } = "leg {index} price must be positive, got {price}",
59 LegSizeNonPositive {
60 index: usize,
61 size: rust_decimal::Decimal,
62 } = "leg {index} size must be positive, got {size}",
63 InvalidSide {
64 index: usize,
65 side: String,
66 } = "leg {index} has invalid side: {side:?}",
67 NetPremiumNotRepresentable {
68 net_premium: rust_decimal::Decimal,
69 } = "net_premium {net_premium} not representable as micro-units i64",
70 NetPremiumSubMicroPrecision {
71 net_premium: rust_decimal::Decimal,
72 } = "net_premium {net_premium} has sub-micro precision; use at most 6 decimal places so the signed value matches the wire string",
73 NetPremiumConversion {
74 #[source]
75 source: BoxClientSource,
76 } = "net_premium I256 conversion failed: {source}",
77}
78
79#[derive(Debug, thiserror::Error)]
84#[displaystr::display]
85pub enum SigningUnavailableReason {
86 AwsKmsPrivateKeyMaterial = "private key material is unavailable for AWS KMS wallets",
87 HyperliquidMockApiUnauthenticated = "Hyperliquid mock API is not authenticated",
88 HyperliquidSimulationVenueUnauthenticated = "Hyperliquid simulation venue is not authenticated",
89}
90
91macro_rules! client_error_enum {
97 ($($rfq_v2_feature:literal)?) => {
98 #[derive(Debug, thiserror::Error)]
100 #[displaystr::display]
101 pub enum ClientError {
102 Http(#[from] reqwest::Error) = "HTTP error: {_0}",
104 Json(#[from] sonic_rs::Error) = "JSON error: {_0}",
106 InboundJson(#[from] serde_json::Error) = "inbound JSON decode error: {_0}",
109 Signing {
111 operation: String,
112 #[source]
113 source: BoxClientSource,
114 } = "Signing error: {operation}: {source}",
115 SigningUnavailable(#[source] SigningUnavailableReason) = "Signing error: {_0}",
117 Api { status: u16, message: String } = "API error ({status}): {message}",
119 $(
120 #[doc = ""]
122 #[doc = concat!("Requires the `", $rfq_v2_feature, "` feature.")]
123 RfqV2Api {
124 status: u16,
125 code: String,
126 message: String,
127 } = "RFQ v2 API error ({status}, {code}): {message}",
128 #[doc = ""]
130 #[doc = concat!("Requires the `", $rfq_v2_feature, "` feature.")]
131 RfqV2ChangeFeedCursor {
132 after_sequence: u64,
133 next_after_sequence: u64,
134 has_more: bool,
135 } = "RFQ v2 change feed cursor did not advance after {after_sequence}: next {next_after_sequence}, has_more {has_more}",
136 #[doc = ""]
140 #[doc = concat!("Requires the `", $rfq_v2_feature, "` feature.")]
141 RfqV2ProtocolViolation(String) = "RFQ v2 protocol violation: {_0}",
142 #[doc = ""]
150 #[doc = concat!("Requires the `", $rfq_v2_feature, "` feature.")]
151 RfqV2SubmissionAmbiguous {
152 rfq_id: Option<Uuid>,
153 operation_id: Uuid,
154 #[source]
155 source: Box<ClientError>,
156 } = "RFQ v2 submission outcome is unknown for operation {operation_id} (RFQ {rfq_id:?}): {source}; reconcile or retry only the identical signed request",
157 )?
158 ApiSource {
160 status: u16,
161 #[source]
162 source: BoxClientSource,
163 } = "API error ({status}): {source}",
164 WebSocket(String) = "WebSocket error: {_0}",
166 InvalidInput(String) = "invalid input: {_0}",
168 InvalidInputSource {
170 context: String,
171 #[source]
172 source: BoxClientSource,
173 } = "invalid input: invalid {context}: {source}",
174 RfqInput(#[source] RfqInputError) = "API error (0): {_0}",
176 Onchain {
178 operation: String,
179 #[source]
180 source: BoxClientSource,
181 } = "failed to {operation}: {source}",
182 TransactionReverted {
184 operation: &'static str,
185 transaction_hash: Option<B256>,
186 } = (
187 "{operation} transaction{} reverted",
188 transaction_hash_display_fragment(operation, transaction_hash.as_ref()),
189 ),
190 MissingAccountCreatedEvent = "confirmed Factory transaction did not emit AccountCreated",
192 AccountCreatedManagerMismatch {
194 observed: Address,
195 expected: Address,
196 } = "AccountCreated manager {observed} does not match submitting manager {expected}",
197 AccountCreatedAddressMismatch {
199 observed: Address,
200 expected: Address,
201 } = "AccountCreated account {observed} does not match simulated account {expected}",
202 ArithmeticOverflow { operation: &'static str } = "{operation} overflow",
204 WithdrawalSubmissionAmbiguous {
206 action: String,
207 route: String,
208 account: AccountAddress,
209 destination: AccountAddress,
210 destination_dex: Option<u32>,
211 amount: String,
212 nonce: u64,
213 #[source]
214 source: Box<ClientError>,
215 } = "{action} submission outcome is unknown: route={route}, account={account}, destination={destination}, destination_dex={destination_dex:?}, amount={amount}, nonce={nonce}, submission_error={source}; reconcile or retry only with these identical fields",
216 TeeSubmissionAmbiguous {
225 action: String,
226 route: String,
227 nonce: u64,
228 request_json: String,
229 #[source]
230 source: Box<ClientError>,
231 } = "{action} submission outcome is unknown: route={route}, nonce={nonce}, submission_error={source}; reconcile, or resend only the identical signed request={request_json}",
232 TransactionSubmissionUnknown {
234 operation: String,
235 transaction_hash: B256,
236 #[source]
237 source: BoxClientSource,
238 } = "{operation} submission outcome is unknown: hash={transaction_hash}, rpc_error={source}; reconcile this transaction before retrying",
239 TransactionConfirmationUnknown {
241 operation: String,
242 transaction_hash: B256,
243 #[source]
244 source: BoxClientSource,
245 } = "{operation} {transaction_hash} was broadcast, but confirmation is unknown: {source}; reconcile this transaction before retrying",
246 MissingTransactionBlock { transaction_hash: B256 } =
248 "confirmed Hypercall USDC deposit transaction {transaction_hash} has no block number",
249 }
250 };
251}
252
253#[cfg(feature = "rfq-v2")]
254client_error_enum!("rfq-v2");
255
256#[cfg(not(feature = "rfq-v2"))]
257client_error_enum! {}
258
259impl ClientError {
260 pub fn signing(
262 operation: impl Into<String>,
263 source: impl Error + Send + Sync + 'static,
264 ) -> Self {
265 Self::Signing {
266 operation: operation.into(),
267 source: Box::new(source),
268 }
269 }
270
271 pub fn api_source(status: u16, source: impl Error + Send + Sync + 'static) -> Self {
273 Self::ApiSource {
274 status,
275 source: Box::new(source),
276 }
277 }
278
279 pub fn invalid_input(
281 context: impl Into<String>,
282 source: impl Error + Send + Sync + 'static,
283 ) -> Self {
284 Self::InvalidInputSource {
285 context: context.into(),
286 source: Box::new(source),
287 }
288 }
289
290 pub fn api_error_code(&self) -> Option<String> {
297 let Self::Api { message, .. } = self else {
298 return None;
299 };
300 let body = &message[message.find('{')?..];
302 let value: serde_json::Value = serde_json::from_str(body).ok()?;
303 value.get("code")?.as_str().map(str::to_owned)
304 }
305
306 pub fn is_unsupported_action(&self) -> bool {
311 self.api_error_code().as_deref() == Some("unsupported_action")
312 }
313
314 pub fn is_connection_error(&self) -> bool {
317 match self {
318 Self::Http(e) => e.is_connect() || e.is_timeout(),
319 _ => false,
320 }
321 }
322}
323
324pub type Result<T> = std::result::Result<T, ClientError>;
326
327fn transaction_hash_display_fragment(operation: &str, transaction_hash: Option<&B256>) -> String {
332 if operation == "Factory account creation" {
333 return String::new();
334 }
335
336 transaction_hash
337 .map(|transaction_hash| format!(" {transaction_hash}"))
338 .unwrap_or_default()
339}
340
341#[cfg(test)]
342#[path = "error_test.rs"]
343mod tests;