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 NetPremiumConversion {
71 #[source]
72 source: BoxClientSource,
73 } = "net_premium I256 conversion failed: {source}",
74}
75
76#[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
88macro_rules! client_error_enum {
94 ($($rfq_v2_feature:literal)?) => {
95 #[derive(Debug, thiserror::Error)]
97 #[displaystr::display]
98 pub enum ClientError {
99 Http(#[from] reqwest::Error) = "HTTP error: {_0}",
101 Json(#[from] sonic_rs::Error) = "JSON error: {_0}",
103 InboundJson(#[from] serde_json::Error) = "inbound JSON decode error: {_0}",
106 Signing {
108 operation: String,
109 #[source]
110 source: BoxClientSource,
111 } = "Signing error: {operation}: {source}",
112 SigningUnavailable(#[source] SigningUnavailableReason) = "Signing error: {_0}",
114 Api { status: u16, message: String } = "API error ({status}): {message}",
116 $(
117 #[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 #[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 #[doc = ""]
137 #[doc = concat!("Requires the `", $rfq_v2_feature, "` feature.")]
138 RfqV2ProtocolViolation(String) = "RFQ v2 protocol violation: {_0}",
139 #[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 ApiSource {
157 status: u16,
158 #[source]
159 source: BoxClientSource,
160 } = "API error ({status}): {source}",
161 WebSocket(String) = "WebSocket error: {_0}",
163 InvalidInput(String) = "invalid input: {_0}",
165 InvalidInputSource {
167 context: String,
168 #[source]
169 source: BoxClientSource,
170 } = "invalid input: invalid {context}: {source}",
171 RfqInput(#[source] RfqInputError) = "API error (0): {_0}",
173 Onchain {
175 operation: String,
176 #[source]
177 source: BoxClientSource,
178 } = "failed to {operation}: {source}",
179 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 MissingAccountCreatedEvent = "confirmed Factory transaction did not emit AccountCreated",
189 AccountCreatedManagerMismatch {
191 observed: Address,
192 expected: Address,
193 } = "AccountCreated manager {observed} does not match submitting manager {expected}",
194 AccountCreatedAddressMismatch {
196 observed: Address,
197 expected: Address,
198 } = "AccountCreated account {observed} does not match simulated account {expected}",
199 ArithmeticOverflow { operation: &'static str } = "{operation} overflow",
201 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 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 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 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 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 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 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 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 pub fn api_error_code(&self) -> Option<String> {
294 let Self::Api { message, .. } = self else {
295 return None;
296 };
297 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 pub fn is_unsupported_action(&self) -> bool {
308 self.api_error_code().as_deref() == Some("unsupported_action")
309 }
310
311 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
321pub type Result<T> = std::result::Result<T, ClientError>;
323
324fn 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;