1#![allow(non_snake_case)]
23
24use indexmap::IndexMap as HashMap;
25use std::sync::Arc;
26use hmac::{Hmac, Mac};
27use sha2::{Sha256, Sha512, Digest as Sha2Digest};
28use sha1::Sha1;
29use md5::Md5;
30use base64::{engine::general_purpose::STANDARD as B64, Engine as _};
31use crate::{Value, ExchangeError, Result};
32
33type HmacSha256 = Hmac<Sha256>;
34type HmacSha512 = Hmac<Sha512>;
35type HmacSha1 = Hmac<Sha1>;
36type HmacMd5 = Hmac<Md5>;
37
38pub type DescribeCallback = Arc<dyn Fn() -> Value + Send + Sync>;
40
41static HTTP_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
44static JSON_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
45static HTTP_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
46
47tokio::task_local! {
48 static WS_DRIVEN_URLS: std::sync::Mutex<std::collections::HashSet<String>>;
55}
56
57pub fn take_http_timings() -> (u64, u64, u64) {
60 use std::sync::atomic::Ordering::Relaxed;
61 (
62 HTTP_NANOS.swap(0, Relaxed),
63 JSON_NANOS.swap(0, Relaxed),
64 HTTP_CALLS.swap(0, Relaxed),
65 )
66}
67
68pub struct Internals {
71 pub http_client: Option<reqwest::Client>,
72 pub describe_cb: Option<DescribeCallback>,
73 pub last_rest_ts: i64,
74 pub headers: HashMap<String, String>,
75 pub throttle: std::sync::Arc<tokio::sync::Mutex<(f64, i64)>>,
79 pub implicit_api: HashMap<String, (String, Vec<String>, String, Value)>,
83 pub dispatch_stack: Vec<String>,
89 pub dynamic_dispatch_miss: Option<String>,
96}
97
98pub trait DerivedExchange {
106 fn parse_ticker(&self, _ticker: Value, _market: Value) -> Value { Value::Null }
108 fn parse_trade(&self, _trade: Value, _market: Value) -> Value { Value::Null }
109 fn parse_order(&self, _order: Value, _market: Value) -> Value { Value::Null }
110 fn parse_market(&self, _market: Value) -> Value { Value::Null }
111 fn parse_ohlcv(&self, _ohlcv: Value, _market: Value) -> Value { Value::Null }
112 fn parse_order_book(&self, _ob: Value, _symbol: Value, _ts: Value, _bk: Value, _ak: Value, _pk: Value, _ak2: Value, _ck: Value) -> Value { Value::Null }
113 fn parse_balance(&self, _response: Value) -> Value { Value::Null }
114 fn parse_position(&self, _position: Value, _market: Value) -> Value { Value::Null }
115 fn parse_funding_rate(&self, _rate: Value, _market: Value) -> Value { Value::Null }
116 fn parse_deposit(&self, _tx: Value, _currency: Value) -> Value { Value::Null }
117 fn parse_deposit_address(&self, _addr: Value, _currency: Value) -> Value { Value::Null }
118 fn parse_last_price(&self, _entry: Value, _market: Value) -> Value { Value::Null }
119 fn parse_withdrawal(&self, _tx: Value, _currency: Value) -> Value { Value::Null }
120 fn parse_ledger_entry(&self, _entry: Value, _currency: Value) -> Value { Value::Null }
121 fn parse_transfer(&self, _transfer: Value, _currency: Value) -> Value { Value::Null }
122 fn parse_currency(&self, _currency: Value) -> Value { Value::Null }
123 fn parse_bid_ask(&self, _bidask: Value, _price_key: Value, _amount_key: Value, _market: Value) -> Value { Value::Null }
124 fn parse_open_interest(&self, _interest: Value, _market: Value) -> Value { Value::Null }
125 fn parse_liquidation(&self, _liquidation: Value, _market: Value) -> Value { Value::Null }
126 fn parse_funding_rate_history(&self, _entry: Value, _market: Value) -> Value { Value::Null }
127 fn parse_margin_modification(&self, _data: Value, _market: Value) -> Value { Value::Null }
128 fn parse_account(&self, _account: Value) -> Value { Value::Null }
129 fn parse_my_trade(&self, _trade: Value, _market: Value) -> Value { Value::Null }
130 fn parse_transaction(&self, _transaction: Value, _currency: Value) -> Value { Value::Null }
131 fn parse_borrow_interest(&self, _info: Value, _market: Value) -> Value { Value::Null }
132 fn parse_adl_rank(&self, _info: Value, _market: Value) -> Value { Value::Null }
133 fn parse_income(&self, _info: Value, _market: Value) -> Value { Value::Null }
134 fn parse_greeks(&self, _greeks: Value, _market: Value) -> Value { Value::Null }
135 fn parse_margin_mode(&self, _margin_mode: Value, _market: Value) -> Value { Value::Null }
136 fn parse_conversion(&self, _conversion: Value, _from_currency: Value, _to_currency: Value) -> Value { Value::Null }
137 fn parse_borrow_rate(&self, _info: Value, _currency: Value) -> Value { Value::Null }
138 fn parse_leverage(&self, _leverage: Value, _market: Value) -> Value { Value::Null }
139 fn parse_market_leverage_tiers(&self, _info: Value, _market: Value) -> Value { Value::Null }
140 fn parse_deposit_withdraw_fee(&self, _fee: Value, _currency: Value) -> Value { Value::Null }
141 fn create_expired_option_market(&self, _symbol: Value) -> Value { Value::Null }
142 fn parse_prediction_trade(&self, _trade: Value, _market: Value) -> Value { Value::Null }
144 fn parse_prediction_order(&self, _order: Value, _market: Value) -> Value { Value::Null }
145 fn parse_prediction_position(&self, _position: Value, _market: Value) -> Value { Value::Null }
146 fn nonce(&self) -> Value { Value::Null }
155 fn sign(&self, _path: Value, _api: Value, _method: Value, _params: Value, _headers: Value, _body: Value) -> Value { Value::Null }
156 fn handle_errors(&self, _code: Value, _reason: Value, _url: Value, _method: Value, _headers: Value, _body: Value, _response: Value, _request_headers: Value, _request_body: Value) -> Value { Value::Null }
157}
158
159impl Clone for Internals {
169 fn clone(&self) -> Self { Internals::default() }
170}
171
172impl Default for Internals {
173 fn default() -> Self {
174 Self {
175 http_client: None,
176 describe_cb: None,
177 last_rest_ts: 0,
178 headers: HashMap::new(),
179 throttle: std::sync::Arc::new(tokio::sync::Mutex::new((0.0, 0))),
180 implicit_api: HashMap::new(),
181 dispatch_stack: Vec::new(),
182 dynamic_dispatch_miss: None,
183 }
184 }
185}
186
187#[derive(Clone)]
193pub struct Exchange {
194 pub id: Value,
196 pub name: Value,
197 pub countries: Value,
198 pub version: Value,
199 pub alias: Value,
200 pub certified: Value,
201 pub pro: Value,
202 pub hostname: Value,
203
204 pub apiKey: Value,
206 pub secret: Value,
207 pub password: Value,
208 pub uid: Value,
209 pub walletAddress: Value,
210 pub privateKey: Value,
211 pub twofa: Value,
212 pub token: Value,
213 pub login: Value,
214 pub accountId: Value,
215 pub requiredCredentials: Value,
216
217 pub timeout: Value,
219 pub rateLimit: Value,
220 pub enableRateLimit: Value,
221 pub rateLimiterAlgorithm: Value,
222 pub rollingWindowSize: Value,
223 pub tokenBucket: Value,
224 pub userConfig: Value,
229 pub verbose: Value,
230 pub isSandboxModeEnabled: Value,
231
232 pub proxy: Value,
234 pub proxyUrl: Value,
235 pub proxy_url: Value,
236 pub proxyUrlCallback: Value,
237 pub proxy_url_callback: Value,
238 pub httpProxy: Value,
239 pub http_proxy: Value,
240 pub httpProxyCallback: Value,
241 pub http_proxy_callback: Value,
242 pub httpsProxy: Value,
243 pub https_proxy: Value,
244 pub httpsProxyCallback: Value,
245 pub https_proxy_callback: Value,
246 pub socksProxy: Value,
247 pub socks_proxy: Value,
248 pub socksProxyCallback: Value,
249 pub socks_proxy_callback: Value,
250 pub wsProxy: Value,
251 pub ws_proxy: Value,
252 pub wssProxy: Value,
253 pub wss_proxy: Value,
254 pub wsSocksProxy: Value,
255 pub ws_socks_proxy: Value,
256
257 pub markets: Value,
259 pub markets_by_id: Value,
260 pub currencies: Value,
261 pub currencies_by_id: Value,
262 pub commonCurrencies: Value,
263 pub baseCurrencies: Value,
264 pub quoteCurrencies: Value,
265 pub symbols: Value,
266 pub ids: Value,
267 pub codes: Value,
268 pub timeframes: Value,
269 pub precision: Value,
270 pub limits: Value,
271 pub fees: Value,
272 pub features: Value,
273 pub has: Value,
274 pub exceptions: Value,
275 pub urls: Value,
276 pub api: Value,
277 pub options: Value,
278 pub headers: Value,
279 pub accounts: Value,
280 pub accountsById: Value,
281
282 pub orderbooks: Value,
284 pub orders: Value,
285 pub trades: Value,
286 pub myTrades: Value,
287 pub positions: Value,
288 pub newUpdates: Value,
293 pub tickers: Value,
294 pub bidsasks: Value,
295 pub ohlcvs: Value,
296 pub clients: Value,
297 pub balance: Value,
298 pub liquidations: Value,
299 pub myLiquidations: Value,
300 pub fundingRates: Value,
301 pub triggerOrders: Value,
302 pub transactions: Value,
303 pub reloadingMarkets: Value,
304 pub marketsLoading: Value,
305
306 pub last_request_url: Value,
308 pub last_request_headers: Value,
309 pub last_request_body: Value,
310 pub last_http_response: Value,
311 pub last_response_headers: Value,
312 pub mock_response: Value,
318 pub mock_response_by_url: Value,
322 pub last_json_response: Value,
323 pub lastRestRequestTimestamp: Value,
324 pub fetchHistoryCache: Value,
328 pub fetchHistoryCacheSize: Value,
329
330 pub paddingMode: Value,
332 pub precisionMode: Value,
333 pub substituteCommonCurrencyCodes: Value,
334 pub reduceFees: Value,
335 pub minFundingAddressLength: Value,
336 pub MAX_VALUE: Value,
337 pub returnResponseHeaders: Value,
338 pub httpExceptions: Value,
339 pub status: Value,
340
341 pub userAgent: Value,
343 pub user_agent: Value,
344 pub userAgents: Value,
345
346 pub describe_data: Value,
348 pub derived_describe: Option<DescribeCallback>,
349
350 pub internals: Internals,
352}
353
354impl Default for Exchange {
355 fn default() -> Self { Self::new(None) }
356}
357
358fn vmap(pairs: &[(&str, Value)]) -> Value {
364 let mut m = HashMap::new();
365 for (k, v) in pairs { m.insert((*k).to_string(), v.clone()); }
366 Value::Map(m)
367}
368
369fn min_max() -> Value { vmap(&[("min", Value::Null), ("max", Value::Null)]) }
370
371fn base_limits() -> Value {
372 vmap(&[
373 ("leverage", min_max()),
374 ("amount", min_max()),
375 ("price", min_max()),
376 ("cost", min_max()),
377 ])
378}
379
380fn base_fees() -> Value {
381 vmap(&[
382 ("trading", vmap(&[
383 ("tierBased", Value::Null),
384 ("percentage", Value::Null),
385 ("taker", Value::Null),
386 ("maker", Value::Null),
387 ])),
388 ("funding", vmap(&[
389 ("tierBased", Value::Null),
390 ("percentage", Value::Null),
391 ("withdraw", Value::Map(HashMap::new())),
392 ("deposit", Value::Map(HashMap::new())),
393 ])),
394 ])
395}
396
397fn base_urls() -> Value {
398 vmap(&[
399 ("logo", Value::Null), ("api", Value::Null), ("test", Value::Null),
400 ("www", Value::Null), ("doc", Value::Null), ("api_management", Value::Null),
401 ("fees", Value::Null), ("referral", Value::Null),
402 ])
403}
404
405fn base_status() -> Value {
406 vmap(&[
407 ("status", Value::Str("ok".into())),
408 ("updated", Value::Null),
409 ("eta", Value::Null),
410 ("url", Value::Null),
411 ("info", Value::Null),
412 ])
413}
414
415fn deep_merge(a: &Value, b: &Value) -> Value {
418 match (a, b) {
419 (Value::Dict(am), Value::Dict(bm)) => {
420 let mut out = (**am).clone();
421 for (k, bv) in bm.iter() {
422 let merged = match out.get(k) {
423 Some(av) => deep_merge(av, bv),
424 None => bv.clone(),
425 };
426 out.insert(k.clone(), merged);
427 }
428 Value::Map(out)
429 }
430 _ => b.clone(),
431 }
432}
433
434fn base_http_exceptions() -> Value {
435 let mut m = HashMap::new();
436 for (code, class) in [
437 ("422", "ExchangeError"), ("418", "DDoSProtection"),
438 ("429", "RateLimitExceeded"), ("404", "ExchangeNotAvailable"),
439 ("409", "ExchangeNotAvailable"), ("410", "ExchangeNotAvailable"),
440 ("451", "ExchangeNotAvailable"), ("500", "ExchangeNotAvailable"),
441 ("501", "ExchangeNotAvailable"), ("502", "ExchangeNotAvailable"),
442 ("520", "ExchangeNotAvailable"), ("521", "ExchangeNotAvailable"),
443 ("522", "ExchangeNotAvailable"), ("525", "ExchangeNotAvailable"),
444 ("526", "ExchangeNotAvailable"), ("400", "ExchangeNotAvailable"),
445 ("403", "ExchangeNotAvailable"), ("405", "ExchangeNotAvailable"),
446 ("503", "ExchangeNotAvailable"), ("530", "ExchangeNotAvailable"),
447 ("408", "RequestTimeout"), ("504", "RequestTimeout"),
448 ("401", "AuthenticationError"), ("407", "AuthenticationError"),
449 ("511", "AuthenticationError"),
450 ] {
451 m.insert(code.to_string(), Value::Str(class.to_string().into()));
452 }
453 Value::Map(m)
454}
455
456impl Exchange {
457 pub fn new(config: Option<Value>) -> Self {
458 let mut ex = Exchange {
459 id: Value::Str("Exchange".into()),
462 name: Value::Null,
463 countries: Value::Null,
464 version: Value::Null,
465 alias: Value::Bool(false),
466 certified: Value::Bool(false),
467 pro: Value::Bool(false),
468 hostname: Value::Null,
469
470 apiKey: Value::Null,
471 secret: Value::Null,
472 password: Value::Null,
473 uid: Value::Null,
474 walletAddress: Value::Null,
475 privateKey: Value::Null,
476 twofa: Value::Null,
477 token: Value::Null,
478 login: Value::Null,
479 accountId: Value::Null,
480 requiredCredentials: {
484 let mut m = HashMap::new();
485 m.insert("apiKey".to_string(), Value::Bool(true));
486 m.insert("secret".to_string(), Value::Bool(true));
487 m.insert("uid".to_string(), Value::Bool(false));
488 m.insert("accountId".to_string(), Value::Bool(false));
489 m.insert("login".to_string(), Value::Bool(false));
490 m.insert("password".to_string(), Value::Bool(false));
491 m.insert("twofa".to_string(), Value::Bool(false));
492 m.insert("privateKey".to_string(), Value::Bool(false));
493 m.insert("walletAddress".to_string(), Value::Bool(false));
494 m.insert("token".to_string(), Value::Bool(false));
495 Value::Map(m)
496 },
497
498 timeout: Value::Int(10_000),
499 rateLimit: Value::Int(2_000),
500 enableRateLimit: Value::Bool(true),
501 rateLimiterAlgorithm: Value::Str("leakyBucket".into()),
502 rollingWindowSize: Value::Int(60_000),
503 tokenBucket: Value::Map(HashMap::new()),
504 userConfig: Value::Null,
505 verbose: Value::Bool(false),
506 isSandboxModeEnabled: Value::Bool(false),
507
508 proxy: Value::Null,
509 proxyUrl: Value::Null,
510 proxy_url: Value::Null,
511 proxyUrlCallback: Value::Null,
512 proxy_url_callback: Value::Null,
513 httpProxy: Value::Null,
514 http_proxy: Value::Null,
515 httpProxyCallback: Value::Null,
516 http_proxy_callback: Value::Null,
517 httpsProxy: Value::Null,
518 https_proxy: Value::Null,
519 httpsProxyCallback: Value::Null,
520 https_proxy_callback: Value::Null,
521 socksProxy: Value::Null,
522 socks_proxy: Value::Null,
523 socksProxyCallback: Value::Null,
524 socks_proxy_callback: Value::Null,
525 wsProxy: Value::Null,
526 ws_proxy: Value::Null,
527 wssProxy: Value::Null,
528 wss_proxy: Value::Null,
529 wsSocksProxy: Value::Null,
530 ws_socks_proxy: Value::Null,
531
532 markets: Value::Null,
533 markets_by_id: Value::Null,
534 currencies: Value::Map(HashMap::new()),
535 currencies_by_id: Value::Null,
536 commonCurrencies: {
537 let mut m = HashMap::new();
538 m.insert("XBT".to_string(), Value::Str("BTC".into()));
539 m.insert("BCHSV".to_string(), Value::Str("BSV".into()));
540 Value::Map(m)
541 },
542 baseCurrencies: Value::Null,
543 quoteCurrencies: Value::Null,
544 symbols: Value::Null,
545 ids: Value::Null,
546 codes: Value::Null,
547 timeframes: Value::Null,
548 precision: Value::Null,
549 limits: base_limits(),
550 fees: base_fees(),
551 features: Value::Null,
552 has: Value::Map(HashMap::new()),
553 exceptions: Value::Null,
554 urls: base_urls(),
555 api: Value::Null,
556 options: {
560 let mk = |p: &str, s: &str, d: &str| {
561 let mut e = HashMap::new();
562 e.insert("primary".to_string(), Value::Str(p.to_string().into()));
563 e.insert("secondary".to_string(), Value::Str(s.to_string().into()));
564 e.insert("default".to_string(), Value::Str(d.to_string().into()));
565 Value::Map(e)
566 };
567 let mut repl = HashMap::new();
568 repl.insert("ETH".to_string(), mk("ETH", "ERC20", "secondary"));
569 repl.insert("CRO".to_string(), mk("CRONOS", "CRC20", "secondary"));
570 repl.insert("TRX".to_string(), mk("TRX", "TRC20", "secondary"));
571 repl.insert("BTC".to_string(), mk("BTC", "BRC20", "primary"));
572 let mut o = HashMap::new();
573 o.insert("defaultNetworkCodeReplacements".to_string(), Value::Map(repl));
574 Value::Map(o)
575 },
576 headers: Value::Map(HashMap::new()),
577 accounts: Value::Null,
578 accountsById: Value::Null,
579
580 orderbooks: Value::Map(HashMap::new()),
581 orders: Value::Null,
582 trades: Value::Map(HashMap::new()),
583 myTrades: Value::Null,
584 positions: Value::Null,
585 newUpdates: Value::Bool(true),
586 tickers: Value::Map(HashMap::new()),
587 bidsasks: Value::Map(HashMap::new()),
588 ohlcvs: Value::Map(HashMap::new()),
589 clients: Value::Map(HashMap::new()),
590 balance: Value::Map(HashMap::new()),
591 liquidations: Value::Null,
592 myLiquidations: Value::Null,
593 fundingRates: Value::Null,
594 triggerOrders: Value::Null,
595 transactions: Value::Map(HashMap::new()),
596 reloadingMarkets: Value::Null,
597 marketsLoading: Value::Null,
598
599 last_request_url: Value::Null,
600 last_request_headers: Value::Null,
601 last_request_body: Value::Null,
602 last_http_response: Value::Null,
603 last_response_headers: Value::Null,
604 mock_response: Value::Null,
605 mock_response_by_url: Value::Null,
606 last_json_response: Value::Null,
607 lastRestRequestTimestamp: Value::Int(0),
608 fetchHistoryCache: Value::List(vec![]),
609 fetchHistoryCacheSize: Value::Int(0),
610
611 paddingMode: Value::Null,
612 precisionMode: Value::Null,
613 substituteCommonCurrencyCodes: Value::Bool(true),
614 reduceFees: Value::Bool(true),
615 minFundingAddressLength: Value::Int(1),
616 MAX_VALUE: Value::Float(f64::MAX),
617 returnResponseHeaders: Value::Bool(false),
618 httpExceptions: base_http_exceptions(),
619 status: base_status(),
620
621 userAgent: Value::Null,
622 user_agent: Value::Null,
623 userAgents: {
624 let mut m = HashMap::new();
625 m.insert("chrome".to_string(), Value::Str("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36".into()));
626 m.insert("chrome39".to_string(), Value::Str("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36".into()));
627 m.insert("chrome100".to_string(), Value::Str("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36".into()));
628 Value::Map(m)
629 },
630
631 describe_data: Value::Null,
632 derived_describe: None,
633
634 internals: Internals::default(),
635 };
636 if let Some(cfg) = config {
637 ex.userConfig = cfg.clone();
638 ex.apply_config(&cfg);
639 }
640 ex
650 }
651
652 pub fn initialize_properties(&mut self, described: Value) {
668 let props = if matches!(self.userConfig, Value::Null) {
669 described
670 } else {
671 crate::runtime::deep_merge_dict(&described, &self.userConfig.clone())
672 };
673 let get = |k: &str| crate::get_value(&props, &Value::Str(k.to_string().into()));
674 let assign = |field: &mut Value, v: Value| {
675 if !matches!(v, Value::Null) {
676 *field = v;
677 }
678 };
679 assign(&mut self.api, get("api"));
680 assign(&mut self.urls, get("urls"));
681 assign(&mut self.has, get("has"));
682 assign(&mut self.hostname, get("hostname"));
683 assign(&mut self.version, get("version"));
684 assign(&mut self.id, get("id"));
685 assign(&mut self.name, get("name"));
686 assign(&mut self.exceptions, get("exceptions"));
687 assign(&mut self.requiredCredentials, get("requiredCredentials"));
688 assign(&mut self.precisionMode, get("precisionMode"));
689 assign(&mut self.timeframes, get("timeframes"));
690 assign(&mut self.fees, get("fees"));
691 assign(&mut self.features, get("features"));
692 let rate_limit = get("rateLimit");
693 if matches!(rate_limit, Value::Int(_) | Value::Float(_)) {
694 self.rateLimit = rate_limit;
695 }
696 if let Value::Dict(extra) = get("options") {
700 let mut merged = match &self.options {
701 Value::Dict(m) => (**m).clone(),
702 _ => HashMap::new(),
703 };
704 let extra = Arc::try_unwrap(extra).unwrap_or_else(|a| (*a).clone());
705 for (k, v) in extra { merged.insert(k, v); }
706 self.options = Value::Map(merged);
707 }
708 if let Value::Dict(extra) = get("commonCurrencies") {
709 let mut merged = match &self.commonCurrencies {
710 Value::Dict(m) => (**m).clone(),
711 _ => HashMap::new(),
712 };
713 let extra = Arc::try_unwrap(extra).unwrap_or_else(|a| (*a).clone());
714 for (k, v) in extra { merged.insert(k, v); }
715 self.commonCurrencies = Value::Map(merged);
716 }
717 let described_markets = get("markets");
721 if matches!(&described_markets, Value::Dict(m) if !m.is_empty())
722 && matches!(self.markets, Value::Null)
723 {
724 self.set_markets_inline(described_markets);
725 }
726 self.build_implicit_api();
727 }
728
729 fn apply_config(&mut self, cfg: &Value) {
730 use crate::value::safe_string;
731 if let Some(v) = safe_string(cfg, "id", None) { self.id = Value::Str(v.into()); }
732 if let Some(v) = safe_string(cfg, "name", None) { self.name = Value::Str(v.into()); }
733 if let Some(v) = safe_string(cfg, "hostname", None) { self.hostname = Value::Str(v.into()); }
734 let rate_limit = crate::get_value(cfg, &Value::Str("rateLimit".into()));
735 if matches!(rate_limit, Value::Int(_) | Value::Float(_)) { self.rateLimit = rate_limit; }
736 let timeout = crate::get_value(cfg, &Value::Str("timeout".into()));
737 if matches!(timeout, Value::Int(_) | Value::Float(_)) { self.timeout = timeout; }
738 let fetch_history_cache_size = crate::get_value(cfg, &Value::Str("fetchHistoryCacheSize".into()));
739 if matches!(fetch_history_cache_size, Value::Int(_) | Value::Float(_)) { self.fetchHistoryCacheSize = fetch_history_cache_size; }
740 let urls = crate::get_value(cfg, &Value::Str("urls".into()));
741 if let Value::Dict(_) = urls { self.urls = deep_merge(&self.urls, &urls); }
742 if let Some(v) = safe_string(cfg, "apiKey", None) { self.apiKey = Value::Str(v.into()); }
743 if let Some(v) = safe_string(cfg, "secret", None) { self.secret = Value::Str(v.into()); }
744 if let Some(v) = safe_string(cfg, "password", None) { self.password = Value::Str(v.into()); }
745 if let Some(v) = safe_string(cfg, "uid", None) { self.uid = Value::Str(v.into()); }
746 if let Some(v) = safe_string(cfg, "walletAddress", None) { self.walletAddress = Value::Str(v.into()); }
747 if let Some(v) = safe_string(cfg, "privateKey", None) { self.privateKey = Value::Str(v.into()); }
748 if let Some(v) = safe_string(cfg, "token", None) { self.token = Value::Str(v.into()); }
749 if let Some(v) = safe_string(cfg, "login", None) { self.login = Value::Str(v.into()); }
750 if let Some(v) = safe_string(cfg, "accountId", None) { self.accountId = Value::Str(v.into()); }
751 if let Some(v) = safe_string(cfg, "httpProxy", None) { self.httpProxy = Value::Str(v.into()); }
752 if let Some(v) = safe_string(cfg, "httpsProxy", None) { self.httpsProxy = Value::Str(v.into()); }
753 if let Some(v) = safe_string(cfg, "socksProxy", None) { self.socksProxy = Value::Str(v.into()); }
754 if let Some(v) = safe_string(cfg, "wsProxy", None) { self.wsProxy = Value::Str(v.into()); }
758 if let Some(v) = safe_string(cfg, "wssProxy", None) { self.wssProxy = Value::Str(v.into()); }
759 if let Some(b) = crate::value::safe_bool(cfg, "verbose", None) { self.verbose = Value::Bool(b); }
760 if let Some(b) = crate::value::safe_bool(cfg, "enableRateLimit", None) { self.enableRateLimit = Value::Bool(b); }
761 let markets = crate::get_value(cfg, &Value::Str("markets".into()));
766 let currencies = crate::get_value(cfg, &Value::Str("currencies".into()));
767 if !matches!(markets, Value::Null) { self.set_markets_inline(markets); }
768 if !matches!(currencies, Value::Null) { self.currencies = currencies; }
769 let opts = crate::get_value(cfg, &Value::Str("options".into()));
770 if let Value::Dict(extra) = opts {
771 let mut merged = match &self.options {
772 Value::Dict(m) => (**m).clone(),
773 _ => HashMap::new(),
774 };
775 let extra = Arc::try_unwrap(extra).unwrap_or_else(|a| (*a).clone());
776 for (k, v) in extra { merged.insert(k, v); }
777 self.options = Value::Map(merged);
778 }
779 let accounts = crate::get_value(cfg, &Value::Str("accounts".into()));
780 if !matches!(accounts, Value::Null) { self.accounts = accounts; }
781 }
782
783 fn set_markets_inline(&mut self, markets: Value) {
786 let arr: Vec<Value> = match &markets {
787 Value::Dict(m) => m.values().cloned().collect(),
788 Value::Arr(a) => (**a).clone(),
789 _ => return,
790 };
791 let mut by_symbol = HashMap::new();
792 let mut by_id: HashMap<String, Vec<Value>> = HashMap::new();
796 let mut symbols = Vec::new();
797 for m in &arr {
798 if let Some(s) = crate::value::safe_string(m, "symbol", None) {
799 by_symbol.insert(s.clone(), m.clone());
800 symbols.push(Value::Str(s.into()));
801 }
802 if let Some(i) = crate::value::safe_string(m, "id", None) {
803 by_id.entry(i).or_default().push(m.clone());
804 }
805 }
806 self.markets = if by_symbol.is_empty() { markets } else { Value::Map(by_symbol) };
807 self.markets_by_id = Value::Map(
808 by_id.into_iter().map(|(k, v)| (k, Value::Array(v))).collect()
809 );
810 self.symbols = Value::Array(symbols);
811 }
812
813 fn http_client(&mut self) -> &reqwest::Client {
816 if self.internals.http_client.is_none() {
817 let mut b = reqwest::Client::builder()
818 .timeout(std::time::Duration::from_millis(self.timeout_ms()))
819 .gzip(true);
824 if let Some(ua) = self.user_agent_str() { b = b.user_agent(ua); }
825 let mut proxies: Vec<reqwest::Proxy> = Vec::new();
834 for field in [&self.socksProxy, &self.socks_proxy] {
835 if let Value::Str(s) = field {
836 if !s.is_empty() {
837 if let Ok(p) = reqwest::Proxy::all(s.as_ref()) { proxies.push(p); }
838 }
839 }
840 }
841 for field in [&self.httpsProxy, &self.https_proxy] {
842 if let Value::Str(s) = field {
843 if !s.is_empty() {
844 if let Ok(p) = reqwest::Proxy::https(s.as_ref()) { proxies.push(p); }
845 }
846 }
847 }
848 for field in [&self.httpProxy, &self.http_proxy] {
849 if let Value::Str(s) = field {
850 if !s.is_empty() {
851 if let Ok(p) = reqwest::Proxy::http(s.as_ref()) { proxies.push(p); }
852 }
853 }
854 }
855 if proxies.is_empty() {
858 if let Value::Str(s) = &self.proxy {
859 if !s.is_empty() {
860 if let Ok(p) = reqwest::Proxy::all(s.as_ref()) { proxies.push(p); }
861 }
862 }
863 }
864 for p in proxies { b = b.proxy(p); }
865 self.internals.http_client = Some(b.build().expect("reqwest client"));
866 }
867 self.internals.http_client.as_ref().unwrap()
868 }
869
870 fn timeout_ms(&self) -> u64 {
871 match &self.timeout {
872 Value::Int(n) => *n as u64,
873 Value::Float(f) => *f as u64,
874 _ => 10_000,
875 }
876 }
877
878 fn user_agent_str(&self) -> Option<&str> {
879 match &self.userAgent { Value::Str(s) => Some(s.as_ref()), _ => match &self.user_agent {
880 Value::Str(s) => Some(s.as_ref()), _ => None
881 }}
882 }
883
884
885 fn is_verbose(&self) -> bool {
886 matches!(self.verbose, Value::Bool(true))
887 }
888
889
890 pub fn urlencode_kv(&self, params: &Value) -> String {
893 let m = match params { Value::Dict(m) => m, _ => return String::new() };
894 m.iter().map(|(k, v)| format!(
895 "{}={}",
896 url_pct(k),
897 url_pct(&crate::runtime::stringify_param(v)),
898 )).collect::<Vec<_>>().join("&")
899 }
900
901 pub fn implode_params(&self, path: Value, params: Value) -> Value {
902 let path_str = match &path { Value::Str(s) => s.clone(), _ => return path };
903 let m = match ¶ms { Value::Dict(m) => m, _ => return Value::Str(path_str) };
904 let mut out = path_str;
905 for (k, v) in m.iter() {
906 let needle = format!("{{{k}}}");
907 if out.contains(&needle) {
908 out = out.replace(&needle, &crate::runtime::stringify_param(v)).into();
909 }
910 }
911 Value::Str(out)
912 }
913
914 pub fn json_str(&self, v: &Value) -> String {
915 serde_json::to_string(&v.to_json()).unwrap_or_default()
916 }
917
918 pub fn hmac(&self, data: Value, secret: Value, hash: Value, optional_args: &[Value]) -> Value {
921 let dbytes = value_to_bytes(&data);
924 let sbytes = value_to_bytes(&secret);
925 let h = match &hash { Value::Str(s) => s.clone(), _ => "sha256".to_string().into() };
926 let digest = match optional_args.get(0) {
927 Some(Value::Str(d)) => d.clone(),
928 _ => "hex".to_string().into(),
929 };
930 match self.hmac_typed(&dbytes, &sbytes, &h, &digest) {
931 Ok(v) => Value::Str(v.into()),
932 Err(_) => Value::Null,
933 }
934 }
935
936 pub fn hmac_typed(&self, data: &[u8], secret: &[u8], hash: &str, digest: &str) -> Result<String> {
937 let dbytes = data;
938 let sbytes = secret;
939 let raw: Vec<u8> = match hash.to_ascii_lowercase().as_str() {
940 "sha256" => { let mut m = HmacSha256::new_from_slice(sbytes).unwrap(); m.update(dbytes); m.finalize().into_bytes().to_vec() }
941 "sha512" => { let mut m = HmacSha512::new_from_slice(sbytes).unwrap(); m.update(dbytes); m.finalize().into_bytes().to_vec() }
942 "sha1" => { let mut m = HmacSha1::new_from_slice(sbytes).unwrap(); m.update(dbytes); m.finalize().into_bytes().to_vec() }
943 "md5" => { let mut m = HmacMd5::new_from_slice(sbytes).unwrap(); m.update(dbytes); m.finalize().into_bytes().to_vec() }
944 other => return Err(ExchangeError::new("BadRequest", format!("unknown hmac: {other}"))),
945 };
946 Ok(match digest {
947 "base64" => B64.encode(&raw),
948 _ => hex::encode(&raw),
949 })
950 }
951
952 pub fn hash(&self, data: Value, algo: Value, optional_args: &[Value]) -> Value {
953 let dbytes = value_to_bytes(&data);
955 let a = match &algo { Value::Str(s) => s.clone(), _ => "sha256".to_string().into() };
956 let digest = match optional_args.get(0) {
957 Some(Value::Str(d)) => d.clone(),
958 _ => "hex".to_string().into(),
959 };
960 let raw = hash_raw(&dbytes, &a);
961 match digest.as_ref() {
962 "binary" => Value::Array(raw.iter().map(|b| Value::Int(*b as i64)).collect()),
964 "base64" => Value::Str(B64.encode(&raw).into()),
965 _ => Value::Str(hex::encode(&raw).into()),
966 }
967 }
968
969 pub fn hash_typed(&self, data: &[u8], algo: &str, digest: &str) -> String {
970 let raw = hash_raw(data, algo);
971 match digest {
972 "base64" => B64.encode(&raw),
973 _ => hex::encode(&raw),
974 }
975 }
976
977 pub fn binary_to_base64(&self, data: Value, _optional_args: &[Value]) -> Value {
978 let bytes = value_to_bytes(&data);
979 Value::Str(B64.encode(&bytes).into())
980 }
981 pub fn base64_to_binary(&self, s: Value, _optional_args: &[Value]) -> Value {
982 let str_val = match &s { Value::Str(s) => s.clone(), _ => return Value::Null };
983 match B64.decode(&*str_val) {
984 Ok(b) => Value::Array(b.into_iter().map(|n| Value::Int(n as i64)).collect()),
985 Err(_) => Value::Null,
986 }
987 }
988 pub fn binary_to_base16(&self, data: Value, _optional_args: &[Value]) -> Value {
989 let bytes = value_to_bytes(&data);
990 Value::Str(hex::encode(&bytes).into())
991 }
992 pub fn base16_to_binary(&self, s: Value, _optional_args: &[Value]) -> Value {
993 let str_val = match &s { Value::Str(s) => s.clone(), _ => return Value::Null };
994 match hex::decode(&*str_val) {
995 Ok(b) => Value::Array(b.into_iter().map(|n| Value::Int(n as i64)).collect()),
996 Err(_) => Value::Null,
997 }
998 }
999
1000 pub fn milliseconds(&self) -> Value {
1003 let n = std::time::SystemTime::now()
1004 .duration_since(std::time::UNIX_EPOCH)
1005 .map(|d| d.as_millis() as i64).unwrap_or(0);
1006 Value::Int(n)
1007 }
1008 pub fn seconds(&self) -> Value {
1009 match self.milliseconds() { Value::Int(n) => Value::Int(n / 1000), v => v }
1010 }
1011 pub fn microseconds(&self) -> Value {
1012 match self.milliseconds() { Value::Int(n) => Value::Int(n * 1000), v => v }
1013 }
1014
1015 pub fn iso8601(&self, ts: Value) -> Value {
1016 let n = match ts {
1017 Value::Int(n) => n,
1018 Value::Float(f) => f as i64,
1019 Value::Str(ref s) => match s.parse::<i64>() { Ok(v) => v, Err(_) => return Value::Null },
1020 _ => return Value::Null,
1021 };
1022 if n < 0 {
1023 return Value::Null;
1024 }
1025 chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n)
1026 .map(|t| Value::Str(t.to_rfc3339_opts(chrono::SecondsFormat::Millis, true).into()))
1027 .unwrap_or(Value::Null)
1028 }
1029
1030 pub fn parse8601(&self, s: Value) -> Value {
1031 let str_val = match s { Value::Str(s) => s, _ => return Value::Null };
1032 if str_val.is_empty() {
1033 return Value::Null;
1034 }
1035 if let Ok(t) = chrono::DateTime::parse_from_rfc3339(&str_val) {
1037 return Value::Int(t.timestamp_millis());
1038 }
1039 for fmt in [
1043 "%Y-%m-%dT%H:%M:%S%.f%z", "%Y-%m-%dT%H:%M:%S%z",
1044 "%Y-%m-%d %H:%M:%S%.f%z", "%Y-%m-%d %H:%M:%S%z",
1045 ] {
1046 if let Ok(t) = chrono::DateTime::parse_from_str(&str_val, fmt) {
1047 return Value::Int(t.timestamp_millis());
1048 }
1049 }
1050 for fmt in [
1052 "%Y-%m-%d %H:%M:%S%.f", "%Y-%m-%d %H:%M:%S",
1053 "%Y-%m-%dT%H:%M:%S%.f", "%Y-%m-%dT%H:%M:%S",
1054 "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M",
1055 ] {
1056 if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(&str_val, fmt) {
1057 return Value::Int(ndt.and_utc().timestamp_millis());
1058 }
1059 }
1060 if let Ok(d) = chrono::NaiveDate::parse_from_str(&str_val, "%Y-%m-%d") {
1061 if let Some(ndt) = d.and_hms_opt(0, 0, 0) {
1062 return Value::Int(ndt.and_utc().timestamp_millis());
1063 }
1064 }
1065 Value::Null
1066 }
1067
1068 }
1075
1076impl Exchange {
1088 pub fn dispatch_guard_enter(&mut self, method: &str) -> bool {
1092 if self.internals.dispatch_stack.iter().any(|m| m == method) { return false; }
1093 self.internals.dispatch_stack.push(method.to_string());
1094 true
1095 }
1096
1097 pub fn dispatch_guard_exit(&mut self) {
1099 self.internals.dispatch_stack.pop();
1100 }
1101}
1102
1103fn ws_string_list(v: &Value) -> Vec<String> {
1115 match v {
1116 Value::Str(s) => vec![s.to_string()],
1117 Value::Arr(a) => a
1118 .iter()
1119 .filter_map(|x| match x {
1120 Value::Str(s) => Some(s.to_string()),
1121 _ => None,
1122 })
1123 .collect(),
1124 _ => Vec::new(),
1125 }
1126}
1127
1128pub trait ExchangeRuntime: crate::exchange_generated::ExchangeBase {
1129 fn fetch(&mut self, url: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1130 let url_str = match &url { Value::Str(s) => s.to_string(), _ => crate::runtime::stringify_param(&url).into() };
1131 let method = optional_args.get(0).cloned().unwrap_or(Value::Str("GET".into()));
1132 let headers = optional_args.get(1).cloned().unwrap_or(Value::Null);
1133 let body = optional_args.get(2).cloned().unwrap_or(Value::Null);
1134 let method_str = match &method { Value::Str(s) => s.to_string(), _ => "GET".to_string().into() };
1135 let body_str = match &body { Value::Str(s) => Some(s.to_string()), _ => None };
1136 let headers_map: HashMap<String, String> = match &headers {
1137 Value::Dict(m) => m.iter().filter_map(|(k, v)| match v {
1138 Value::Str(s) => Some((k.clone(), s.to_string())),
1139 _ => None,
1140 }).collect(),
1141 _ => HashMap::new(),
1142 };
1143 match self.fetch_typed(&url_str, &method_str, headers_map, body_str).await {
1144 Ok(v) => v,
1145 Err(e) => panic!("{}", e),
1148 }
1149 } }
1150
1151 fn ws_run(
1168 &mut self,
1169 url: String,
1170 hashes: Vec<String>,
1171 message: Value,
1172 subscribe_hashes: Vec<String>,
1173 subscription: Value,
1174 ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1175 let __ws_proxy = [&self.wsProxy, &self.ws_proxy, &self.wssProxy]
1176 .iter()
1177 .find_map(|v| match v { Value::Str(s) if !s.is_empty() => Some(s.to_string()), _ => None });
1178 let __decompress_binary = !matches!(crate::get_value(&self.options, &Value::Str("decompressBinary".into())), Value::Bool(false));
1180 let client = match crate::pro::ws_client::ensure_client(&url, __ws_proxy, __decompress_binary).await {
1181 Ok(c) => c,
1182 Err(e) => panic!("{}", e),
1183 };
1184 if std::env::var("CCXT_WS_DEBUG").is_ok() {
1185 eprintln!("[wswait] {:?}", hashes);
1186 }
1187 client.note_futures(&hashes);
1188 let mut send_subscribe = subscribe_hashes.is_empty();
1192 for sh in &subscribe_hashes {
1193 if client.subscribe_once(sh, subscription.clone()) {
1194 send_subscribe = true;
1195 }
1196 }
1197 if send_subscribe && !matches!(message, Value::Null) {
1198 let payload = match &message {
1199 Value::Str(s) => s.to_string(),
1200 v => v.to_json().to_string(),
1201 };
1202 client.send_text(payload);
1203 }
1204 crate::runtime::add_element_to_object(
1211 &mut self.clients,
1212 &Value::Str(url.clone().into()),
1213 crate::pro::ws_client::client_value(&url),
1214 );
1215 let nested_same = WS_DRIVEN_URLS
1219 .try_with(|s| s.lock().unwrap().contains(&url))
1220 .unwrap_or(false);
1221 if nested_same {
1222 return match client.take_settled(&hashes) {
1223 Some(Ok(v)) => v,
1224 _ => Value::Null,
1225 };
1226 }
1227 if WS_DRIVEN_URLS.try_with(|_| ()).is_ok() {
1231 WS_DRIVEN_URLS.with(|s| { s.lock().unwrap().insert(url.clone()); });
1232 let r = self.ws_drive_loop(client, hashes, url.clone()).await;
1233 WS_DRIVEN_URLS.with(|s| { s.lock().unwrap().remove(&url); });
1234 r
1235 } else {
1236 let mut set = std::collections::HashSet::new();
1237 set.insert(url.clone());
1238 WS_DRIVEN_URLS
1239 .scope(std::sync::Mutex::new(set), self.ws_drive_loop(client, hashes, url.clone()))
1240 .await
1241 }
1242 } }
1243
1244 fn ws_drive_loop(
1247 &mut self,
1248 client: std::sync::Arc<crate::pro::ws_client::ClientState>,
1249 hashes: Vec<String>,
1250 url: String,
1251 ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1252 loop {
1253 loop {
1259 let batch = crate::exchange_stubs::drain_spawn_queue();
1260 if batch.is_empty() { break; }
1261 for (method, args) in batch {
1262 if std::env::var("CCXT_WS_DEBUG").is_ok() {
1263 eprintln!("[wsdrain] {}", method);
1264 }
1265 if method == "load_order_book" {
1266 self.ws_load_order_book(args).await;
1267 } else {
1268 let _ = self.dispatch_to_derived(&method, args).await;
1269 }
1270 }
1271 }
1272 if let Some(settled) = client.take_settled(&hashes) {
1273 match settled {
1274 Ok(v) => return v,
1275 Err(e) => panic!(
1276 "{}",
1277 match &e {
1278 Value::Str(s) => s.clone(),
1279 v => crate::runtime::stringify_param(v).into(),
1280 }
1281 ),
1282 }
1283 }
1284 let next_due = crate::exchange_stubs::next_spawn_due();
1289 let received = match next_due {
1290 Some(d) => match tokio::time::timeout(d, client.next_message()).await {
1291 Ok(m) => m,
1292 Err(_) => continue,
1294 },
1295 None => client.next_message().await,
1296 };
1297 let msg = match received {
1298 Some(m) => m,
1299 None => panic!("[NetworkError] {} websocket connection closed", url),
1300 };
1301 if std::env::var("CCXT_WS_DEBUG").is_ok() {
1302 let n: usize = std::env::var("CCXT_WS_DEBUG").ok()
1303 .and_then(|v| v.parse().ok()).filter(|v| *v > 1).unwrap_or(220);
1304 let s = msg.to_json().to_string();
1305 eprintln!("[wsmsg] {}", s.chars().take(n).collect::<String>());
1306 }
1307 let client_value = crate::pro::ws_client::client_value(&url);
1308 let _ = self
1309 .dispatch_to_derived("handle_message", vec![client_value, msg])
1310 .await;
1311 }
1312 } }
1313
1314 fn ws_load_order_book(
1319 &mut self,
1320 args: Vec<Value>,
1321 ) -> impl ::std::future::Future<Output = ()> + Send { async move {
1322 let client = args.get(0).cloned().unwrap_or(Value::Null);
1323 let message_hash = args.get(1).cloned().unwrap_or(Value::Null);
1324 let symbol = args.get(2).cloned().unwrap_or(Value::Null);
1325 let limit = args.get(3).cloned().unwrap_or(Value::Null);
1326 let params = args.get(4).cloned().unwrap_or(Value::Map(indexmap::IndexMap::new()));
1327 let err = |id: &Value| Value::Str(format!(
1328 "[ExchangeError] {} loadOrderBook() failed to synchronize",
1329 match id { Value::Str(s) => s.as_ref(), _ => "" }).into());
1330 if !crate::runtime::in_op(&self.orderbooks, &symbol) {
1331 crate::pro::ws_client::value_reject(&client, &[err(&self.id), message_hash]);
1332 return;
1333 }
1334 let max_retries: i64 = 3;
1335 let mut tries = 0;
1336 while tries < max_retries {
1337 let mut stored = crate::get_value(&self.orderbooks, &symbol);
1338 let cache = crate::get_value(&stored, &Value::Str("cache".into()));
1339 let snapshot = self
1340 .dispatch_to_derived("fetch_rest_order_book_safe",
1341 vec![symbol.clone(), limit.clone(), params.clone()])
1342 .await
1343 .unwrap_or(Value::Null);
1344 let index = self
1345 .dispatch_to_derived("get_cache_index", vec![snapshot.clone(), cache.clone()])
1346 .await;
1347 let idx = match index { Some(Value::Int(n)) => n, _ => -1 };
1348 if idx >= 0 {
1349 stored.reset(snapshot);
1350 let clen = match crate::runtime::get_array_length(&cache) { Value::Int(n) => n, _ => 0 };
1351 let deltas: Vec<Value> = (idx..clen)
1352 .map(|i| crate::get_value(&cache, &Value::Int(i)))
1353 .collect();
1354 self.dispatch_to_derived("handle_deltas", vec![stored.clone(), Value::List(deltas)]).await;
1355 crate::set_value(&mut stored, &Value::Str("cache".into()), Value::List(Vec::new()));
1356 crate::pro::ws_client::value_resolve(&client, &[stored.clone(), message_hash.clone()]);
1357 return;
1358 }
1359 tries += 1;
1360 }
1361 crate::pro::ws_client::value_reject(&client, &[err(&self.id), message_hash]);
1362 } }
1363
1364 fn watch(
1365 &mut self,
1366 url: Value,
1367 message_hash: Value,
1368 optional_args: &[Value],
1369 ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1370 let url_s = match &url { Value::Str(s) => s.to_string(), v => crate::runtime::stringify_param(v) };
1371 let hash_s = match &message_hash { Value::Str(s) => s.to_string(), v => crate::runtime::stringify_param(v) };
1372 let message = optional_args.get(0).cloned().unwrap_or(Value::Null);
1373 let subscribe_hash = optional_args.get(1).cloned().unwrap_or(message_hash.clone());
1374 let sub_hash_s = match &subscribe_hash { Value::Str(s) => s.to_string(), v => crate::runtime::stringify_param(v) };
1375 let subscription = optional_args.get(2).cloned().unwrap_or(Value::Null);
1376 self.ws_run(url_s, vec![hash_s], message, vec![sub_hash_s], subscription).await
1377 } }
1378
1379 fn watch_multiple(
1380 &mut self,
1381 url: Value,
1382 message_hashes: Value,
1383 optional_args: &[Value],
1384 ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1385 let url_s = match &url { Value::Str(s) => s.to_string(), v => crate::runtime::stringify_param(v) };
1386 let hashes = ws_string_list(&message_hashes);
1387 let message = optional_args.get(0).cloned().unwrap_or(Value::Null);
1388 let subscribe_hashes = ws_string_list(&optional_args.get(1).cloned().unwrap_or(Value::Null));
1389 let subscription = optional_args.get(2).cloned().unwrap_or(Value::Null);
1390 self.ws_run(url_s, hashes, message, subscribe_hashes, subscription).await
1391 } }
1392
1393 fn fetch_typed(
1394 &mut self,
1395 url: &str,
1396 method: &str,
1397 headers: HashMap<String, String>,
1398 body: Option<String>,
1399 ) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1400 let _fetch_call_count = HTTP_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1401 self.last_request_url = Value::Str(url.to_string().into());
1402 self.last_request_headers = Value::Map(headers.iter()
1403 .map(|(k, v)| (k.clone(), Value::Str(v.clone().into())))
1404 .collect());
1405 self.last_request_body = match &body {
1406 Some(b) => Value::Str(b.clone().into()),
1407 None => Value::Null,
1408 };
1409 if let Value::Dict(byUrl) = &self.mock_response_by_url {
1411 let mut fragments: Vec<&String> = byUrl.keys().collect();
1412 fragments.sort();
1413 for fragment in &fragments {
1414 if url.contains(fragment.as_str()) {
1415 return Ok(byUrl.get(*fragment).cloned().unwrap_or(Value::Null));
1416 }
1417 }
1418 if let Some(first) = fragments.first() {
1419 return Ok(byUrl.get(*first).cloned().unwrap_or(Value::Null));
1420 }
1421 }
1422 if !matches!(self.mock_response, Value::Null) {
1423 return Ok(self.mock_response.clone());
1424 }
1425 let proxy_defined = |v: &Value| matches!(v, Value::Str(s) if !s.is_empty());
1426 let used_proxies = [
1427 proxy_defined(&self.httpProxy) || proxy_defined(&self.http_proxy),
1428 proxy_defined(&self.httpsProxy) || proxy_defined(&self.https_proxy),
1429 proxy_defined(&self.socksProxy) || proxy_defined(&self.socks_proxy),
1430 ].iter().filter(|x| **x).count();
1431 if used_proxies > 1 {
1432 return Err(ExchangeError::new(
1433 "InvalidProxySettings",
1434 format!("{} you have multiple conflicting proxy settings, please use only one from: httpProxy, httpsProxy, socksProxy",
1435 match &self.id { Value::Str(s) => s.as_ref(), _ => "" }),
1436 ));
1437 }
1438 let client = self.http_client().clone();
1439 let method_parsed = reqwest::Method::from_bytes(method.as_bytes())
1440 .map_err(|_| ExchangeError::new("BadRequest", format!("invalid HTTP method: {method}")))?;
1441 let mut req = client.request(method_parsed, url);
1442 for (k, v) in &self.internals.headers { req = req.header(k, v); }
1443 for (k, v) in &headers { req = req.header(k, v); }
1444 if self.is_verbose() {
1445 eprintln!("[ccxt] {method} {url}");
1446 for (k, v) in &self.internals.headers { eprintln!("[ccxt] {k}: {v}"); }
1447 for (k, v) in &headers { eprintln!("[ccxt] {k}: {v}"); }
1448 if let Some(b) = &body {
1449 eprintln!("[ccxt] request body: {b}");
1450 }
1451 }
1452 if let Some(b) = body { req = req.body(b); }
1453 let __http_t0 = std::time::Instant::now();
1454 let resp = req.send().await?;
1455 let status = resp.status().as_u16();
1456 let reason = resp.status().canonical_reason().unwrap_or("");
1457 let text = resp.text().await?;
1458 HTTP_NANOS.fetch_add(__http_t0.elapsed().as_nanos() as u64,
1459 std::sync::atomic::Ordering::Relaxed);
1460 if self.is_verbose() {
1461 eprintln!("[ccxt] ← {status} {} bytes", text.len());
1462 const CAP: usize = 16384;
1463 if text.len() > CAP {
1464 eprintln!("[ccxt] response body: {}… ({} bytes total)",
1465 &text[..text.char_indices().take_while(|(i, _)| *i < CAP).last().map(|(i, c)| i + c.len_utf8()).unwrap_or(0)],
1466 text.len());
1467 } else {
1468 eprintln!("[ccxt] response body: {text}");
1469 }
1470 }
1471 let __json_t0 = std::time::Instant::now();
1472 let json = match serde_json::from_str::<serde_json::Value>(&text) {
1473 Ok(j) => Value::from_json(&j),
1474 Err(_) => Value::Null,
1475 };
1476 JSON_NANOS.fetch_add(__json_t0.elapsed().as_nanos() as u64,
1477 std::sync::atomic::Ordering::Relaxed);
1478 let handled = crate::exchange::DerivedExchange::handle_errors(
1481 self,
1482 Value::Int(status as i64),
1483 Value::Str(reason.into()),
1484 Value::Str(url.to_string().into()),
1485 Value::Str(method.to_string().into()),
1486 Value::Null,
1487 Value::Str(text.clone().into()),
1488 json.clone(),
1489 Value::Null,
1490 Value::Null,
1491 );
1492 if matches!(handled, Value::Null) {
1493 self.handle_http_status_code(
1494 Value::Int(status as i64),
1495 Value::Str(reason.into()),
1496 Value::Str(url.to_string().into()),
1497 Value::Str(method.to_string().into()),
1498 Value::Str(text.clone().into()),
1499 );
1500 }
1501 if status >= 400 {
1502 return Err(ExchangeError::new(
1503 if status == 429 { "RateLimitExceeded" }
1504 else if status >= 500 { "ExchangeNotAvailable" }
1505 else { "ExchangeError" },
1506 format!("HTTP {status}: {text}"),
1507 ));
1508 }
1509 if matches!(json, Value::Null) {
1510 return Ok(Value::Str(text.into()));
1511 }
1512 Ok(json)
1513 } }
1514
1515 fn request_typed(&mut self, path: &str, scope_segments: &[String], verb: &str, params: Value, cost: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1516 if matches!(self.mock_response, Value::Null) && matches!(self.mock_response_by_url, Value::Null) {
1518 self.throttle(&[cost]).await;
1519 }
1520 let api_arg = if scope_segments.len() == 1 {
1521 Value::Str(scope_segments[0].clone().into())
1522 } else {
1523 Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect())
1524 };
1525 let scope_lookup: String = scope_segments.first().cloned().unwrap_or_default();
1526 let signed = crate::exchange::DerivedExchange::sign(
1528 self,
1529 Value::Str(path.to_string().into()),
1530 api_arg,
1531 Value::Str(verb.to_string().into()),
1532 params.clone(),
1533 Value::Null,
1534 Value::Null,
1535 );
1536 if let Value::Dict(m) = &signed {
1537 let url = match m.get("url") { Some(Value::Str(s)) => s.to_string(), _ => String::new().into() };
1538 let method = match m.get("method") { Some(Value::Str(s)) => s.to_string(), _ => verb.to_string().into() };
1539 let body = match m.get("body") { Some(Value::Str(s)) => Some(s.to_string()), _ => None };
1540 let headers = match m.get("headers") {
1541 Some(Value::Dict(h)) => h.iter()
1542 .filter_map(|(k, v)| match v { Value::Str(s) => Some((k.clone(), s.to_string())), _ => None })
1543 .collect::<HashMap<_, _>>(),
1544 _ => HashMap::new(),
1545 };
1546 if !url.is_empty() {
1547 return self.fetch_typed(&url, &method, headers, body).await;
1548 }
1549 }
1550 let base = self.url_for_scope(&scope_lookup).ok_or_else(|| ExchangeError::new(
1551 "BadRequest",
1552 format!("no URL configured for api scope `{scope_lookup}`"),
1553 ))?;
1554 let imploded = self.implode_params(Value::Str(path.to_string().into()), params.clone());
1555 let path_str = match &imploded { Value::Str(s) => s.clone(), _ => path.to_string().into() };
1556 let consumed_keys = self.extract_path_params(path);
1557 let remaining_params = match params {
1558 Value::Dict(m) => {
1559 let mut keep = HashMap::new();
1560 let m = Arc::try_unwrap(m).unwrap_or_else(|a| (*a).clone());
1561 for (k, v) in m {
1562 if !consumed_keys.contains(&k) { keep.insert(k, v); }
1563 }
1564 Value::Map(keep)
1565 }
1566 other => other,
1567 };
1568 let mut url = format!("{}/{}", base.trim_end_matches('/'), path_str.trim_start_matches('/'));
1569 let mut body: Option<String> = None;
1570 let qs = match &remaining_params {
1571 Value::Dict(m) if !m.is_empty() => self.urlencode_kv(&remaining_params),
1572 _ => String::new(),
1573 };
1574 if verb == "GET" || verb == "DELETE" {
1575 if !qs.is_empty() {
1576 url = format!("{}?{}", url, qs);
1577 }
1578 } else if !qs.is_empty() {
1579 body = Some(qs);
1580 }
1581 let mut headers = HashMap::new();
1582 if scope_lookup != "public" {
1583 if let Value::Str(k) = &self.apiKey {
1584 headers.insert("X-MBX-APIKEY".to_string(), k.to_string());
1585 }
1586 }
1587 self.fetch_typed(&url, verb, headers, body).await
1588 } }
1589
1590 fn implicit_api_call(&mut self, name: &str, params: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1592 if self.internals.implicit_api.is_empty() {
1593 self.build_implicit_api();
1594 }
1595 let entry = self.internals.implicit_api.get(name).cloned();
1596 let (path, scope_segments, verb, config) = match entry {
1597 Some(t) => t,
1598 None => return Err(ExchangeError::new(
1599 "NotSupported",
1600 format!("implicit API method {name} not found in api block"),
1601 )),
1602 };
1603 let api = if scope_segments.len() == 1 {
1604 Value::Str(scope_segments[0].clone().into())
1605 } else {
1606 Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect())
1607 };
1608 let cost = if matches!(self.enableRateLimit, Value::Bool(true)) {
1609 self.call_dynamic(
1610 "calculate_rate_limiter_cost",
1611 vec![api, Value::Str(verb.clone().into()), Value::Str(path.clone().into()), params.clone(), config],
1612 ).await
1613 } else {
1614 Value::Null
1615 };
1616 self.request_typed(&path, &scope_segments, &verb, params, cost).await
1617 } }
1618
1619 #[doc(hidden)]
1620 fn implicit_api_rate_limit_cost(&mut self, name: &str, params: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1621 if self.internals.implicit_api.is_empty() {
1622 self.build_implicit_api();
1623 }
1624 let (path, scope_segments, verb, config) = self.internals.implicit_api
1625 .get(name)
1626 .cloned()
1627 .ok_or_else(|| ExchangeError::new("NotSupported", format!("implicit API method {name} not found in api block")))?;
1628 let api = if scope_segments.len() == 1 {
1629 Value::Str(scope_segments[0].clone().into())
1630 } else {
1631 Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect())
1632 };
1633 Ok(self.call_dynamic(
1634 "calculate_rate_limiter_cost",
1635 vec![api, Value::Str(verb.into()), Value::Str(path.into()), params, config],
1636 ).await)
1637 } }
1638
1639 fn call_method(&mut self, name: Value, args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1641 let n = match name { Value::Str(s) => s, _ => return Value::Null };
1642 let params = args.get(0).cloned().unwrap_or(Value::Map(HashMap::new()));
1643 match self.implicit_api_call(&n, params).await {
1644 Ok(v) => v,
1645 Err(e) => {
1646 if matches!(self.verbose, Value::Bool(true)) {
1647 eprintln!("[ccxt] {n} failed: {e}");
1648 }
1649 panic!("{e}");
1650 }
1651 }
1652 } }
1653
1654 fn load_markets(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1657 let reload = optional_args.get(0).cloned().unwrap_or(Value::Bool(false));
1658 let reload_b = matches!(reload, Value::Bool(true));
1659 if !reload_b && !self.markets.is_null() {
1660 return self.markets.clone();
1661 }
1662 let has_fetch_currencies = matches!(
1663 crate::get_value(&self.has, &Value::Str("fetchCurrencies".into())),
1664 Value::Bool(true),
1665 );
1666 let mut currencies = Value::Null;
1667 if has_fetch_currencies {
1668 if let Some(v) = self.dispatch_to_derived("fetch_currencies", Vec::new()).await {
1669 currencies = v;
1670 }
1671 }
1672 let fetched = match self.dispatch_to_derived("fetch_markets", Vec::new()).await {
1673 Some(v) => v,
1674 None => return Value::Null,
1675 };
1676 if matches!(fetched, Value::Null) {
1677 return self.markets.clone();
1678 }
1679 let preloaded_non_empty = matches!(&self.currencies, Value::Dict(m) if !m.is_empty());
1680 let currencies_arg = if matches!(¤cies, Value::Dict(m) if !m.is_empty()) {
1681 currencies
1682 } else if preloaded_non_empty {
1683 self.currencies.clone()
1684 } else {
1685 crate::exchange_stubs::synthesize_currencies_from_markets(&fetched, &self.precisionMode)
1686 };
1687 let is_prediction = matches!(
1688 crate::get_value(&self.has, &Value::Str("prediction".into())),
1689 Value::Bool(true),
1690 );
1691 if is_prediction {
1692 let _ = self.dispatch_to_derived("set_markets", vec![fetched, currencies_arg]).await;
1693 } else {
1694 <Self as crate::exchange_generated::ExchangeBase>::set_markets(self, fetched, &[currencies_arg]);
1695 }
1696 let markets_snapshot = self.markets.clone();
1701 if let Value::Dict(markets) = &markets_snapshot {
1702 if let Value::Dict(by_id_arc) = &self.markets_by_id {
1703 let mut by_id = (**by_id_arc).clone();
1704 for market in markets.values() {
1705 let id = crate::get_value(market, &Value::Str("id".into()));
1706 let id2 = crate::get_value(market, &Value::Str("id2".into()));
1707 if let (Value::Str(id2s), Value::Str(ids)) = (&id2, &id) {
1708 if id2s != ids && !id2s.is_empty() && !by_id.contains_key(id2s.as_ref()) {
1709 by_id.insert(id2s.to_string(), Value::List(vec![market.clone()]));
1710 }
1711 }
1712 }
1713 self.markets_by_id = Value::Map(by_id);
1714 }
1715 }
1716 self.markets.clone()
1717 } }
1718
1719 fn super_describe(&self) -> Value {
1722 <Self as crate::exchange_generated::ExchangeBase>::describe(self)
1723 }
1724 fn super_set_sandbox_mode(&mut self, enabled: Value) {
1725 <Self as crate::exchange_generated::ExchangeBase>::set_sandbox_mode(self, enabled);
1726 }
1727 fn super_safe_market(&self, id: Value, market: Value, delim: Value, market_type: Value) -> Value {
1728 <Self as crate::exchange_generated::ExchangeBase>::safe_market(self, &[id, market, delim, market_type])
1729 }
1730 fn super_handle_market_type_and_params(&self, method_name: Value, market: Value, params: Value, default_value: Value) -> Value {
1731 <Self as crate::exchange_generated::ExchangeBase>::handle_market_type_and_params(self, method_name, &[market, params, default_value])
1732 }
1733 fn super_market(&self, symbol: Value) -> Value {
1734 <Self as crate::exchange_generated::ExchangeBase>::market(self, symbol)
1735 }
1736 fn super_amount_to_precision(&self, symbol: Value, amount: Value) -> Value {
1737 <Self as crate::exchange_generated::ExchangeBase>::amount_to_precision(self, symbol, amount)
1738 }
1739 fn super_handle_margin_mode_and_params(&self, method_name: Value, params: Value, default_value: Value) -> Value {
1740 <Self as crate::exchange_generated::ExchangeBase>::handle_margin_mode_and_params(self, method_name, &[params, default_value])
1741 }
1742 fn super_safe_currency_code(&self, currency_id: Value, currency: Value) -> Value {
1743 <Self as crate::exchange_generated::ExchangeBase>::safe_currency_code(self, currency_id, &[currency])
1744 }
1745 fn super_set_markets(&mut self, markets: Value, currencies: Value) -> Value {
1746 <Self as crate::exchange_generated::ExchangeBase>::set_markets(self, markets, &[currencies])
1747 }
1748 fn super_network_id_to_code(&self, optional_args: &[Value]) -> Value {
1749 <Self as crate::exchange_generated::ExchangeBase>::network_id_to_code(self, optional_args)
1750 }
1751 fn super_network_code_to_id(&self, network_code: Value, optional_args: &[Value]) -> Value {
1752 <Self as crate::exchange_generated::ExchangeBase>::network_code_to_id(self, network_code, optional_args)
1753 }
1754 fn super_fetch_deposit_address(&mut self, code: Value, params: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
1755 self.fetch_deposit_address(code, &[params]).await
1756 } }
1757 fn super_load_markets(&mut self, reload: Value, params: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
1758 self.load_markets(&[reload, params]).await
1759 } }
1760}
1761
1762impl<T: crate::exchange_generated::ExchangeBase> ExchangeRuntime for T {}
1763
1764pub fn method_name_to_snake_case(name: &Value) -> String {
1780 let name = match name {
1781 Value::Str(name) if !name.is_empty() => name,
1782 _ => panic!(
1783 "{}",
1784 crate::exchange_errors::not_supported(format!(
1785 "dynamic method dispatch requires a non-empty string method name, got {name:?}"
1786 )),
1787 ),
1788 };
1789 let chars: Vec<char> = name.chars().collect();
1790 let mut out = String::with_capacity(name.len() + 4);
1791 for (i, &c) in chars.iter().enumerate() {
1792 if c.is_ascii_uppercase() {
1793 let lower_before = i > 0
1794 && (chars[i - 1].is_ascii_lowercase() || chars[i - 1].is_ascii_digit());
1795 let acronym_end = i > 0 && chars[i - 1].is_ascii_uppercase()
1796 && chars.get(i + 1).map(|next| next.is_ascii_lowercase()).unwrap_or(false);
1797 if lower_before || acronym_end {
1798 out.push('_');
1799 }
1800 out.push(c.to_ascii_lowercase());
1801 } else {
1802 out.push(c);
1803 }
1804 }
1805 out
1806}
1807
1808pub trait CallDynamicChecked: crate::exchange_generated::ExchangeBase {
1817 fn call_dynamic_checked(&mut self, name: Value, args: Vec<Value>) -> impl ::std::future::Future<Output = Value> + Send { async move {
1818 let snake = method_name_to_snake_case(&name);
1819 self.internals.dynamic_dispatch_miss = None;
1822 let out = self.call_dynamic(&snake, args).await;
1823 if self.internals.dynamic_dispatch_miss.as_deref() == Some(snake.as_str()) {
1826 self.internals.dynamic_dispatch_miss = None;
1827 panic!(
1828 "{}",
1829 crate::exchange_errors::not_supported(format!(
1830 "{} dynamic method {snake}() resolved to no dispatch arm and no implicit API endpoint",
1831 crate::runtime::stringify_param(&self.id),
1832 )),
1833 );
1834 }
1835 out
1836 } }
1837}
1838
1839impl<T: crate::exchange_generated::ExchangeBase> CallDynamicChecked for T {}
1840
1841pub struct BaseCore {
1847 pub exchange: Exchange,
1848}
1849impl BaseCore {
1850 pub fn new(exchange: Exchange) -> Self { Self { exchange } }
1851 pub fn into_inner(self) -> Exchange { self.exchange }
1852}
1853impl std::ops::Deref for BaseCore {
1854 type Target = Exchange;
1855 fn deref(&self) -> &Exchange { &self.exchange }
1856}
1857impl std::ops::DerefMut for BaseCore {
1858 fn deref_mut(&mut self) -> &mut Exchange { &mut self.exchange }
1859}
1860impl DerivedExchange for BaseCore {}
1861impl crate::exchange_generated::ExchangeBase for BaseCore {
1862 fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<Value>)
1863 -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>>
1864 {
1865 Box::pin(async move { self.call_dynamic_base(method, args).await })
1866 }
1867}
1868
1869impl Exchange {
1872 pub fn build_implicit_api(&mut self) {
1882 let mut map: HashMap<String, (String, Vec<String>, String, Value)> = HashMap::new();
1883 Self::walk_api_node(&self.api, &[], &mut map);
1884 self.internals.implicit_api = map;
1885 }
1886
1887 fn walk_api_node(
1888 node: &Value,
1889 crumbs: &[String],
1890 out: &mut HashMap<String, (String, Vec<String>, String, Value)>,
1891 ) {
1892 let known_verbs = ["get", "post", "put", "delete", "patch"];
1893 let last_is_verb = crumbs.last()
1894 .map(|c| known_verbs.iter().any(|v| *v == c.to_lowercase().as_str()))
1895 .unwrap_or(false);
1896 match node {
1897 Value::Dict(m) if last_is_verb => {
1901 let verb = crumbs.last().unwrap().to_lowercase();
1902 let scope_snake = Self::api_scope_from_crumbs(&crumbs[..crumbs.len() - 1]);
1904 let scope_segments: Vec<String> = crumbs[..crumbs.len() - 1].to_vec();
1910 for (path_key, endpoint_config) in m.iter() {
1911 let config = match endpoint_config {
1912 Value::Dict(_) => endpoint_config.clone(),
1913 Value::Int(_) | Value::Float(_) => Value::Map({
1914 let mut config = crate::value::HashMap::new();
1915 config.insert("cost".to_string(), endpoint_config.clone());
1916 config
1917 }),
1918 _ => Value::Map(crate::value::HashMap::new()),
1919 };
1920 Self::register_implicit(&verb, &scope_snake, &scope_segments, path_key, config, out);
1921 }
1922 }
1923 Value::Dict(m) => {
1924 for (key, child) in m.iter() {
1925 let mut next = crumbs.to_vec();
1926 next.push(key.clone());
1927 Self::walk_api_node(child, &next, out);
1928 }
1929 }
1930 Value::Arr(a) if last_is_verb => {
1932 let verb = crumbs.last().unwrap().to_lowercase();
1933 let scope_snake = Self::api_scope_from_crumbs(&crumbs[..crumbs.len() - 1]);
1934 let scope_segments: Vec<String> = crumbs[..crumbs.len() - 1].to_vec();
1935 for path in a.iter() {
1936 let (path_str, config) = match path {
1937 Value::Str(s) => (s.clone(), Value::Map(crate::value::HashMap::new())),
1938 Value::Dict(pm) => match pm.get("method").or_else(|| pm.get("path")) {
1939 Some(Value::Str(s)) => (s.clone(), path.clone()),
1940 _ => continue,
1941 },
1942 _ => continue,
1943 };
1944 Self::register_implicit(&verb, &scope_snake, &scope_segments, &path_str, config, out);
1945 }
1946 }
1947 _ => {}
1948 }
1949 }
1950
1951 fn api_scope_from_crumbs(crumbs: &[String]) -> String {
1952 crumbs.iter()
1956 .map(|s| s
1957 .chars()
1958 .enumerate()
1959 .flat_map(|(i, c)| {
1960 if c.is_ascii_uppercase() && i > 0 {
1961 vec!['_', c.to_ascii_lowercase()]
1962 } else {
1963 vec![c.to_ascii_lowercase()]
1964 }
1965 })
1966 .collect::<String>())
1967 .collect::<Vec<_>>()
1968 .join("_")
1969 }
1970
1971 fn register_implicit(
1972 verb: &str,
1973 scope_snake: &str,
1974 scope_segments: &[String],
1975 path: &str,
1976 config: Value,
1977 out: &mut HashMap<String, (String, Vec<String>, String, Value)>,
1978 ) {
1979 let camel: String = path
1988 .split(|c: char| !c.is_ascii_alphanumeric())
1989 .filter(|s| !s.is_empty())
1990 .map(|seg| {
1991 let mut chars = seg.chars();
1992 match chars.next() {
1993 None => String::new(),
1994 Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
1995 }
1996 })
1997 .collect();
1998 let snake = Self::to_snake_case(&camel);
2002 let snake_name = if snake.is_empty() {
2006 format!("{scope_snake}_{verb}")
2007 } else {
2008 format!("{scope_snake}_{verb}_{snake}")
2009 };
2010 let scope_camel: String = scope_segments.iter()
2015 .enumerate()
2016 .map(|(i, s)| {
2017 if i == 0 {
2018 s.to_string()
2019 } else {
2020 let mut chars = s.chars();
2021 match chars.next() {
2022 None => String::new(),
2023 Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
2024 }
2025 }
2026 })
2027 .collect();
2028 let verb_camel = {
2029 let mut chars = verb.chars();
2030 match chars.next() {
2031 None => String::new(),
2032 Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str().to_lowercase().as_str(),
2033 }
2034 };
2035 let camel_name = format!("{scope_camel}{verb_camel}{camel}");
2036 let camel_snake_name = Self::to_snake_case(&camel_name);
2046 let entry = (path.to_string(), scope_segments.to_vec(), verb.to_uppercase(), config);
2047 out.insert(snake_name, entry.clone());
2048 if !out.contains_key(&camel_snake_name) {
2049 out.insert(camel_snake_name, entry.clone());
2050 }
2051 if !out.contains_key(&camel_name) {
2052 out.insert(camel_name, entry);
2053 }
2054 }
2055
2056 fn to_snake_case(s: &str) -> String {
2057 let bytes: Vec<char> = s.chars().collect();
2059 let mut out = String::with_capacity(s.len() + 4);
2060 for i in 0..bytes.len() {
2061 let c = bytes[i];
2062 let prev = if i > 0 { Some(bytes[i - 1]) } else { None };
2063 let next = if i + 1 < bytes.len() { Some(bytes[i + 1]) } else { None };
2064 if c.is_ascii_uppercase() {
2065 let prev_lower_or_digit = prev
2066 .map(|p| p.is_ascii_lowercase() || p.is_ascii_digit())
2067 .unwrap_or(false);
2068 let prev_upper = prev.map(|p| p.is_ascii_uppercase()).unwrap_or(false);
2069 let next_lower = next.map(|n| n.is_ascii_lowercase()).unwrap_or(false);
2070 if prev_lower_or_digit {
2071 out.push('_');
2072 } else if prev_upper && next_lower {
2073 out.push('_');
2074 }
2075 }
2076 out.push(c.to_ascii_lowercase());
2077 }
2078 while out.contains("__") {
2080 out = out.replace("__", "_");
2081 }
2082 out.trim_matches('_').to_string()
2083 }
2084
2085 fn url_for_scope(&self, scope: &str) -> Option<String> {
2088 let api = crate::get_value(&self.urls, &Value::Str("api".into()));
2089 let scoped = crate::get_value(&api, &Value::Str(scope.to_string().into()));
2091 let raw = match scoped {
2092 Value::Str(s) => s,
2093 Value::Dict(m) => match m.get("rest").or_else(|| m.get("current")) {
2094 Some(Value::Str(s)) => s.clone(),
2095 _ => return self.fallback_rest_url(&api),
2096 },
2097 _ => return self.fallback_rest_url(&api),
2098 };
2099 Some(self.implode_hostname_typed(&raw))
2100 }
2101
2102 fn fallback_rest_url(&self, api: &Value) -> Option<String> {
2106 let rest = crate::get_value(api, &Value::Str("rest".into()));
2107 if let Value::Str(s) = rest {
2108 return Some(self.implode_hostname_typed(&s));
2109 }
2110 if let Value::Str(s) = api {
2112 return Some(self.implode_hostname_typed(s));
2113 }
2114 None
2115 }
2116
2117 fn implode_hostname_typed(&self, url: &str) -> String {
2119 let host = match &self.hostname {
2120 Value::Str(s) => s.clone(),
2121 _ => return url.to_string(),
2122 };
2123 url.replace("{hostname}", &host)
2124 }
2125
2126 fn extract_path_params(&self, path: &str) -> Vec<String> {
2132 let mut out: Vec<String> = vec![];
2133 let mut chars = path.chars().peekable();
2134 while let Some(c) = chars.next() {
2135 if c == '{' {
2136 let mut name = String::new();
2137 while let Some(&nc) = chars.peek() {
2138 if nc == '}' { chars.next(); break; }
2139 name.push(nc); chars.next();
2140 }
2141 if !name.is_empty() { out.push(name); }
2142 }
2143 }
2144 out
2145 }
2146}
2147
2148pub(crate) fn hash_raw(data: &[u8], algo: &str) -> Vec<u8> {
2151 match algo.to_ascii_lowercase().as_str() {
2152 "sha256" => { let mut h = Sha256::new(); h.update(data); h.finalize().to_vec() }
2153 "sha512" => { let mut h = Sha512::new(); h.update(data); h.finalize().to_vec() }
2154 "sha1" => { let mut h = Sha1::new(); h.update(data); h.finalize().to_vec() }
2155 "md5" => { let mut h = Md5::new(); h.update(data); h.finalize().to_vec() }
2156 "keccak" | "keccak256" => {
2157 use sha3::{Keccak256, Digest as _};
2158 let mut h = Keccak256::new();
2159 h.update(data);
2160 h.finalize().to_vec()
2161 }
2162 _ => Vec::new(),
2163 }
2164}
2165
2166type Eip712Types = std::collections::BTreeMap<String, Vec<(String, String)>>;
2170
2171fn eip712_base_type(ty: &str) -> &str {
2174 match ty.find('[') { Some(i) => &ty[..i], None => ty }
2175}
2176
2177fn eip712_encode_type(primary: &str, types: &Eip712Types) -> String {
2181 fn collect(name: &str, types: &Eip712Types, deps: &mut std::collections::BTreeSet<String>) {
2182 if let Some(fields) = types.get(name) {
2183 for (_, ty) in fields {
2184 let base = eip712_base_type(ty).to_string();
2185 if types.contains_key(&base) && deps.insert(base.clone()) {
2186 collect(&base, types, deps);
2187 }
2188 }
2189 }
2190 }
2191 let fmt = |name: &str| -> String {
2192 let fields = types.get(name).cloned().unwrap_or_default();
2193 let inner: Vec<String> = fields.iter().map(|(n, t)| format!("{t} {n}")).collect();
2194 format!("{}({})", name, inner.join(","))
2195 };
2196 let mut deps = std::collections::BTreeSet::new();
2197 collect(primary, types, &mut deps);
2198 deps.remove(primary);
2199 let mut out = fmt(primary);
2200 for dep in &deps { out.push_str(&fmt(dep)); } out
2202}
2203
2204pub(crate) fn eip712_encode(domain: &Value, types: &Value, message: &Value) -> Vec<u8> {
2205 let dm = match domain { Value::Dict(m) => m, _ => return Vec::new() };
2206 let mut domain_fields: Vec<(String, String)> = Vec::new();
2208 for (n, t) in [("name", "string"), ("version", "string"), ("chainId", "uint256"),
2209 ("verifyingContract", "address"), ("salt", "bytes32")] {
2210 if dm.contains_key(n) { domain_fields.push((n.to_string(), t.to_string())); }
2211 }
2212 let mut domain_types: Eip712Types = Eip712Types::new();
2214 domain_types.insert("EIP712Domain".to_string(), domain_fields);
2215 let domain_sep = eip712_hash_struct("EIP712Domain", domain, &domain_types);
2216
2217 let mut type_map: Eip712Types = Eip712Types::new();
2219 if let Value::Dict(m) = types {
2220 for (name, def) in m.iter() {
2221 if name == "EIP712Domain" { continue; }
2222 if let Value::Arr(arr) = def {
2223 let fields: Vec<(String, String)> = arr.iter().filter_map(|it| match it {
2224 Value::Dict(fm) => Some((
2225 fm.get("name")?.as_str()?.to_string(),
2226 fm.get("type")?.as_str()?.to_string(),
2227 )),
2228 _ => None,
2229 }).collect();
2230 type_map.insert(name.clone(), fields);
2231 }
2232 }
2233 }
2234 if type_map.is_empty() { return Vec::new(); }
2235 let referenced: std::collections::HashSet<String> = type_map.values()
2238 .flat_map(|fs| fs.iter().map(|(_, t)| eip712_base_type(t).to_string()))
2239 .collect();
2240 let primary = type_map.keys().find(|k| !referenced.contains(*k)).cloned()
2241 .unwrap_or_else(|| type_map.keys().next().cloned().unwrap_or_default());
2242 let struct_hash = eip712_hash_struct(&primary, message, &type_map);
2243 let mut out = vec![0x19u8, 0x01u8];
2244 out.extend_from_slice(&domain_sep);
2245 out.extend_from_slice(&struct_hash);
2246 out
2247}
2248
2249fn eip712_hash_struct(type_name: &str, data: &Value, types: &Eip712Types) -> Vec<u8> {
2252 let type_str = eip712_encode_type(type_name, types);
2253 let mut enc = hash_raw(type_str.as_bytes(), "keccak"); let dm = match data { Value::Dict(m) => Some(m), _ => None };
2255 let fields = types.get(type_name).cloned().unwrap_or_default();
2256 for (name, ty) in &fields {
2257 let v = dm.and_then(|m| m.get(name)).cloned().unwrap_or(Value::Null);
2258 let base = eip712_base_type(ty);
2259 if types.contains_key(base) {
2260 enc.extend_from_slice(&eip712_hash_struct(base, &v, types));
2262 } else {
2263 enc.extend_from_slice(&eip712_encode_value(ty, &v));
2264 }
2265 }
2266 hash_raw(&enc, "keccak")
2267}
2268
2269pub(crate) fn eip712_int_word(ty: &str, n: &num_bigint::BigInt) -> [u8; 32] {
2277 use num_bigint::{BigInt, Sign};
2278 let signed = ty.starts_with("int");
2279 let digits = ty.trim_start_matches(if signed { "int" } else { "uint" });
2280 let mut width: usize = if digits.is_empty() { 256 } else { digits.parse().unwrap_or(256) };
2281 if !((8..=256).contains(&width) && width % 8 == 0) { width = 256; }
2282 let mut out = [0u8; 32];
2283 if !signed {
2284 if n.sign() == Sign::Minus {
2285 panic!("eip712/abi: negative value {n} supplied for unsigned type {ty}");
2286 }
2287 let max = (BigInt::from(1) << width) - 1;
2288 if n > &max {
2289 panic!("eip712/abi: value {n} overflows {ty} (max {max})");
2290 }
2291 let (_, be) = n.to_bytes_be();
2292 let take = be.len().min(32);
2293 out[32 - take..].copy_from_slice(&be[be.len() - take..]);
2294 } else {
2295 let min = -(BigInt::from(1) << (width - 1));
2296 let max = (BigInt::from(1) << (width - 1)) - 1;
2297 if n < &min || n > &max {
2298 panic!("eip712/abi: value {n} out of range for {ty} ([{min}, {max}])");
2299 }
2300 if n.sign() == Sign::Minus { out = [0xff; 32]; }
2301 let be = n.to_signed_bytes_be();
2302 let take = be.len().min(32);
2303 out[32 - take..].copy_from_slice(&be[be.len() - take..]);
2304 }
2305 out
2306}
2307
2308fn eip712_encode_value(ty: &str, v: &Value) -> [u8; 32] {
2309 let mut out = [0u8; 32];
2310 if ty == "string" || ty == "bytes" {
2311 out.copy_from_slice(&hash_raw(&value_to_bytes(v), "keccak"));
2312 } else if ty.starts_with("bytes") {
2313 let b = eip712_bytes(v);
2315 let n = b.len().min(32);
2316 out[..n].copy_from_slice(&b[..n]);
2317 } else if ty == "address" {
2318 let b = eip712_bytes(v);
2320 let take = b.len().min(20);
2321 out[32 - take..].copy_from_slice(&b[b.len() - take..]);
2322 } else if ty == "bool" {
2323 if matches!(v, Value::Bool(true)) { out[31] = 1; }
2324 } else if ty.starts_with("uint") || ty.starts_with("int") {
2325 use num_bigint::BigInt;
2328 let n: BigInt = match v {
2329 Value::Int(i) => BigInt::from(*i),
2330 Value::Float(f) => BigInt::from(*f as i64),
2331 Value::Str(s) => {
2332 let t = s.trim();
2333 if let Some(h) = t.strip_prefix("0x") {
2334 BigInt::parse_bytes(h.as_bytes(), 16).unwrap_or_default()
2335 } else {
2336 BigInt::parse_bytes(t.as_bytes(), 10).unwrap_or_default()
2337 }
2338 }
2339 _ => BigInt::from(0),
2340 };
2341 out = eip712_int_word(ty, &n);
2342 }
2343 out
2344}
2345
2346fn eip712_bytes(v: &Value) -> Vec<u8> {
2348 match v {
2349 Value::Str(s) => {
2350 let h = s.strip_prefix("0x").unwrap_or(s);
2351 hex::decode(h).unwrap_or_else(|_| s.as_bytes().to_vec())
2352 }
2353 _ => value_to_bytes(v),
2354 }
2355}
2356
2357pub(crate) fn value_to_bytes(v: &Value) -> Vec<u8> {
2358 match v {
2359 Value::Str(s) => s.as_bytes().to_vec(),
2360 Value::Arr(a) => a.iter().filter_map(|x| match x {
2361 Value::Int(n) => Some(*n as u8),
2362 _ => None,
2363 }).collect(),
2364 _ => Vec::new(),
2365 }
2366}
2367
2368pub(crate) fn url_pct(s: &str) -> String {
2369 s.bytes().map(|b| match b {
2370 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
2371 _ => format!("%{b:02X}"),
2372 }).collect()
2373}
2374
2375#[cfg(test)]
2389mod method_name_snake_case_tests {
2390 use super::{method_name_to_snake_case, Exchange};
2391 use crate::Value;
2392
2393 fn snake(name: &str) -> String {
2394 method_name_to_snake_case(&Value::Str(name.to_string().into()))
2395 }
2396
2397 #[test]
2400 fn matches_the_transpiler_dispatch_arm_names() {
2401 assert_eq!(snake("fetchTransfers"), "fetch_transfers");
2403 assert_eq!(snake("fetchOHLCV"), "fetch_ohlcv"); assert_eq!(snake("fetchOpenOrdersWs"), "fetch_open_orders_ws");
2405 assert_eq!(snake("fetchL2OrderBook"), "fetch_l2_order_book"); assert_eq!(snake("getLeverageTiersPaginated"), "get_leverage_tiers_paginated");
2407 assert_eq!(snake("publicGetTicker24hr"), "public_get_ticker24hr"); assert_eq!(snake("webExchangeGetV3Assets"), "web_exchange_get_v3_assets");
2411 assert_eq!(snake("webApiGetAjaxCoinCoinInfo"), "web_api_get_ajax_coin_coin_info");
2412 assert_eq!(snake("parseHTTPResponse"), "parse_http_response");
2414 assert_eq!(snake("fetchOHLCVWs"), "fetch_ohlcv_ws");
2415 assert_eq!(snake("fetch"), "fetch");
2417 assert_eq!(snake("fetch_transfers"), "fetch_transfers");
2418 }
2419
2420 #[test]
2425 fn agrees_with_exchange_to_snake_case() {
2426 for name in [
2427 "fetchTransfers", "fetchOHLCV", "fetchOpenOrdersWs", "publicGetTicker24hr",
2428 "fetchL2OrderBook", "webExchangeGetV3Assets", "webApiGetAjaxCoinCoinInfo",
2429 "parseHTTPResponse", "fetchOHLCVWs", "privatePostSPEIWithdrawal",
2430 "sapiV3GetAsset", "fapiPublicGetTicker24hr", "publicGet10PublicTickers",
2431 "fetch", "fetchPositionsRisk", "createOrderWs", "fetchMyLiquidations",
2432 ] {
2433 assert_eq!(
2434 snake(name),
2435 Exchange::to_snake_case(name),
2436 "method_name_to_snake_case and Exchange::to_snake_case diverge on {name}",
2437 );
2438 }
2439 }
2440
2441 #[test]
2444 #[should_panic(expected = "NotSupported")]
2445 fn non_string_method_name_is_loud() {
2446 let _ = method_name_to_snake_case(&Value::Int(7));
2447 }
2448
2449 #[test]
2450 #[should_panic(expected = "NotSupported")]
2451 fn empty_method_name_is_loud() {
2452 let _ = method_name_to_snake_case(&Value::Str(String::new().into()));
2453 }
2454}
2455
2456#[cfg(test)]
2457mod eip712_int_tests {
2458 use super::eip712_int_word;
2459 use num_bigint::BigInt;
2460
2461 #[test]
2462 fn uint8_max_ok_and_int8_bounds_ok() {
2463 assert_eq!(eip712_int_word("uint8", &BigInt::from(255))[31], 255);
2464 let _ = eip712_int_word("int8", &BigInt::from(127));
2465 let _ = eip712_int_word("int8", &BigInt::from(-128));
2466 }
2467
2468 #[test]
2469 fn i64_u64_boundaries_ok() {
2470 let _ = eip712_int_word("int64", &BigInt::from(i64::MAX));
2471 let _ = eip712_int_word("int64", &BigInt::from(i64::MIN));
2472 let _ = eip712_int_word("uint64", &BigInt::from(u64::MAX));
2473 }
2474
2475 #[test]
2478 fn u64_plus_one_preserved_in_uint256() {
2479 let n = BigInt::from(u64::MAX) + 1;
2480 assert_eq!(eip712_int_word("uint256", &n)[23], 1);
2481 }
2482
2483 #[test]
2484 fn negative_int_is_twos_complement() {
2485 assert_eq!(eip712_int_word("int256", &BigInt::from(-1)), [0xff; 32]);
2486 }
2487
2488 #[test]
2489 #[should_panic(expected = "overflows")]
2490 fn uint8_overflow_rejected() { let _ = eip712_int_word("uint8", &BigInt::from(256)); }
2491
2492 #[test]
2493 #[should_panic(expected = "negative")]
2494 fn uint_negative_rejected() { let _ = eip712_int_word("uint256", &BigInt::from(-1)); }
2495
2496 #[test]
2497 #[should_panic(expected = "out of range")]
2498 fn int8_overflow_rejected() { let _ = eip712_int_word("int8", &BigInt::from(128)); }
2499
2500 #[test]
2501 #[should_panic(expected = "overflows")]
2502 fn uint64_plus_one_rejected() {
2503 let _ = eip712_int_word("uint64", &(BigInt::from(u64::MAX) + 1));
2504 }
2505}
2506
2507#[cfg(test)]
2508mod throttle_tests {
2509 use super::Exchange;
2510 use crate::Value;
2511
2512 #[test]
2513 fn implicit_api_retains_endpoint_cost_config() {
2514 let mut by_limit = crate::value::HashMap::new();
2515 by_limit.insert("cost".to_string(), Value::Int(2));
2516 by_limit.insert("byLimit".to_string(), Value::List(vec![
2517 Value::List(vec![Value::Int(100), Value::Int(5)]),
2518 ]));
2519 let mut endpoints = crate::value::HashMap::new();
2520 endpoints.insert("ticker".to_string(), Value::Float(0.1));
2521 endpoints.insert("depth".to_string(), Value::Map(by_limit.clone()));
2522 let mut verbs = crate::value::HashMap::new();
2523 verbs.insert("get".to_string(), Value::Map(endpoints));
2524 let mut api = crate::value::HashMap::new();
2525 api.insert("public".to_string(), Value::Map(verbs));
2526 let mut exchange = Exchange::new(None);
2527 exchange.api = Value::Map(api);
2528 exchange.build_implicit_api();
2529 let ticker_config = &exchange.internals.implicit_api["public_get_ticker"].3;
2530 assert_eq!(
2531 crate::get_value(ticker_config, &Value::Str("cost".into())),
2532 Value::Float(0.1),
2533 "numeric endpoint costs must be normalized to a config object"
2534 );
2535 let depth_config = &exchange.internals.implicit_api["public_get_depth"].3;
2536 assert_eq!(depth_config, &Value::Map(by_limit), "object endpoint config must be retained");
2537 }
2538
2539 #[tokio::test]
2541 async fn spaces_requests_by_rate_limit() {
2542 let mut ex = Exchange::new(None);
2543 ex.enableRateLimit = Value::Bool(true);
2544 ex.rateLimit = Value::Int(15); let start = std::time::Instant::now();
2546 for _ in 0..5 { ex.throttle(&[]).await; }
2547 let elapsed = start.elapsed().as_millis();
2548 assert!(elapsed >= 45, "throttle did not space requests: {elapsed}ms");
2550 }
2551
2552 #[tokio::test]
2554 async fn disabled_is_noop() {
2555 let mut ex = Exchange::new(None);
2556 ex.enableRateLimit = Value::Bool(false);
2557 ex.rateLimit = Value::Int(1000);
2558 let start = std::time::Instant::now();
2559 for _ in 0..5 { ex.throttle(&[]).await; }
2560 assert!(start.elapsed().as_millis() < 50, "disabled throttle slept");
2561 }
2562}
2563
2564#[cfg(all(test, feature = "engine"))]
2565mod cow_alias_tests {
2566 use super::Exchange;
2567 use crate::Value;
2568 use crate::runtime::get_array_length;
2569
2570 #[test]
2574 fn convert_ohlcv_to_trading_view_preserves_pushes() {
2575 use crate::exchange_generated::ExchangeBase;
2576 let ex = super::BaseCore::new(Exchange::new(None));
2577 let row = Value::List(vec![
2578 Value::Int(1_700_000_000_000), Value::Int(1), Value::Int(2),
2579 Value::Int(0), Value::Int(1), Value::Int(10),
2580 ]);
2581 let ohlcvs = Value::List(vec![row.clone(), row]);
2582 let r = ex.convert_ohlcv_to_trading_view(ohlcvs, &[]);
2583 for key in ["t", "o", "h", "l", "c", "v"] {
2584 let col = crate::get_value(&r, &Value::Str(key.to_string().into()));
2585 assert_eq!(get_array_length(&col), Value::Int(2),
2586 "result['{key}'] lost its pushes — COW write-back failed");
2587 }
2588 }
2589}
2590
2591#[cfg(test)]
2592mod http_error_tests {
2593 use super::{BaseCore, DerivedExchange, Exchange, ExchangeRuntime};
2594 use crate::Value;
2595 use futures::FutureExt;
2596 use std::io::{Read, Write};
2597
2598 fn serve_once(status_line: &'static str, body: &'static str) -> String {
2600 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2601 let url = format!("http://{}/", listener.local_addr().unwrap());
2602 std::thread::spawn(move || {
2603 let (mut stream, _) = listener.accept().unwrap();
2604 let mut request = [0u8; 4096];
2605 let _ = stream.read(&mut request);
2606 let response = format!(
2607 "HTTP/1.1 {status_line}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
2608 body.len(),
2609 );
2610 stream.write_all(response.as_bytes()).unwrap();
2611 });
2612 url
2613 }
2614
2615 struct EnvelopeCore {
2617 exchange: Exchange,
2618 }
2619 impl std::ops::Deref for EnvelopeCore {
2620 type Target = Exchange;
2621 fn deref(&self) -> &Exchange { &self.exchange }
2622 }
2623 impl std::ops::DerefMut for EnvelopeCore {
2624 fn deref_mut(&mut self) -> &mut Exchange { &mut self.exchange }
2625 }
2626 impl DerivedExchange for EnvelopeCore {
2627 fn handle_errors(&self, _code: Value, _reason: Value, _url: Value, _method: Value, _headers: Value, _body: Value, response: Value, _request_headers: Value, _request_body: Value) -> Value {
2628 let code = crate::get_value(&response, &Value::Str("code".into()));
2629 if !matches!(code, Value::Null) && code != Value::Str("0".into()) {
2630 panic!("{}", crate::exchange_errors::create_error("InsufficientFunds", "code 51008"));
2631 }
2632 Value::Null
2633 }
2634 }
2635 impl crate::exchange_generated::ExchangeBase for EnvelopeCore {
2636 fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<Value>)
2637 -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>>
2638 {
2639 Box::pin(async move { self.call_dynamic_base(method, args).await })
2640 }
2641 }
2642
2643 async fn fetch_error<C: ExchangeRuntime + Send>(core: &mut C, url: String) -> String {
2644 let outcome = std::panic::AssertUnwindSafe(core.fetch(Value::Str(url.into()), &[])).catch_unwind().await;
2645 match outcome {
2646 Ok(value) => format!("no error, returned {value:?}"),
2647 Err(payload) => payload.downcast_ref::<String>().cloned().unwrap_or_default(),
2648 }
2649 }
2650
2651 #[tokio::test]
2652 async fn an_error_in_a_2xx_body_reaches_handle_errors() {
2653 let url = serve_once("200 OK", r#"{"code":"51008","msg":"Insufficient balance"}"#);
2654 let mut core = EnvelopeCore { exchange: Exchange::new(None) };
2655 let error = fetch_error(&mut core, url).await;
2656 assert!(error.contains("InsufficientFunds"), "{error}");
2657 }
2658
2659 #[tokio::test]
2660 async fn a_status_in_http_exceptions_raises_its_class() {
2661 let url = serve_once("401 Unauthorized", "{}");
2662 let mut core = BaseCore::new(Exchange::new(None));
2663 let error = fetch_error(&mut core, url).await;
2664 assert!(error.contains("AuthenticationError"), "{error}");
2665 }
2666
2667 #[tokio::test]
2668 async fn a_status_outside_http_exceptions_still_fails() {
2669 let url = serve_once("402 Payment Required", "{}");
2670 let mut core = BaseCore::new(Exchange::new(None));
2671 let error = fetch_error(&mut core, url).await;
2672 assert!(error.contains("ExchangeError"), "{error}");
2673 }
2674}