use std::{borrow::Cow, fmt, time::Duration};
use alloy_primitives::Address;
use crate::{
model::MakerPreparationState,
types::{BridgeId, ClientId, OrderId, PreparationId, SetupStepKind, VenueId, open_enum},
};
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("api error {0}")]
Api(Box<ApiError>),
#[error("transport error")]
Transport(#[source] TransportError),
#[error("unreadable response")]
Decode(#[source] Box<DecodeError>),
#[error("refused to sign: {0}")]
Verification(VerificationError),
#[error("signer error")]
Signer(#[source] Box<SignerError>),
#[error("store error")]
Store(#[source] Box<StoreError>),
#[error("venue api error")]
VenueApi(#[source] VenueApiError),
#[error("quote unavailable: {0}")]
QuoteUnavailable(&'static str),
#[error("invalid request: {0}")]
InvalidRequest(Cow<'static, str>),
#[error("signed out")]
SignedOut,
#[error("aster request outcome unknown")]
AsterRequestUncertain,
#[error("withdrawal {id} was refused ({code})")]
WithdrawalRefused {
id: ClientId,
code: ErrorCode,
},
#[error("order {order} failed: {reason}")]
OrderFailed {
order: OrderId,
reason: String,
},
#[error("funding {preparation} {state}: {reason}")]
FundingFailed {
preparation: PreparationId,
state: MakerPreparationState,
reason: String,
},
#[error("{venue} setup incomplete at step {step}")]
SetupIncomplete {
venue: VenueId,
step: SetupStepKind,
},
#[error("another client holds bridge {0}'s deposit: do not send")]
DepositFenced(BridgeId),
#[error("route of transfer {transfer} not committed: {reason}")]
RouteNotCommitted {
transfer: crate::types::TransferId,
reason: crate::flows::RouteNotCommitted,
commit_by: Option<chrono::DateTime<chrono::Utc>>,
},
#[error("a transaction sender is required")]
TransactionSenderRequired,
#[error("timed out waiting for {0}")]
Timeout(&'static str),
#[error("invalid configuration: {0}")]
Config(Cow<'static, str>),
}
impl From<VerificationError> for Error {
fn from(error: VerificationError) -> Self {
Self::Verification(error)
}
}
impl Error {
pub fn api(&self) -> Option<&ApiError> {
match self {
Self::Api(error) => Some(error),
_ => None,
}
}
pub fn status(&self) -> Option<u16> {
match self {
Self::Api(error) => Some(error.status),
Self::Decode(error) => error.status,
_ => None,
}
}
pub fn code(&self) -> Option<&ErrorCode> {
self.api().map(ApiError::code)
}
pub fn request_id(&self) -> Option<&str> {
match self {
Self::Api(error) => error.request_id(),
Self::Decode(error) => error.request_id(),
_ => None,
}
}
pub fn retry_after(&self) -> Option<Duration> {
self.api().and_then(ApiError::retry_after)
}
pub fn is_retryable(&self) -> bool {
match self {
Self::Transport(_) => true,
Self::Api(error) => error.retryable,
_ => false,
}
}
pub fn is_unauthenticated(&self) -> bool {
self.api()
.is_some_and(|error| error.status == 401 || error.code == ErrorCode::Unauthenticated)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApiError {
status: u16,
code: ErrorCode,
message: String,
request_id: Option<String>,
retryable: bool,
retry_after: Option<Duration>,
reason: Option<Reason>,
venue: Option<VenueId>,
step: Option<SetupStepKind>,
}
impl ApiError {
pub(crate) fn from_answer(
status: u16,
body: &[u8],
request_id: Option<String>,
retry_after: Option<Duration>,
) -> Self {
#[derive(serde::Deserialize)]
struct Envelope {
error: Body,
}
#[derive(serde::Deserialize)]
struct Body {
code: ErrorCode,
message: String,
request_id: Option<String>,
retryable: Option<bool>,
reason: Option<Reason>,
venue: Option<VenueId>,
step: Option<SetupStepKind>,
}
let default_retryable = status == 429 || status >= 500;
match serde_json::from_slice::<Envelope>(body) {
Ok(Envelope { error }) => Self {
status,
code: error.code,
message: error.message,
request_id: error.request_id.or(request_id),
retryable: error.retryable.unwrap_or(default_retryable),
retry_after,
reason: error.reason,
venue: error.venue,
step: error.step,
},
Err(_) => Self {
status,
code: ErrorCode::Unknown(crate::types::UnknownValue::new(String::new())),
message: format!("HTTP {status}"),
request_id,
retryable: default_retryable,
retry_after,
reason: None,
venue: None,
step: None,
},
}
}
pub fn status(&self) -> u16 {
self.status
}
pub fn code(&self) -> &ErrorCode {
&self.code
}
pub fn message(&self) -> &str {
&self.message
}
pub fn request_id(&self) -> Option<&str> {
self.request_id.as_deref()
}
pub fn is_retryable(&self) -> bool {
self.retryable
}
pub fn retry_after(&self) -> Option<Duration> {
self.retry_after
}
pub fn reason(&self) -> Option<&Reason> {
self.reason.as_ref()
}
pub fn venue(&self) -> Option<&VenueId> {
self.venue.as_ref()
}
pub fn step(&self) -> Option<&SetupStepKind> {
self.step.as_ref()
}
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}: {}", self.status, self.code, self.message)?;
if let Some(id) = &self.request_id {
write!(f, " (request {id})")?;
}
Ok(())
}
}
impl std::error::Error for ApiError {}
open_enum! {
pub enum ErrorCode {
ValidationError = "VALIDATION_ERROR",
BadSignature = "BAD_SIGNATURE",
WithdrawalExpired = "WITHDRAWAL_EXPIRED",
CaptchaFailed = "CAPTCHA_FAILED",
Unauthenticated = "UNAUTHENTICATED",
Forbidden = "FORBIDDEN",
AccessRequired = "ACCESS_REQUIRED",
MakerNotApproved = "MAKER_NOT_APPROVED",
NotFound = "NOT_FOUND",
MethodNotAllowed = "METHOD_NOT_ALLOWED",
StateConflict = "STATE_CONFLICT",
AccountInUse = "ACCOUNT_IN_USE",
PrefundingRequired = "PREFUNDING_REQUIRED",
StaleSequence = "STALE_SEQUENCE",
StaleQuote = "STALE_QUOTE",
InsufficientLiquidity = "INSUFFICIENT_LIQUIDITY",
Slippage = "SLIPPAGE",
FillInProgress = "FILL_IN_PROGRESS",
TakeExpired = "TAKE_EXPIRED",
ResyncRequired = "RESYNC_REQUIRED",
PayloadTooLarge = "PAYLOAD_TOO_LARGE",
VenueDisabled = "VENUE_DISABLED",
AccountNotLinked = "ACCOUNT_NOT_LINKED",
WalletNotFound = "WALLET_NOT_FOUND",
SetupRequired = "SETUP_REQUIRED",
DeliveryPending = "DELIVERY_PENDING",
RateLimited = "RATE_LIMITED",
VenueRejected = "VENUE_REJECTED",
VenueUnavailable = "VENUE_UNAVAILABLE",
Internal = "INTERNAL",
OperatorUnavailable = "OPERATOR_UNAVAILABLE",
SnapshotTooLarge = "SNAPSHOT_TOO_LARGE",
}
}
open_enum! {
pub enum Reason {
FeeAboveMax = "fee_above_max",
TooMany = "too_many",
FundsChanged = "funds_changed",
GroupedUnavailable = "grouped_unavailable",
GroupedRoute = "grouped_route",
FundsArriving = "funds_arriving",
WithdrawalSubmitted = "withdrawal_submitted",
WithdrawalUnsigned = "withdrawal_unsigned",
VenuePayment = "venue_payment",
AsterRequest = "aster_request",
NoDeposit = "no_deposit",
NotDue = "not_due",
RefundAuthorized = "refund_authorized",
ReportWindowClosed = "report_window_closed",
TransferUsed = "transfer_used",
NotATransfer = "not_a_transfer",
UnknownTransaction = "unknown_transaction",
SendUnresolved = "send_unresolved",
AmountOver = "amount_over",
BeforeFill = "before_fill",
AmountShort = "amount_short",
ExecutedLate = "executed_late",
Fenced = "fenced",
ChainUnread = "chain_unread",
ChainUnavailable = "chain_unavailable",
}
}
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct TransportError(TransportKind);
#[derive(Debug, thiserror::Error)]
enum TransportKind {
#[error("http request failed")]
Http(#[source] reqwest::Error),
#[error("websocket failed")]
WebSocket(#[source] Box<tokio_tungstenite::tungstenite::Error>),
#[error("timed out")]
Timeout,
#[error("the caller's request failed")]
Caller(#[source] Box<dyn std::error::Error + Send + Sync>),
}
impl TransportError {
pub(crate) fn http(error: reqwest::Error) -> Self {
Self(TransportKind::Http(error.without_url()))
}
pub(crate) fn websocket(error: tokio_tungstenite::tungstenite::Error) -> Self {
Self(TransportKind::WebSocket(Box::new(error)))
}
pub(crate) const fn timeout() -> Self {
Self(TransportKind::Timeout)
}
pub(crate) fn caller(error: Box<dyn std::error::Error + Send + Sync>) -> Self {
Self(TransportKind::Caller(error))
}
pub fn is_timeout(&self) -> bool {
match &self.0 {
TransportKind::Http(error) => error.is_timeout(),
TransportKind::WebSocket(_) | TransportKind::Caller(_) => false,
TransportKind::Timeout => true,
}
}
pub fn is_connect(&self) -> bool {
match &self.0 {
TransportKind::Http(error) => error.is_connect(),
TransportKind::WebSocket(error) => {
matches!(**error, tokio_tungstenite::tungstenite::Error::Io(_))
}
TransportKind::Timeout | TransportKind::Caller(_) => false,
}
}
}
#[derive(Debug)]
pub struct DecodeError {
status: Option<u16>,
request_id: Option<String>,
detail: DecodeDetail,
excerpt: Option<String>,
}
#[derive(Debug)]
enum DecodeDetail {
Json { message: Option<String>, line: usize, column: usize },
TooLarge { limit: usize },
Invalid(&'static str),
}
const EXCERPT_BYTES: usize = 1024;
impl DecodeError {
pub(crate) fn json(
status: Option<u16>,
request_id: Option<String>,
body: &[u8],
error: &serde_json::Error,
secret: bool,
) -> Self {
let excerpt = (!secret).then(|| {
let end = body.len().min(EXCERPT_BYTES);
String::from_utf8_lossy(&body[..end]).into_owned()
});
Self {
status,
request_id,
detail: DecodeDetail::Json {
message: (!secret).then(|| error.to_string()),
line: error.line(),
column: error.column(),
},
excerpt,
}
}
pub(crate) fn invalid(what: &'static str) -> Self {
Self { status: None, request_id: None, detail: DecodeDetail::Invalid(what), excerpt: None }
}
pub(crate) fn too_large(status: Option<u16>, request_id: Option<String>, limit: usize) -> Self {
Self { status, request_id, detail: DecodeDetail::TooLarge { limit }, excerpt: None }
}
pub fn status(&self) -> Option<u16> {
self.status
}
pub fn request_id(&self) -> Option<&str> {
self.request_id.as_deref()
}
pub fn excerpt(&self) -> Option<&str> {
self.excerpt.as_deref()
}
}
impl fmt::Display for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(status) = self.status {
write!(f, "HTTP {status}: ")?;
}
match &self.detail {
DecodeDetail::Json { message: Some(message), .. } => write!(f, "{message}")?,
DecodeDetail::Json { message: None, line, column } => {
write!(f, "unexpected JSON at line {line} column {column}")?;
}
DecodeDetail::TooLarge { limit } => write!(f, "body over {limit} bytes")?,
DecodeDetail::Invalid(what) => f.write_str(what)?,
}
if let Some(id) = &self.request_id {
write!(f, " (request {id})")?;
}
Ok(())
}
}
impl std::error::Error for DecodeError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct VerificationError {
pub kind: VerificationKind,
pub detail: &'static str,
pub index: Option<usize>,
}
impl fmt::Display for VerificationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.kind, self.detail)?;
if let Some(index) = self.index {
write!(f, "[{index}]")?;
}
Ok(())
}
}
impl std::error::Error for VerificationError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum VerificationKind {
Deployment,
Differs,
Stale,
Changed,
Unsupported,
}
impl fmt::Display for VerificationKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Deployment => "deployment",
Self::Differs => "differs",
Self::Stale => "stale",
Self::Changed => "changed",
Self::Unsupported => "unsupported",
})
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SignerError {
#[error("signer failed")]
Failed(#[source] alloy_signer::Error),
#[error("signature from {recovered}, expected {expected}")]
Mismatch {
expected: Address,
recovered: Address,
},
}
#[derive(Debug, thiserror::Error)]
#[error("store key {key:?}{}", if *.submitted { " (after submission)" } else { "" })]
pub struct StoreError {
key: String,
submitted: bool,
#[source]
source: std::io::Error,
}
impl StoreError {
pub(crate) fn new(key: impl Into<String>, submitted: bool, source: std::io::Error) -> Self {
Self { key: key.into(), submitted, source }
}
pub fn key(&self) -> &str {
&self.key
}
pub fn submitted(&self) -> bool {
self.submitted
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("a credential token starts with mk_")]
pub struct InvalidCredentialToken;
#[derive(Debug)]
pub struct VenueApiError {
venue: VenueId,
kind: VenueApiKind,
}
#[derive(Debug)]
enum VenueApiKind {
Unreachable(TransportError),
Status(u16),
Unreadable,
}
impl VenueApiError {
pub(crate) fn unreachable(venue: VenueId, error: TransportError) -> Self {
Self { venue, kind: VenueApiKind::Unreachable(error) }
}
pub(crate) fn answered(venue: VenueId, status: u16) -> Self {
Self { venue, kind: VenueApiKind::Status(status) }
}
pub(crate) fn unreadable(venue: VenueId) -> Self {
Self { venue, kind: VenueApiKind::Unreadable }
}
pub fn venue(&self) -> &VenueId {
&self.venue
}
pub fn status(&self) -> Option<u16> {
match self.kind {
VenueApiKind::Status(status) => Some(status),
_ => None,
}
}
pub fn is_timeout(&self) -> bool {
matches!(&self.kind, VenueApiKind::Unreachable(error) if error.is_timeout())
}
}
impl fmt::Display for VenueApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.kind {
VenueApiKind::Unreachable(_) => write!(f, "{} api unreachable", self.venue),
VenueApiKind::Status(status) => write!(f, "{} api answered HTTP {status}", self.venue),
VenueApiKind::Unreadable => write!(f, "{} api answer unreadable", self.venue),
}
}
}
impl std::error::Error for VenueApiError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
VenueApiKind::Unreachable(error) => Some(error),
_ => None,
}
}
}
#[cfg(test)]
mod tests;