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    NetPremiumConversion {
71        #[source]
72        source: BoxClientSource,
73    } = "net_premium I256 conversion failed: {source}",
74}
75
76/// A closed reason why the configured signer cannot perform an operation.
77///
78/// These variants preserve the public diagnostics that predate the typed
79/// client-error migration without accepting arbitrary string-wrapped errors.
80#[derive(Debug, thiserror::Error)]
81#[displaystr::display]
82pub enum SigningUnavailableReason {
83    AwsKmsPrivateKeyMaterial = "private key material is unavailable for AWS KMS wallets",
84    HyperliquidMockApiUnauthenticated = "Hyperliquid mock API is not authenticated",
85    HyperliquidSimulationVenueUnauthenticated = "Hyperliquid simulation venue is not authenticated",
86}
87
88// `displaystr` builds its `Display` match from the raw variant list and does
89// not honor `#[cfg]` on variants, so the enum is emitted through this macro
90// with or without the `rfq-v2` variants. The variants stay in the macro body
91// (not passed in by the caller) so their `{_0}` format captures share the
92// hygiene context of the bindings `displaystr` generates.
93macro_rules! client_error_enum {
94    ($($rfq_v2_feature:literal)?) => {
95        /// Client error type.
96        #[derive(Debug, thiserror::Error)]
97        #[displaystr::display]
98        pub enum ClientError {
99            /// HTTP request failed
100            Http(#[from] reqwest::Error) = "HTTP error: {_0}",
101            /// JSON serialization/deserialization failed
102            Json(#[from] sonic_rs::Error) = "JSON error: {_0}",
103            /// Decoding an inbound server frame failed. Inbound frames are parsed
104            /// with Serde, whose default recursion limit bounds hostile nesting.
105            InboundJson(#[from] serde_json::Error) = "inbound JSON decode error: {_0}",
106            /// A concrete signing operation failed.
107            Signing {
108                operation: String,
109                #[source]
110                source: BoxClientSource,
111            } = "Signing error: {operation}: {source}",
112            /// The selected signer cannot perform the requested operation.
113            SigningUnavailable(#[source] SigningUnavailableReason) = "Signing error: {_0}",
114            /// API returned an error
115            Api { status: u16, message: String } = "API error ({status}): {message}",
116            $(
117                /// RFQ v2 response with its machine-readable domain code preserved.
118                #[doc = ""]
119                #[doc = concat!("Requires the `", $rfq_v2_feature, "` feature.")]
120                RfqV2Api {
121                    status: u16,
122                    code: String,
123                    message: String,
124                } = "RFQ v2 API error ({status}, {code}): {message}",
125                /// The signed change feed returned a non-progressing global cursor.
126                #[doc = ""]
127                #[doc = concat!("Requires the `", $rfq_v2_feature, "` feature.")]
128                RfqV2ChangeFeedCursor {
129                    after_sequence: u64,
130                    next_after_sequence: u64,
131                    has_more: bool,
132                } = "RFQ v2 change feed cursor did not advance after {after_sequence}: next {next_after_sequence}, has_more {has_more}",
133                /// An RFQ v2 read broke a durable contract: a quote delivered twice
134                /// across pages, retained history that vanished, or a page with more
135                /// results and no cursor.
136                #[doc = ""]
137                #[doc = concat!("Requires the `", $rfq_v2_feature, "` feature.")]
138                RfqV2ProtocolViolation(String) = "RFQ v2 protocol violation: {_0}",
139                /// A mutation may have been applied: the request timed out,
140                /// failed in transport, or got a 5xx. `rfq_id` is `None` for
141                /// maker-wide actions (bulk withdrawal, cancel schedule).
142                /// `operation_id` is the stable identity of the request: the
143                /// object ID for create and publish, the operation ID
144                /// otherwise. Reconcile by these IDs or resend only the
145                /// identical signed request.
146                #[doc = ""]
147                #[doc = concat!("Requires the `", $rfq_v2_feature, "` feature.")]
148                RfqV2SubmissionAmbiguous {
149                    rfq_id: Option<Uuid>,
150                    operation_id: Uuid,
151                    #[source]
152                    source: Box<ClientError>,
153                } = "RFQ v2 submission outcome is unknown for operation {operation_id} (RFQ {rfq_id:?}): {source}; reconcile or retry only the identical signed request",
154            )?
155            /// An API-shaped external response failed while retaining its concrete source.
156            ApiSource {
157                status: u16,
158                #[source]
159                source: BoxClientSource,
160            } = "API error ({status}): {source}",
161            /// WebSocket error
162            WebSocket(String) = "WebSocket error: {_0}",
163            /// Invalid input
164            InvalidInput(String) = "invalid input: {_0}",
165            /// A concrete parser or validator rejected caller-provided input.
166            InvalidInputSource {
167                context: String,
168                #[source]
169                source: BoxClientSource,
170            } = "invalid input: invalid {context}: {source}",
171            /// Caller-side RFQ validation with the legacy public diagnostic text.
172            RfqInput(#[source] RfqInputError) = "API error (0): {_0}",
173            /// A typed failure returned by the HyperEVM provider or contract binding.
174            Onchain {
175                operation: String,
176                #[source]
177                source: BoxClientSource,
178            } = "failed to {operation}: {source}",
179            /// A submitted transaction was confirmed as reverted.
180            TransactionReverted {
181                operation: &'static str,
182                transaction_hash: Option<B256>,
183            } = (
184                "{operation} transaction{} reverted",
185                transaction_hash_display_fragment(operation, transaction_hash.as_ref()),
186            ),
187            /// A confirmed Factory transaction omitted its required creation event.
188            MissingAccountCreatedEvent = "confirmed Factory transaction did not emit AccountCreated",
189            /// The Factory event named a different manager from the submitting wallet.
190            AccountCreatedManagerMismatch {
191                observed: Address,
192                expected: Address,
193            } = "AccountCreated manager {observed} does not match submitting manager {expected}",
194            /// The Factory event named an account different from the simulated address.
195            AccountCreatedAddressMismatch {
196                observed: Address,
197                expected: Address,
198            } = "AccountCreated account {observed} does not match simulated account {expected}",
199            /// A checked client-side calculation overflowed.
200            ArithmeticOverflow { operation: &'static str } = "{operation} overflow",
201            /// An HTTP withdrawal request may have reached the server before failing.
202            WithdrawalSubmissionAmbiguous {
203                action: String,
204                route: String,
205                account: AccountAddress,
206                destination: AccountAddress,
207                destination_dex: Option<u32>,
208                amount: String,
209                nonce: u64,
210                #[source]
211                source: Box<ClientError>,
212            } = "{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",
213            /// A signed TEE perp (or TEE API wallet) submission may have reached the
214            /// server before failing: a transport error, a timeout, a `5xx`, or a
215            /// `2xx` whose body did not decode. `request_json` is the exact signed
216            /// body that was sent. Reconcile from venue or directive state, or resend
217            /// exactly these bytes with
218            /// [`HypercallClient::resend_tee_submission`](crate::HypercallClient::resend_tee_submission),
219            /// which the server deduplicates. Never re-run the high-level method: a
220            /// fresh nonce (and nonce-derived cloids) would sign a second action.
221            TeeSubmissionAmbiguous {
222                action: String,
223                route: String,
224                nonce: u64,
225                request_json: String,
226                #[source]
227                source: Box<ClientError>,
228            } = "{action} submission outcome is unknown: route={route}, nonce={nonce}, submission_error={source}; reconcile, or resend only the identical signed request={request_json}",
229            /// A broadcast transaction has an unknown submission outcome.
230            TransactionSubmissionUnknown {
231                operation: String,
232                transaction_hash: B256,
233                #[source]
234                source: BoxClientSource,
235            } = "{operation} submission outcome is unknown: hash={transaction_hash}, rpc_error={source}; reconcile this transaction before retrying",
236            /// A broadcast transaction has an unknown confirmation outcome.
237            TransactionConfirmationUnknown {
238                operation: String,
239                transaction_hash: B256,
240                #[source]
241                source: BoxClientSource,
242            } = "{operation} {transaction_hash} was broadcast, but confirmation is unknown: {source}; reconcile this transaction before retrying",
243            /// A confirmed receipt omitted its required block number.
244            MissingTransactionBlock { transaction_hash: B256 } =
245                "confirmed Hypercall USDC deposit transaction {transaction_hash} has no block number",
246        }
247    };
248}
249
250#[cfg(feature = "rfq-v2")]
251client_error_enum!("rfq-v2");
252
253#[cfg(not(feature = "rfq-v2"))]
254client_error_enum! {}
255
256impl ClientError {
257    /// Add operation context without discarding the concrete signer error.
258    pub fn signing(
259        operation: impl Into<String>,
260        source: impl Error + Send + Sync + 'static,
261    ) -> Self {
262        Self::Signing {
263            operation: operation.into(),
264            source: Box::new(source),
265        }
266    }
267
268    /// Preserve the legacy API error boundary without flattening the source.
269    pub fn api_source(status: u16, source: impl Error + Send + Sync + 'static) -> Self {
270        Self::ApiSource {
271            status,
272            source: Box::new(source),
273        }
274    }
275
276    /// Add input context without discarding the concrete parser error.
277    pub fn invalid_input(
278        context: impl Into<String>,
279        source: impl Error + Send + Sync + 'static,
280    ) -> Self {
281        Self::InvalidInputSource {
282            context: context.into(),
283            source: Box::new(source),
284        }
285    }
286
287    /// The stable `code` of an API error body (`{"code": ..., "message": ...}`),
288    /// when this is an [`ClientError::Api`] whose body carries one.
289    ///
290    /// For example `unsupported_action`, which the TEE perp routes return
291    /// (HTTP 400) when the admitted enclave release does not enable an action
292    /// kind such as TWAP or batch modify.
293    pub fn api_error_code(&self) -> Option<String> {
294        let Self::Api { message, .. } = self else {
295            return None;
296        };
297        // `ensure_success` prefixes the body with the action and ": ".
298        let body = &message[message.find('{')?..];
299        let value: serde_json::Value = serde_json::from_str(body).ok()?;
300        value.get("code")?.as_str().map(str::to_owned)
301    }
302
303    /// Whether the server refused the request because this deployment does
304    /// not enable the action (`400 unsupported_action`). Nothing was signed
305    /// at the venue or reserved; retrying the same action will not help until
306    /// the operator enables it.
307    pub fn is_unsupported_action(&self) -> bool {
308        self.api_error_code().as_deref() == Some("unsupported_action")
309    }
310
311    /// Returns true if this error indicates a connection-level failure
312    /// (TCP connect error or request timeout), as opposed to an HTTP response error.
313    pub fn is_connection_error(&self) -> bool {
314        match self {
315            Self::Http(e) => e.is_connect() || e.is_timeout(),
316            _ => false,
317        }
318    }
319}
320
321/// Result type alias for client operations.
322pub type Result<T> = std::result::Result<T, ClientError>;
323
324/// Keep the pre-typed-error public text while retaining a structured hash for
325/// reconciliation. Factory creation historically omitted its confirmed hash;
326/// the funding operations placed the hash between `transaction` and
327/// `reverted`.
328fn transaction_hash_display_fragment(operation: &str, transaction_hash: Option<&B256>) -> String {
329    if operation == "Factory account creation" {
330        return String::new();
331    }
332
333    transaction_hash
334        .map(|transaction_hash| format!(" {transaction_hash}"))
335        .unwrap_or_default()
336}
337
338#[cfg(test)]
339#[path = "error_test.rs"]
340mod tests;