Skip to main content

hypercall_client/
error.rs

1//! Error types for the Hypercall client SDK.
2//!
3//! All fallible operations return [`Result<T>`](crate::error::Result) which uses
4//! [`ClientError`] as the error type.
5//!
6//! # Error Variants
7//!
8//! - [`ClientError::Api`]: server returned an error (4xx/5xx with message)
9//! - [`ClientError::Http`]: network/transport failure
10//! - [`ClientError::Signing`]: EIP-712 signature creation failed
11//! - [`ClientError::InvalidInput`]: bad input (unknown symbol, invalid key, etc)
12//! - [`ClientError::WebSocket`]: WS connection or message failure
13
14use std::error::Error;
15
16use alloy::primitives::{Address, B256};
17#[cfg(feature = "rfq-v2")]
18use uuid::Uuid;
19
20use crate::wallet::AccountAddress;
21
22/// Dynamically typed source retained by a public client error.
23pub type BoxClientSource = Box<dyn Error + Send + Sync + 'static>;
24
25/// Caller-side RFQ validation failures.
26///
27/// These remain a local-input classification even though their `Display`
28/// contract is wrapped in the historical `API error (0)` text below. Existing
29/// SDK users may persist or surface that text, so the representation migration
30/// must not silently rewrite it.
31#[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/// A closed reason why the configured signer cannot perform an operation.
80///
81/// These variants preserve the public diagnostics that predate the typed
82/// client-error migration without accepting arbitrary string-wrapped errors.
83#[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
91// `displaystr` builds its `Display` match from the raw variant list and does
92// not honor `#[cfg]` on variants, so the enum is emitted through this macro
93// with or without the `rfq-v2` variants. The variants stay in the macro body
94// (not passed in by the caller) so their `{_0}` format captures share the
95// hygiene context of the bindings `displaystr` generates.
96macro_rules! client_error_enum {
97    ($($rfq_v2_feature:literal)?) => {
98        /// Client error type.
99        #[derive(Debug, thiserror::Error)]
100        #[displaystr::display]
101        pub enum ClientError {
102            /// HTTP request failed
103            Http(#[from] reqwest::Error) = "HTTP error: {_0}",
104            /// JSON serialization/deserialization failed
105            Json(#[from] sonic_rs::Error) = "JSON error: {_0}",
106            /// Decoding an inbound server frame failed. Inbound frames are parsed
107            /// with Serde, whose default recursion limit bounds hostile nesting.
108            InboundJson(#[from] serde_json::Error) = "inbound JSON decode error: {_0}",
109            /// A concrete signing operation failed.
110            Signing {
111                operation: String,
112                #[source]
113                source: BoxClientSource,
114            } = "Signing error: {operation}: {source}",
115            /// The selected signer cannot perform the requested operation.
116            SigningUnavailable(#[source] SigningUnavailableReason) = "Signing error: {_0}",
117            /// API returned an error
118            Api { status: u16, message: String } = "API error ({status}): {message}",
119            $(
120                /// RFQ v2 response with its machine-readable domain code preserved.
121                #[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                /// The signed change feed returned a non-progressing global cursor.
129                #[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                /// An RFQ v2 read broke a durable contract: a quote delivered twice
137                /// across pages, retained history that vanished, or a page with more
138                /// results and no cursor.
139                #[doc = ""]
140                #[doc = concat!("Requires the `", $rfq_v2_feature, "` feature.")]
141                RfqV2ProtocolViolation(String) = "RFQ v2 protocol violation: {_0}",
142                /// A mutation may have been applied: the request timed out,
143                /// failed in transport, or got a 5xx. `rfq_id` is `None` for
144                /// maker-wide actions (bulk withdrawal, cancel schedule).
145                /// `operation_id` is the stable identity of the request: the
146                /// object ID for create and publish, the operation ID
147                /// otherwise. Reconcile by these IDs or resend only the
148                /// identical signed request.
149                #[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            /// An API-shaped external response failed while retaining its concrete source.
159            ApiSource {
160                status: u16,
161                #[source]
162                source: BoxClientSource,
163            } = "API error ({status}): {source}",
164            /// WebSocket error
165            WebSocket(String) = "WebSocket error: {_0}",
166            /// Invalid input
167            InvalidInput(String) = "invalid input: {_0}",
168            /// A concrete parser or validator rejected caller-provided input.
169            InvalidInputSource {
170                context: String,
171                #[source]
172                source: BoxClientSource,
173            } = "invalid input: invalid {context}: {source}",
174            /// Caller-side RFQ validation with the legacy public diagnostic text.
175            RfqInput(#[source] RfqInputError) = "API error (0): {_0}",
176            /// A typed failure returned by the HyperEVM provider or contract binding.
177            Onchain {
178                operation: String,
179                #[source]
180                source: BoxClientSource,
181            } = "failed to {operation}: {source}",
182            /// A submitted transaction was confirmed as reverted.
183            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            /// A confirmed Factory transaction omitted its required creation event.
191            MissingAccountCreatedEvent = "confirmed Factory transaction did not emit AccountCreated",
192            /// The Factory event named a different manager from the submitting wallet.
193            AccountCreatedManagerMismatch {
194                observed: Address,
195                expected: Address,
196            } = "AccountCreated manager {observed} does not match submitting manager {expected}",
197            /// The Factory event named an account different from the simulated address.
198            AccountCreatedAddressMismatch {
199                observed: Address,
200                expected: Address,
201            } = "AccountCreated account {observed} does not match simulated account {expected}",
202            /// A checked client-side calculation overflowed.
203            ArithmeticOverflow { operation: &'static str } = "{operation} overflow",
204            /// An HTTP withdrawal request may have reached the server before failing.
205            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            /// A signed TEE perp (or TEE API wallet) submission may have reached the
217            /// server before failing: a transport error, a timeout, a `5xx`, or a
218            /// `2xx` whose body did not decode. `request_json` is the exact signed
219            /// body that was sent. Reconcile from venue or directive state, or resend
220            /// exactly these bytes with
221            /// [`HypercallClient::resend_tee_submission`](crate::HypercallClient::resend_tee_submission),
222            /// which the server deduplicates. Never re-run the high-level method: a
223            /// fresh nonce (and nonce-derived cloids) would sign a second action.
224            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            /// A broadcast transaction has an unknown submission outcome.
233            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            /// A broadcast transaction has an unknown confirmation outcome.
240            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            /// A confirmed receipt omitted its required block number.
247            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    /// Add operation context without discarding the concrete signer error.
261    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    /// Preserve the legacy API error boundary without flattening the source.
272    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    /// Add input context without discarding the concrete parser error.
280    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    /// The stable `code` of an API error body (`{"code": ..., "message": ...}`),
291    /// when this is an [`ClientError::Api`] whose body carries one.
292    ///
293    /// For example `unsupported_action`, which the TEE perp routes return
294    /// (HTTP 400) when the admitted enclave release does not enable an action
295    /// kind such as TWAP or batch modify.
296    pub fn api_error_code(&self) -> Option<String> {
297        let Self::Api { message, .. } = self else {
298            return None;
299        };
300        // `ensure_success` prefixes the body with the action and ": ".
301        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    /// Whether the server refused the request because this deployment does
307    /// not enable the action (`400 unsupported_action`). Nothing was signed
308    /// at the venue or reserved; retrying the same action will not help until
309    /// the operator enables it.
310    pub fn is_unsupported_action(&self) -> bool {
311        self.api_error_code().as_deref() == Some("unsupported_action")
312    }
313
314    /// Returns true if this error indicates a connection-level failure
315    /// (TCP connect error or request timeout), as opposed to an HTTP response error.
316    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
324/// Result type alias for client operations.
325pub type Result<T> = std::result::Result<T, ClientError>;
326
327/// Keep the pre-typed-error public text while retaining a structured hash for
328/// reconciliation. Factory creation historically omitted its confirmed hash;
329/// the funding operations placed the hash between `transaction` and
330/// `reverted`.
331fn 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;