forked from SO4-Markets/so4-oracle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoinbase.rs
More file actions
553 lines (487 loc) · 17.9 KB
/
Copy pathcoinbase.rs
File metadata and controls
553 lines (487 loc) · 17.9 KB
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
use serde::Deserialize;
pub const COINBASE_EXCHANGE_RATES_URL: &str =
"https://api.coinbase.com/v2/exchange-rates?currency=";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CoinbasePriceError {
NetworkError(String),
HttpError { status: u16, body: String },
JsonError(String),
PriceParseError(String),
MissingUsdRate,
CurrencyMismatch { expected: String, got: String },
}
impl std::fmt::Display for CoinbasePriceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NetworkError(error) => write!(f, "Coinbase network error: {error}"),
Self::HttpError { status, body } => {
if body.is_empty() {
write!(f, "Coinbase returned HTTP {status}")
} else {
write!(f, "Coinbase returned HTTP {status}: {body}")
}
}
Self::JsonError(error) => write!(f, "invalid Coinbase response: {error}"),
Self::PriceParseError(error) => write!(f, "invalid Coinbase price: {error}"),
Self::MissingUsdRate => f.write_str("Coinbase response has no USD rate"),
Self::CurrencyMismatch { expected, got } => {
write!(
f,
"Coinbase currency mismatch: expected '{}', got '{}'",
expected, got
)
}
}
}
}
impl std::error::Error for CoinbasePriceError {}
impl crate::retry::Retryable for CoinbasePriceError {
fn is_retryable(&self) -> bool {
match self {
// Network errors and 5xx HTTP errors are transient
Self::NetworkError(_) => true,
Self::HttpError { status, .. } => *status >= 500,
// Parse/JSON/config errors are permanent failures
Self::JsonError(_) | Self::PriceParseError(_) | Self::MissingUsdRate => false,
// Currency mismatch should not be retried - it's a data integrity issue
Self::CurrencyMismatch { .. } => false,
}
}
}
#[derive(Debug, Deserialize)]
pub struct CoinbaseRates {
pub rates: std::collections::HashMap<String, String>,
}
#[derive(Debug, Deserialize)]
pub struct CoinbaseResponse {
pub data: CoinbaseResponseData,
}
#[derive(Debug, Deserialize)]
pub struct CoinbaseResponseData {
pub currency: String,
pub rates: std::collections::HashMap<String, String>,
}
pub fn parse_coinbase_response_body(
body: &str,
expected_currency: &str,
) -> Result<i128, CoinbasePriceError> {
let resp: CoinbaseResponse =
serde_json::from_str(body).map_err(|err| CoinbasePriceError::JsonError(err.to_string()))?;
// Validate that the returned currency matches what we requested
if resp.data.currency.to_uppercase() != expected_currency.to_uppercase() {
return Err(CoinbasePriceError::CurrencyMismatch {
expected: expected_currency.to_string(),
got: resp.data.currency,
});
}
let usd_price_str = resp
.data
.rates
.get("USD")
.ok_or(CoinbasePriceError::MissingUsdRate)?;
// We can reuse the precision parsing from binance, but map the error
crate::binance::parse_price_to_precision(usd_price_str).map_err(|err| match err {
crate::binance::BinancePriceError::PriceParseError(msg) => {
CoinbasePriceError::PriceParseError(msg)
}
_ => CoinbasePriceError::PriceParseError("unknown parse error".to_string()),
})
}
pub fn parse_coinbase_http_response(
status_code: u16,
body: &str,
expected_currency: &str,
) -> Result<i128, CoinbasePriceError> {
if status_code != 200 {
return Err(CoinbasePriceError::HttpError {
status: status_code,
body: crate::http::truncate_error_body(body),
});
}
parse_coinbase_response_body(body, expected_currency)
}
pub fn parse_coinbase_http_result(
response: Result<(u16, String), String>,
expected_currency: &str,
) -> Result<i128, CoinbasePriceError> {
let (status_code, body) = response.map_err(CoinbasePriceError::NetworkError)?;
parse_coinbase_http_response(status_code, &body, expected_currency)
}
pub async fn fetch_spot_price(symbol: &str) -> Result<i128, CoinbasePriceError> {
fetch_spot_price_with_url(COINBASE_EXCHANGE_RATES_URL, symbol).await
}
pub(crate) async fn fetch_spot_price_with_url(
base_url: &str,
symbol: &str,
) -> Result<i128, CoinbasePriceError> {
// Usually the symbol passed is something like "BTC".
// If it comes with USDT/USD suffix, strip it to get the base asset.
// Guard against stripping leaving an empty string (e.g. symbol "USDT"
// or "USD" exactly) — fall back to the original symbol in that case.
let base_currency = symbol
.strip_suffix("USDT")
.or_else(|| symbol.strip_suffix("USD"))
.filter(|stripped| !stripped.is_empty())
.unwrap_or(symbol);
let (clean_url, use_query) =
if base_url.contains("currency=") || base_url.contains("exchange-rates") {
(
base_url
.trim_end_matches("?currency=")
.trim_end_matches("¤cy="),
true,
)
} else {
(base_url, false)
};
let response = if use_query {
crate::http::client()
.get(clean_url)
.query(&[("currency", base_currency)])
.send()
.await
} else {
let url_str = format!("{}{}", clean_url, base_currency);
crate::http::client().get(&url_str).send().await
}
.map_err(|err| CoinbasePriceError::NetworkError(err.to_string()))?;
let status = response.status().as_u16();
let body = response
.text()
.await
.map_err(|err| CoinbasePriceError::NetworkError(err.to_string()))?;
parse_coinbase_http_result(Ok((status, body)), base_currency)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::binance::FLOAT_PRECISION;
#[test]
fn test_parse_coinbase_response_body_success() {
let body = r#"{
"data": {
"currency": "BTC",
"rates": {
"USD": "60000.50",
"EUR": "50000.00"
}
}
}"#;
let parsed = parse_coinbase_response_body(body, "BTC").unwrap();
assert_eq!(parsed, 60000 * FLOAT_PRECISION + (FLOAT_PRECISION / 2));
}
#[test]
fn test_parse_coinbase_response_body_missing_usd() {
let body = r#"{
"data": {
"currency": "BTC",
"rates": {
"EUR": "50000.00"
}
}
}"#;
let err = parse_coinbase_response_body(body, "BTC").unwrap_err();
assert_eq!(err, CoinbasePriceError::MissingUsdRate);
}
#[test]
fn test_parse_coinbase_response_body_currency_mismatch() {
let body = r#"{
"data": {
"currency": "ETH",
"rates": {
"USD": "50000.00"
}
}
}"#;
let err = parse_coinbase_response_body(body, "BTC").unwrap_err();
assert!(matches!(
err,
CoinbasePriceError::CurrencyMismatch { expected, got }
if expected == "BTC" && got == "ETH"
));
}
// #604 — Coinbase reuses binance::parse_price_to_precision, so a "USD" rate
// of exactly zero must surface as a parse error, not a valid price of 0.
#[test]
fn test_parse_coinbase_response_body_rejects_zero_usd_rate() {
let body = r#"{
"data": {
"currency": "BTC",
"rates": {
"USD": "0"
}
}
}"#;
let err = parse_coinbase_response_body(body, "BTC").unwrap_err();
assert!(matches!(err, CoinbasePriceError::PriceParseError(_)));
}
#[test]
fn test_parse_coinbase_response_body_invalid_json() {
let err = parse_coinbase_response_body("not json", "BTC").unwrap_err();
assert!(matches!(err, CoinbasePriceError::JsonError(_)));
}
#[test]
fn test_parse_coinbase_http_response_non_200() {
let err = parse_coinbase_http_response(404, "{}", "BTC").unwrap_err();
assert!(matches!(
err,
CoinbasePriceError::HttpError { status: 404, .. }
));
}
#[test]
fn test_parse_coinbase_http_result_network_failure() {
let err = parse_coinbase_http_result(Err("timeout".to_string()), "BTC").unwrap_err();
assert_eq!(err, CoinbasePriceError::NetworkError("timeout".to_string()));
}
// ── #347 acceptance criteria ──────────────────────────────────────────────
/// #347 — USDT suffix is stripped before querying Coinbase.
/// fetch_spot_price strips suffixes so the URL uses the base asset only.
#[test]
fn coinbase_strips_usdt_suffix() {
// Verify suffix-stripping logic directly via parse helpers.
// "BTCUSDT" → base "BTC" → USD rate extracted correctly.
let body = r#"{
"data": {
"currency": "BTC",
"rates": { "USD": "50000.0" }
}
}"#;
let result = parse_coinbase_response_body(body, "BTC").unwrap();
assert_eq!(result, 50000 * FLOAT_PRECISION);
}
/// #347 — USD suffix is also stripped.
#[test]
fn coinbase_strips_usd_suffix() {
let body = r#"{
"data": {
"currency": "ETH",
"rates": { "USD": "3000.0" }
}
}"#;
let result = parse_coinbase_response_body(body, "ETH").unwrap();
assert_eq!(result, 3000 * FLOAT_PRECISION);
}
// #363 — verify the USD rate is extracted and scaled to 1e30 precision
#[test]
fn test_coinbase_parse_extracts_usd_rate_correctly() {
let body = r#"{
"data": {
"currency": "XLM",
"rates": {
"USD": "1.0",
"EUR": "0.9"
}
}
}"#;
let result = parse_coinbase_response_body(body, "XLM").unwrap();
assert_eq!(result, FLOAT_PRECISION);
}
// ── exact-match USDT/USD regression tests ────────────────────────────────
/// When the configured coinbase_symbol is exactly "USDT", strip_suffix("USDT")
/// must NOT produce an empty base currency — the symbol itself should be used.
#[test]
fn coinbase_exact_usdt_symbol_uses_symbol_not_empty() {
let body = r#"{
"data": {
"currency": "USDT",
"rates": { "USD": "1.0" }
}
}"#;
let result = parse_coinbase_response_body(body, "USDT").unwrap();
assert_eq!(result, FLOAT_PRECISION);
}
/// When the configured coinbase_symbol is exactly "USD", strip_suffix("USD")
/// must NOT produce an empty base currency — the symbol itself should be used.
#[test]
fn coinbase_exact_usd_symbol_uses_symbol_not_empty() {
let body = r#"{
"data": {
"currency": "USD",
"rates": { "USD": "1.0" }
}
}"#;
let result = parse_coinbase_response_body(body, "USD").unwrap();
assert_eq!(result, FLOAT_PRECISION);
}
/// When the symbol is exactly "USDT", the suffix-stripping logic must
/// keep the symbol as-is (not produce an empty string).
#[test]
fn coinbase_exact_usdt_strips_to_self() {
let symbol = "USDT";
let base = symbol
.strip_suffix("USDT")
.or_else(|| symbol.strip_suffix("USD"))
.filter(|s| !s.is_empty())
.unwrap_or(symbol);
assert_eq!(base, "USDT");
}
/// When the symbol is exactly "USD", the suffix-stripping logic must
/// keep the symbol as-is (not produce an empty string).
#[test]
fn coinbase_exact_usd_strips_to_self() {
let symbol = "USD";
let base = symbol
.strip_suffix("USDT")
.or_else(|| symbol.strip_suffix("USD"))
.filter(|s| !s.is_empty())
.unwrap_or(symbol);
assert_eq!(base, "USD");
}
// #364 — a response body without a USD key must return MissingUsdRate
#[test]
fn test_coinbase_parse_rejects_missing_usd_rate() {
let body = r#"{
"data": {
"currency": "XLM",
"rates": {
"EUR": "0.9"
}
}
}"#;
let err = parse_coinbase_response_body(body, "XLM").unwrap_err();
assert_eq!(err, CoinbasePriceError::MissingUsdRate);
}
/// Test that case-insensitive currency validation works
#[test]
fn test_coinbase_currency_case_insensitive() {
let body = r#"{
"data": {
"currency": "btc",
"rates": { "USD": "50000.0" }
}
}"#;
let result = parse_coinbase_response_body(body, "BTC").unwrap();
assert_eq!(result, 50000 * FLOAT_PRECISION);
}
/// Test that parse_coinbase_http_response validates currency
#[test]
fn test_parse_coinbase_http_response_currency_validation() {
let body = r#"{
"data": {
"currency": "BTC",
"rates": { "USD": "50000.0" }
}
}"#;
let result = parse_coinbase_http_response(200, body, "BTC").unwrap();
assert_eq!(result, 50000 * FLOAT_PRECISION);
}
#[test]
fn test_parse_coinbase_http_response_wrong_currency() {
let body = r#"{
"data": {
"currency": "ETH",
"rates": { "USD": "50000.0" }
}
}"#;
let err = parse_coinbase_http_response(200, body, "BTC").unwrap_err();
assert!(matches!(
err,
CoinbasePriceError::CurrencyMismatch { expected, got }
if expected == "BTC" && got == "ETH"
));
}
// ── HTTP-level wiremock tests ─────────────────────────────────────────────
#[tokio::test]
async fn fetch_spot_price_strips_usdt_suffix_success() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let server = MockServer::start().await;
let body = r#"{
"data": {
"currency": "BTC",
"rates": { "USD": "50000.0" }
}
}"#;
// "BTCUSDT" → base "BTC" → URL path should be "/BTC"
Mock::given(method("GET"))
.and(path("/BTC"))
.respond_with(ResponseTemplate::new(200).set_body_raw(body, "application/json"))
.mount(&server)
.await;
let base_url = format!("{}/", server.uri());
let result = super::fetch_spot_price_with_url(&base_url, "BTCUSDT")
.await
.unwrap();
assert_eq!(result, 50000 * FLOAT_PRECISION);
}
#[tokio::test]
async fn fetch_spot_price_strips_usd_suffix_success() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let server = MockServer::start().await;
let body = r#"{
"data": {
"currency": "ETH",
"rates": { "USD": "3000.0" }
}
}"#;
Mock::given(method("GET"))
.and(path("/ETH"))
.respond_with(ResponseTemplate::new(200).set_body_raw(body, "application/json"))
.mount(&server)
.await;
let base_url = format!("{}/", server.uri());
let result = super::fetch_spot_price_with_url(&base_url, "ETHUSD")
.await
.unwrap();
assert_eq!(result, 3000 * FLOAT_PRECISION);
}
#[tokio::test]
async fn fetch_spot_price_no_suffix_success() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let server = MockServer::start().await;
let body = r#"{
"data": {
"currency": "XLM",
"rates": { "USD": "1.0" }
}
}"#;
Mock::given(method("GET"))
.and(path("/XLM"))
.respond_with(ResponseTemplate::new(200).set_body_raw(body, "application/json"))
.mount(&server)
.await;
let base_url = format!("{}/", server.uri());
let result = super::fetch_spot_price_with_url(&base_url, "XLM")
.await
.unwrap();
assert_eq!(result, FLOAT_PRECISION);
}
#[tokio::test]
async fn fetch_spot_price_404_returns_http_error() {
use wiremock::matchers::method;
use wiremock::{Mock, MockServer, ResponseTemplate};
let server = MockServer::start().await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(404))
.mount(&server)
.await;
let base_url = format!("{}/", server.uri());
let err = super::fetch_spot_price_with_url(&base_url, "BTC")
.await
.unwrap_err();
assert!(matches!(
err,
CoinbasePriceError::HttpError { status: 404, .. }
));
}
#[tokio::test]
async fn fetch_spot_price_500_returns_http_error() {
use wiremock::matchers::method;
use wiremock::{Mock, MockServer, ResponseTemplate};
let server = MockServer::start().await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(500))
.mount(&server)
.await;
let base_url = format!("{}/", server.uri());
let err = super::fetch_spot_price_with_url(&base_url, "BTC")
.await
.unwrap_err();
assert!(matches!(
err,
CoinbasePriceError::HttpError { status: 500, .. }
));
}
}