1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
//! Error and result types shared by every exchange.
use std::fmt;
use crate::Feature;
/// Result type returned by every fallible `maxt` operation.
pub type Result<T> = std::result::Result<T, Error>;
/// Local request, adapter, authentication, exchange, transport, and decoding failures.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
/// A request field failed validation.
///
/// Retrying the same request unchanged returns the same error.
InvalidRequest {
/// The request field that failed validation.
field: String,
/// What was wrong with it.
detail: String,
},
/// A cross-exchange transfer failed local safety validation.
Transfer {
/// Stable transfer failure category.
kind: TransferErrorKind,
/// Human-readable validation detail.
detail: String,
},
/// The adapter does not map this feature or request shape.
///
/// Retrying the same request or adding credentials cannot change this
/// result. The exchange may still expose a native API outside `maxt`.
Unsupported {
/// The unmapped feature.
feature: Feature,
/// The configured exchange.
exchange: &'static str,
/// Mapping details and any available alternative.
detail: String,
},
/// An adapter or foreign dispatcher violated the [`Adapter`](crate::Adapter)
/// contract.
Adapter {
/// What contract boundary failed.
detail: String,
},
/// A credentialed request could not be built locally, so none was sent.
Auth {
/// Credential or signing failure.
detail: String,
},
/// Error response from the exchange, including rejected credentials.
Exchange {
/// The exchange that answered.
exchange: &'static str,
/// Provider error code or event name.
code: String,
/// Provider error message.
message: String,
/// HTTP status when available.
status: Option<u16>,
/// How the error classifies for retry purposes.
kind: ExchangeErrorKind,
},
/// The request never completed: DNS, TLS, socket, or timeout.
Transport {
/// What failed about the connection.
detail: String,
},
/// The response payload could not be decoded.
Decode {
/// Decode failure.
detail: String,
},
}
impl Error {
/// Whether retrying the identical request could plausibly succeed.
///
/// Returns `true` for rate limits, exchange unavailability, and transport
/// failures. A rejected request is `false`, even when rebuilding a request
/// with a fresh timestamp could succeed.
pub fn is_retryable(&self) -> bool {
match self {
Self::Exchange { kind, .. } => kind.is_retryable(),
Self::Transport { .. } => true,
Self::InvalidRequest { .. }
| Self::Transfer { .. }
| Self::Unsupported { .. }
| Self::Adapter { .. }
| Self::Auth { .. }
| Self::Decode { .. } => false,
}
}
/// Whether the exchange refused because the caller sent requests too fast.
///
/// Worth branching on separately from [`Error::is_retryable`]: a rate limit
/// asks for a longer pause than a transport blip does.
pub fn is_rate_limited(&self) -> bool {
matches!(
self,
Self::Exchange {
kind: ExchangeErrorKind::RateLimited,
..
}
)
}
pub(crate) fn invalid_request(field: impl Into<String>, detail: impl Into<String>) -> Self {
Self::InvalidRequest {
field: field.into(),
detail: detail.into(),
}
}
pub(crate) fn transfer(kind: TransferErrorKind, detail: impl Into<String>) -> Self {
Self::Transfer {
kind,
detail: detail.into(),
}
}
pub(crate) fn unsupported(
feature: Feature,
exchange: &'static str,
detail: impl Into<String>,
) -> Self {
Self::Unsupported {
feature,
exchange,
detail: detail.into(),
}
}
/// Builds an adapter contract error.
pub fn adapter(detail: impl Into<String>) -> Self {
Self::Adapter {
detail: detail.into(),
}
}
pub(crate) fn auth(detail: impl Into<String>) -> Self {
Self::Auth {
detail: detail.into(),
}
}
pub(crate) fn transport(detail: impl Into<String>) -> Self {
Self::Transport {
detail: detail.into(),
}
}
pub(crate) fn decode(detail: impl Into<String>) -> Self {
Self::Decode {
detail: detail.into(),
}
}
pub(crate) fn exchange(
exchange: &'static str,
code: impl Into<String>,
message: impl Into<String>,
) -> Self {
Self::Exchange {
exchange,
code: code.into(),
message: message.into(),
status: None,
kind: ExchangeErrorKind::Unknown,
}
}
pub(crate) fn exchange_http(
exchange: &'static str,
status: u16,
code: impl Into<String>,
message: impl Into<String>,
) -> Self {
Self::Exchange {
exchange,
code: code.into(),
message: message.into(),
status: Some(status),
kind: ExchangeErrorKind::from_status(status),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidRequest { field, detail } => {
write!(f, "invalid request: `{field}`: {detail}")
}
Self::Transfer { kind, detail } => write!(f, "transfer {kind}: {detail}"),
Self::Unsupported {
feature,
exchange,
detail,
} => write!(f, "{exchange} adapter does not support {feature}: {detail}"),
Self::Adapter { detail } => write!(f, "adapter failed: {detail}"),
Self::Auth { detail } => write!(f, "authentication failed: {detail}"),
Self::Exchange {
exchange,
code,
message,
status,
..
} => match status {
Some(status) => write!(f, "{exchange} returned {status} {code}: {message}"),
None => write!(f, "{exchange} returned {code}: {message}"),
},
Self::Transport { detail } => write!(f, "transport failed: {detail}"),
Self::Decode { detail } => write!(f, "could not read exchange response: {detail}"),
}
}
}
impl std::error::Error for Error {}
/// Why a transfer was rejected before a withdrawal was submitted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TransferErrorKind {
/// Source and destination assets differ.
AssetMismatch,
/// Source and destination identify different chains.
NetworkMismatch,
/// More than one compatible chain is available and none was selected.
AmbiguousNetwork,
/// The selected chain is not currently available for the asset.
NetworkUnavailable,
/// The destination requires a memo or tag that is absent.
MemoRequired,
/// An exchange has not issued a usable destination address yet.
DestinationUnavailable,
/// The destination address is not allowed by the source account.
AddressNotAllowed,
/// Provider-specific Travel Rule information is required.
TravelRuleRequired,
/// The amount violates a current transfer rule.
AmountOutOfRange,
/// The checked transfer plan has expired.
PlanExpired,
}
impl fmt::Display for TransferErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::AssetMismatch => "asset mismatch",
Self::NetworkMismatch => "network mismatch",
Self::AmbiguousNetwork => "network is ambiguous",
Self::NetworkUnavailable => "network is unavailable",
Self::MemoRequired => "memo is required",
Self::DestinationUnavailable => "destination is unavailable",
Self::AddressNotAllowed => "address is not allowed",
Self::TravelRuleRequired => "requires Travel Rule data",
Self::AmountOutOfRange => "amount is out of range",
Self::PlanExpired => "plan expired",
})
}
}
/// How an exchange-side error classifies for retry purposes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ExchangeErrorKind {
/// The request was wrong: a bad symbol, an insufficient balance, a
/// signature or a credential the exchange would not accept.
///
/// This includes timestamps outside the exchange's receive window. Retrying
/// the identical signed request cannot refresh its timestamp.
Rejected,
/// The caller exceeded a rate limit or is temporarily banned.
RateLimited,
/// The exchange failed on its own side.
Unavailable,
/// The exchange did not classify the failure.
Unknown,
}
impl ExchangeErrorKind {
/// Whether an error of this kind is worth retrying behind a backoff.
pub fn is_retryable(self) -> bool {
matches!(self, Self::RateLimited | Self::Unavailable)
}
fn from_status(status: u16) -> Self {
match status {
// 418 is Binance's "you ignored 429 and kept going" ban response.
418 | 429 => Self::RateLimited,
400..=499 => Self::Rejected,
500..=599 => Self::Unavailable,
_ => Self::Unknown,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn retry_classification_follows_http_status() {
let cases = [
(429, ExchangeErrorKind::RateLimited, true),
(418, ExchangeErrorKind::RateLimited, true),
(503, ExchangeErrorKind::Unavailable, true),
(400, ExchangeErrorKind::Rejected, false),
(401, ExchangeErrorKind::Rejected, false),
];
for (status, expected_kind, expected_retryable) in cases {
let error = Error::exchange_http("upbit", status, "code", "message");
let Error::Exchange { kind, .. } = error else {
panic!("expected an exchange error for status {status}");
};
assert_eq!(kind, expected_kind, "status {status}");
assert_eq!(error.is_retryable(), expected_retryable, "status {status}");
}
}
#[test]
fn caller_side_errors_are_never_retryable() {
assert!(!Error::invalid_request("limit", "must be 1..=200").is_retryable());
assert!(!Error::auth("missing secret key").is_retryable());
assert!(!Error::decode("unexpected null in `price`").is_retryable());
assert!(
!Error::unsupported(Feature::CandleStream, "bithumb", "no public candle stream")
.is_retryable()
);
}
#[test]
fn invalid_request_keeps_a_runtime_defined_field_name() {
let field = format!("custom_{}", "field");
let error = Error::invalid_request(field.clone(), "bad value");
assert!(matches!(
error,
Error::InvalidRequest { field: actual, .. } if actual == field
));
}
#[test]
fn rate_limit_is_distinguishable_from_other_retryable_errors() {
assert!(
Error::exchange_http("binance", 429, "-1003", "too many requests").is_rate_limited()
);
assert!(!Error::exchange_http("binance", 503, "-1001", "disconnected").is_rate_limited());
assert!(!Error::transport("connection reset").is_rate_limited());
assert!(Error::transport("connection reset").is_retryable());
}
#[test]
fn display_keeps_the_exchange_verdict_verbatim() {
let error = Error::exchange_http("binance", 400, "-1121", "Invalid symbol.");
assert_eq!(
error.to_string(),
"binance returned 400 -1121: Invalid symbol."
);
}
}