use std::error::Error;
use alloy::primitives::{Address, B256};
#[cfg(feature = "rfq-v2")]
use uuid::Uuid;
use crate::wallet::AccountAddress;
pub type BoxClientSource = Box<dyn Error + Send + Sync + 'static>;
#[derive(Debug, thiserror::Error)]
#[displaystr::display]
pub enum RfqInputError {
InvalidUuid {
label: &'static str,
#[source]
source: uuid::Error,
} = "{label}: {source}",
InvalidLegSize {
label: &'static str,
value: String,
#[source]
source: rust_decimal::Error,
} = "{label} leg size {value:?}: {source}",
LimitPriceOverflow = "limit_price overflow in micro-unit conversion",
LimitPriceConversion {
#[source]
source: BoxClientSource,
} = "limit_price I256 conversion: {source}",
NoLegs = "RFQ has no legs",
LegCountMismatch {
request_count: usize,
price_count: usize,
} = "leg count mismatch: request has {request_count} legs but {price_count} prices provided",
LegPriceNonPositive {
index: usize,
price: rust_decimal::Decimal,
} = "leg {index} price must be positive, got {price}",
LegSizeNonPositive {
index: usize,
size: rust_decimal::Decimal,
} = "leg {index} size must be positive, got {size}",
InvalidSide {
index: usize,
side: String,
} = "leg {index} has invalid side: {side:?}",
NetPremiumNotRepresentable {
net_premium: rust_decimal::Decimal,
} = "net_premium {net_premium} not representable as micro-units i64",
NetPremiumConversion {
#[source]
source: BoxClientSource,
} = "net_premium I256 conversion failed: {source}",
}
#[derive(Debug, thiserror::Error)]
#[displaystr::display]
pub enum SigningUnavailableReason {
AwsKmsPrivateKeyMaterial = "private key material is unavailable for AWS KMS wallets",
HyperliquidMockApiUnauthenticated = "Hyperliquid mock API is not authenticated",
HyperliquidSimulationVenueUnauthenticated = "Hyperliquid simulation venue is not authenticated",
}
macro_rules! client_error_enum {
($($rfq_v2_feature:literal)?) => {
#[derive(Debug, thiserror::Error)]
#[displaystr::display]
pub enum ClientError {
Http(#[from] reqwest::Error) = "HTTP error: {_0}",
Json(#[from] sonic_rs::Error) = "JSON error: {_0}",
InboundJson(#[from] serde_json::Error) = "inbound JSON decode error: {_0}",
Signing {
operation: String,
#[source]
source: BoxClientSource,
} = "Signing error: {operation}: {source}",
SigningUnavailable(#[source] SigningUnavailableReason) = "Signing error: {_0}",
Api { status: u16, message: String } = "API error ({status}): {message}",
$(
#[doc = ""]
#[doc = concat!("Requires the `", $rfq_v2_feature, "` feature.")]
RfqV2Api {
status: u16,
code: String,
message: String,
} = "RFQ v2 API error ({status}, {code}): {message}",
#[doc = ""]
#[doc = concat!("Requires the `", $rfq_v2_feature, "` feature.")]
RfqV2ChangeFeedCursor {
after_sequence: u64,
next_after_sequence: u64,
has_more: bool,
} = "RFQ v2 change feed cursor did not advance after {after_sequence}: next {next_after_sequence}, has_more {has_more}",
#[doc = ""]
#[doc = concat!("Requires the `", $rfq_v2_feature, "` feature.")]
RfqV2ProtocolViolation(String) = "RFQ v2 protocol violation: {_0}",
#[doc = ""]
#[doc = concat!("Requires the `", $rfq_v2_feature, "` feature.")]
RfqV2SubmissionAmbiguous {
rfq_id: Option<Uuid>,
operation_id: Uuid,
#[source]
source: Box<ClientError>,
} = "RFQ v2 submission outcome is unknown for operation {operation_id} (RFQ {rfq_id:?}): {source}; reconcile or retry only the identical signed request",
)?
ApiSource {
status: u16,
#[source]
source: BoxClientSource,
} = "API error ({status}): {source}",
WebSocket(String) = "WebSocket error: {_0}",
InvalidInput(String) = "invalid input: {_0}",
InvalidInputSource {
context: String,
#[source]
source: BoxClientSource,
} = "invalid input: invalid {context}: {source}",
RfqInput(#[source] RfqInputError) = "API error (0): {_0}",
Onchain {
operation: String,
#[source]
source: BoxClientSource,
} = "failed to {operation}: {source}",
TransactionReverted {
operation: &'static str,
transaction_hash: Option<B256>,
} = (
"{operation} transaction{} reverted",
transaction_hash_display_fragment(operation, transaction_hash.as_ref()),
),
MissingAccountCreatedEvent = "confirmed Factory transaction did not emit AccountCreated",
AccountCreatedManagerMismatch {
observed: Address,
expected: Address,
} = "AccountCreated manager {observed} does not match submitting manager {expected}",
AccountCreatedAddressMismatch {
observed: Address,
expected: Address,
} = "AccountCreated account {observed} does not match simulated account {expected}",
ArithmeticOverflow { operation: &'static str } = "{operation} overflow",
WithdrawalSubmissionAmbiguous {
action: String,
route: String,
account: AccountAddress,
destination: AccountAddress,
destination_dex: Option<u32>,
amount: String,
nonce: u64,
#[source]
source: Box<ClientError>,
} = "{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",
TeeSubmissionAmbiguous {
action: String,
route: String,
nonce: u64,
request_json: String,
#[source]
source: Box<ClientError>,
} = "{action} submission outcome is unknown: route={route}, nonce={nonce}, submission_error={source}; reconcile, or resend only the identical signed request={request_json}",
TransactionSubmissionUnknown {
operation: String,
transaction_hash: B256,
#[source]
source: BoxClientSource,
} = "{operation} submission outcome is unknown: hash={transaction_hash}, rpc_error={source}; reconcile this transaction before retrying",
TransactionConfirmationUnknown {
operation: String,
transaction_hash: B256,
#[source]
source: BoxClientSource,
} = "{operation} {transaction_hash} was broadcast, but confirmation is unknown: {source}; reconcile this transaction before retrying",
MissingTransactionBlock { transaction_hash: B256 } =
"confirmed Hypercall USDC deposit transaction {transaction_hash} has no block number",
}
};
}
#[cfg(feature = "rfq-v2")]
client_error_enum!("rfq-v2");
#[cfg(not(feature = "rfq-v2"))]
client_error_enum! {}
impl ClientError {
pub fn signing(
operation: impl Into<String>,
source: impl Error + Send + Sync + 'static,
) -> Self {
Self::Signing {
operation: operation.into(),
source: Box::new(source),
}
}
pub fn api_source(status: u16, source: impl Error + Send + Sync + 'static) -> Self {
Self::ApiSource {
status,
source: Box::new(source),
}
}
pub fn invalid_input(
context: impl Into<String>,
source: impl Error + Send + Sync + 'static,
) -> Self {
Self::InvalidInputSource {
context: context.into(),
source: Box::new(source),
}
}
pub fn api_error_code(&self) -> Option<String> {
let Self::Api { message, .. } = self else {
return None;
};
let body = &message[message.find('{')?..];
let value: serde_json::Value = serde_json::from_str(body).ok()?;
value.get("code")?.as_str().map(str::to_owned)
}
pub fn is_unsupported_action(&self) -> bool {
self.api_error_code().as_deref() == Some("unsupported_action")
}
pub fn is_connection_error(&self) -> bool {
match self {
Self::Http(e) => e.is_connect() || e.is_timeout(),
_ => false,
}
}
}
pub type Result<T> = std::result::Result<T, ClientError>;
fn transaction_hash_display_fragment(operation: &str, transaction_hash: Option<&B256>) -> String {
if operation == "Factory account creation" {
return String::new();
}
transaction_hash
.map(|transaction_hash| format!(" {transaction_hash}"))
.unwrap_or_default()
}
#[cfg(test)]
#[path = "error_test.rs"]
mod tests;