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".to_string())),
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()));
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".to_string()),
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".to_string()),
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".to_string()));
539 m.insert("BCHSV".to_string(), Value::Str("BSV".to_string()));
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()));
563 e.insert("secondary".to_string(), Value::Str(s.to_string()));
564 e.insert("default".to_string(), Value::Str(d.to_string()));
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".to_string()));
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".to_string()));
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".to_string()));
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()));
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); }
732 if let Some(v) = safe_string(cfg, "name", None) { self.name = Value::Str(v); }
733 if let Some(v) = safe_string(cfg, "hostname", None) { self.hostname = Value::Str(v); }
734 let rate_limit = crate::get_value(cfg, &Value::Str("rateLimit".to_string()));
735 if matches!(rate_limit, Value::Int(_) | Value::Float(_)) { self.rateLimit = rate_limit; }
736 let timeout = crate::get_value(cfg, &Value::Str("timeout".to_string()));
737 if matches!(timeout, Value::Int(_) | Value::Float(_)) { self.timeout = timeout; }
738 let fetch_history_cache_size = crate::get_value(cfg, &Value::Str("fetchHistoryCacheSize".to_string()));
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".to_string()));
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); }
743 if let Some(v) = safe_string(cfg, "secret", None) { self.secret = Value::Str(v); }
744 if let Some(v) = safe_string(cfg, "password", None) { self.password = Value::Str(v); }
745 if let Some(v) = safe_string(cfg, "uid", None) { self.uid = Value::Str(v); }
746 if let Some(v) = safe_string(cfg, "walletAddress", None) { self.walletAddress = Value::Str(v); }
747 if let Some(v) = safe_string(cfg, "privateKey", None) { self.privateKey = Value::Str(v); }
748 if let Some(v) = safe_string(cfg, "token", None) { self.token = Value::Str(v); }
749 if let Some(v) = safe_string(cfg, "login", None) { self.login = Value::Str(v); }
750 if let Some(v) = safe_string(cfg, "accountId", None) { self.accountId = Value::Str(v); }
751 if let Some(v) = safe_string(cfg, "httpProxy", None) { self.httpProxy = Value::Str(v); }
752 if let Some(v) = safe_string(cfg, "httpsProxy", None) { self.httpsProxy = Value::Str(v); }
753 if let Some(v) = safe_string(cfg, "socksProxy", None) { self.socksProxy = Value::Str(v); }
754 if let Some(v) = safe_string(cfg, "wsProxy", None) { self.wsProxy = Value::Str(v); }
758 if let Some(v) = safe_string(cfg, "wssProxy", None) { self.wssProxy = Value::Str(v); }
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".to_string()));
766 let currencies = crate::get_value(cfg, &Value::Str("currencies".to_string()));
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".to_string()));
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".to_string()));
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));
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_str()) { 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_str()) { 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_str()) { 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_str()) { 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_str()), _ => match &self.user_agent {
880 Value::Str(s) => Some(s.as_str()), _ => 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));
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() };
926 let digest = match optional_args.get(0) {
927 Some(Value::Str(d)) => d.clone(),
928 _ => "hex".to_string(),
929 };
930 match self.hmac_typed(&dbytes, &sbytes, &h, &digest) {
931 Ok(v) => Value::Str(v),
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() };
956 let digest = match optional_args.get(0) {
957 Some(Value::Str(d)) => d.clone(),
958 _ => "hex".to_string(),
959 };
960 let raw = hash_raw(&dbytes, &a);
961 match digest.as_str() {
962 "binary" => Value::Array(raw.iter().map(|b| Value::Int(*b as i64)).collect()),
964 "base64" => Value::Str(B64.encode(&raw)),
965 _ => Value::Str(hex::encode(&raw)),
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))
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))
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)))
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.clone()],
1117 Value::Arr(a) => a
1118 .iter()
1119 .filter_map(|x| match x {
1120 Value::Str(s) => Some(s.clone()),
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.clone(), _ => crate::runtime::stringify_param(&url) };
1131 let method = optional_args.get(0).cloned().unwrap_or(Value::Str("GET".to_string()));
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.clone(), _ => "GET".to_string() };
1135 let body_str = match &body { Value::Str(s) => Some(s.clone()), _ => 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.clone())),
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) if e.kind == "InvalidProxySettings" => panic!("{}", e),
1156 Err(_) => Value::Null,
1163 }
1164 } }
1165
1166 fn ws_run(
1183 &mut self,
1184 url: String,
1185 hashes: Vec<String>,
1186 message: Value,
1187 subscribe_hashes: Vec<String>,
1188 subscription: Value,
1189 ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1190 let __ws_proxy = [&self.wsProxy, &self.ws_proxy, &self.wssProxy]
1191 .iter()
1192 .find_map(|v| match v { Value::Str(s) if !s.is_empty() => Some(s.clone()), _ => None });
1193 let client = match crate::pro::ws_client::ensure_client(&url, __ws_proxy).await {
1194 Ok(c) => c,
1195 Err(e) => panic!("{}", e),
1196 };
1197 if std::env::var("CCXT_WS_DEBUG").is_ok() {
1198 eprintln!("[wswait] {:?}", hashes);
1199 }
1200 client.note_futures(&hashes);
1201 let mut send_subscribe = subscribe_hashes.is_empty();
1205 for sh in &subscribe_hashes {
1206 if client.subscribe_once(sh, subscription.clone()) {
1207 send_subscribe = true;
1208 }
1209 }
1210 if send_subscribe && !matches!(message, Value::Null) {
1211 let payload = match &message {
1212 Value::Str(s) => s.clone(),
1213 v => v.to_json().to_string(),
1214 };
1215 client.send_text(payload);
1216 }
1217 crate::runtime::add_element_to_object(
1224 &mut self.clients,
1225 &Value::Str(url.clone()),
1226 crate::pro::ws_client::client_value(&url),
1227 );
1228 let nested_same = WS_DRIVEN_URLS
1232 .try_with(|s| s.lock().unwrap().contains(&url))
1233 .unwrap_or(false);
1234 if nested_same {
1235 return match client.take_settled(&hashes) {
1236 Some(Ok(v)) => v,
1237 _ => Value::Null,
1238 };
1239 }
1240 if WS_DRIVEN_URLS.try_with(|_| ()).is_ok() {
1244 WS_DRIVEN_URLS.with(|s| { s.lock().unwrap().insert(url.clone()); });
1245 let r = self.ws_drive_loop(client, hashes, url.clone()).await;
1246 WS_DRIVEN_URLS.with(|s| { s.lock().unwrap().remove(&url); });
1247 r
1248 } else {
1249 let mut set = std::collections::HashSet::new();
1250 set.insert(url.clone());
1251 WS_DRIVEN_URLS
1252 .scope(std::sync::Mutex::new(set), self.ws_drive_loop(client, hashes, url.clone()))
1253 .await
1254 }
1255 } }
1256
1257 fn ws_drive_loop(
1260 &mut self,
1261 client: std::sync::Arc<crate::pro::ws_client::ClientState>,
1262 hashes: Vec<String>,
1263 url: String,
1264 ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1265 loop {
1266 loop {
1272 let batch = crate::exchange_stubs::drain_spawn_queue();
1273 if batch.is_empty() { break; }
1274 for (method, args) in batch {
1275 if std::env::var("CCXT_WS_DEBUG").is_ok() {
1276 eprintln!("[wsdrain] {}", method);
1277 }
1278 if method == "load_order_book" {
1279 self.ws_load_order_book(args).await;
1280 } else {
1281 let _ = self.dispatch_to_derived(&method, args).await;
1282 }
1283 }
1284 }
1285 if let Some(settled) = client.take_settled(&hashes) {
1286 match settled {
1287 Ok(v) => return v,
1288 Err(e) => panic!(
1289 "{}",
1290 match &e {
1291 Value::Str(s) => s.clone(),
1292 v => crate::runtime::stringify_param(v),
1293 }
1294 ),
1295 }
1296 }
1297 let next_due = crate::exchange_stubs::next_spawn_due();
1302 let received = match next_due {
1303 Some(d) => match tokio::time::timeout(d, client.next_message()).await {
1304 Ok(m) => m,
1305 Err(_) => continue,
1307 },
1308 None => client.next_message().await,
1309 };
1310 let msg = match received {
1311 Some(m) => m,
1312 None => panic!("[NetworkError] {} websocket connection closed", url),
1313 };
1314 if std::env::var("CCXT_WS_DEBUG").is_ok() {
1315 let n: usize = std::env::var("CCXT_WS_DEBUG").ok()
1316 .and_then(|v| v.parse().ok()).filter(|v| *v > 1).unwrap_or(220);
1317 let s = msg.to_json().to_string();
1318 eprintln!("[wsmsg] {}", s.chars().take(n).collect::<String>());
1319 }
1320 let client_value = crate::pro::ws_client::client_value(&url);
1321 let _ = self
1322 .dispatch_to_derived("handle_message", vec![client_value, msg])
1323 .await;
1324 }
1325 } }
1326
1327 fn ws_load_order_book(
1332 &mut self,
1333 args: Vec<Value>,
1334 ) -> impl ::std::future::Future<Output = ()> + Send { async move {
1335 let client = args.get(0).cloned().unwrap_or(Value::Null);
1336 let message_hash = args.get(1).cloned().unwrap_or(Value::Null);
1337 let symbol = args.get(2).cloned().unwrap_or(Value::Null);
1338 let limit = args.get(3).cloned().unwrap_or(Value::Null);
1339 let params = args.get(4).cloned().unwrap_or(Value::Map(indexmap::IndexMap::new()));
1340 let err = |id: &Value| Value::Str(format!(
1341 "[ExchangeError] {} loadOrderBook() failed to synchronize",
1342 match id { Value::Str(s) => s.as_str(), _ => "" }));
1343 if !crate::runtime::in_op(&self.orderbooks, &symbol) {
1344 crate::pro::ws_client::value_reject(&client, &[err(&self.id), message_hash]);
1345 return;
1346 }
1347 let max_retries: i64 = 3;
1348 let mut tries = 0;
1349 while tries < max_retries {
1350 let mut stored = crate::get_value(&self.orderbooks, &symbol);
1351 let cache = crate::get_value(&stored, &Value::Str("cache".to_string()));
1352 let snapshot = self
1353 .dispatch_to_derived("fetch_rest_order_book_safe",
1354 vec![symbol.clone(), limit.clone(), params.clone()])
1355 .await
1356 .unwrap_or(Value::Null);
1357 let index = self
1358 .dispatch_to_derived("get_cache_index", vec![snapshot.clone(), cache.clone()])
1359 .await;
1360 let idx = match index { Some(Value::Int(n)) => n, _ => -1 };
1361 if idx >= 0 {
1362 stored.reset(snapshot);
1363 let clen = match crate::runtime::get_array_length(&cache) { Value::Int(n) => n, _ => 0 };
1364 let deltas: Vec<Value> = (idx..clen)
1365 .map(|i| crate::get_value(&cache, &Value::Int(i)))
1366 .collect();
1367 self.dispatch_to_derived("handle_deltas", vec![stored.clone(), Value::List(deltas)]).await;
1368 crate::set_value(&mut stored, &Value::Str("cache".to_string()), Value::List(Vec::new()));
1369 crate::pro::ws_client::value_resolve(&client, &[stored.clone(), message_hash.clone()]);
1370 return;
1371 }
1372 tries += 1;
1373 }
1374 crate::pro::ws_client::value_reject(&client, &[err(&self.id), message_hash]);
1375 } }
1376
1377 fn watch(
1378 &mut self,
1379 url: Value,
1380 message_hash: Value,
1381 optional_args: &[Value],
1382 ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1383 let url_s = match &url { Value::Str(s) => s.clone(), v => crate::runtime::stringify_param(v) };
1384 let hash_s = match &message_hash { Value::Str(s) => s.clone(), v => crate::runtime::stringify_param(v) };
1385 let message = optional_args.get(0).cloned().unwrap_or(Value::Null);
1386 let subscribe_hash = optional_args.get(1).cloned().unwrap_or(message_hash.clone());
1387 let sub_hash_s = match &subscribe_hash { Value::Str(s) => s.clone(), v => crate::runtime::stringify_param(v) };
1388 let subscription = optional_args.get(2).cloned().unwrap_or(Value::Null);
1389 self.ws_run(url_s, vec![hash_s], message, vec![sub_hash_s], subscription).await
1390 } }
1391
1392 fn watch_multiple(
1393 &mut self,
1394 url: Value,
1395 message_hashes: Value,
1396 optional_args: &[Value],
1397 ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1398 let url_s = match &url { Value::Str(s) => s.clone(), v => crate::runtime::stringify_param(v) };
1399 let hashes = ws_string_list(&message_hashes);
1400 let message = optional_args.get(0).cloned().unwrap_or(Value::Null);
1401 let subscribe_hashes = ws_string_list(&optional_args.get(1).cloned().unwrap_or(Value::Null));
1402 let subscription = optional_args.get(2).cloned().unwrap_or(Value::Null);
1403 self.ws_run(url_s, hashes, message, subscribe_hashes, subscription).await
1404 } }
1405
1406 fn fetch_typed(
1407 &mut self,
1408 url: &str,
1409 method: &str,
1410 headers: HashMap<String, String>,
1411 body: Option<String>,
1412 ) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1413 let _fetch_call_count = HTTP_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1414 self.last_request_url = Value::Str(url.to_string());
1415 self.last_request_headers = Value::Map(headers.iter()
1416 .map(|(k, v)| (k.clone(), Value::Str(v.clone())))
1417 .collect());
1418 self.last_request_body = match &body {
1419 Some(b) => Value::Str(b.clone()),
1420 None => Value::Null,
1421 };
1422 if let Value::Dict(byUrl) = &self.mock_response_by_url {
1424 let mut fragments: Vec<&String> = byUrl.keys().collect();
1425 fragments.sort();
1426 for fragment in &fragments {
1427 if url.contains(fragment.as_str()) {
1428 return Ok(byUrl.get(*fragment).cloned().unwrap_or(Value::Null));
1429 }
1430 }
1431 if let Some(first) = fragments.first() {
1432 return Ok(byUrl.get(*first).cloned().unwrap_or(Value::Null));
1433 }
1434 }
1435 if !matches!(self.mock_response, Value::Null) {
1436 return Ok(self.mock_response.clone());
1437 }
1438 let proxy_defined = |v: &Value| matches!(v, Value::Str(s) if !s.is_empty());
1439 let used_proxies = [
1440 proxy_defined(&self.httpProxy) || proxy_defined(&self.http_proxy),
1441 proxy_defined(&self.httpsProxy) || proxy_defined(&self.https_proxy),
1442 proxy_defined(&self.socksProxy) || proxy_defined(&self.socks_proxy),
1443 ].iter().filter(|x| **x).count();
1444 if used_proxies > 1 {
1445 return Err(ExchangeError::new(
1446 "InvalidProxySettings",
1447 format!("{} you have multiple conflicting proxy settings, please use only one from: httpProxy, httpsProxy, socksProxy",
1448 match &self.id { Value::Str(s) => s.as_str(), _ => "" }),
1449 ));
1450 }
1451 let client = self.http_client().clone();
1452 let method_parsed = reqwest::Method::from_bytes(method.as_bytes())
1453 .map_err(|_| ExchangeError::new("BadRequest", format!("invalid HTTP method: {method}")))?;
1454 let mut req = client.request(method_parsed, url);
1455 for (k, v) in &self.internals.headers { req = req.header(k, v); }
1456 for (k, v) in &headers { req = req.header(k, v); }
1457 if self.is_verbose() {
1458 eprintln!("[ccxt] {method} {url}");
1459 for (k, v) in &self.internals.headers { eprintln!("[ccxt] {k}: {v}"); }
1460 for (k, v) in &headers { eprintln!("[ccxt] {k}: {v}"); }
1461 if let Some(b) = &body {
1462 eprintln!("[ccxt] request body: {b}");
1463 }
1464 }
1465 if let Some(b) = body { req = req.body(b); }
1466 let __http_t0 = std::time::Instant::now();
1467 let resp = req.send().await?;
1468 let status = resp.status().as_u16();
1469 let text = resp.text().await?;
1470 HTTP_NANOS.fetch_add(__http_t0.elapsed().as_nanos() as u64,
1471 std::sync::atomic::Ordering::Relaxed);
1472 if self.is_verbose() {
1473 eprintln!("[ccxt] ← {status} {} bytes", text.len());
1474 const CAP: usize = 16384;
1475 if text.len() > CAP {
1476 eprintln!("[ccxt] response body: {}… ({} bytes total)",
1477 &text[..text.char_indices().take_while(|(i, _)| *i < CAP).last().map(|(i, c)| i + c.len_utf8()).unwrap_or(0)],
1478 text.len());
1479 } else {
1480 eprintln!("[ccxt] response body: {text}");
1481 }
1482 }
1483 let __json_t0 = std::time::Instant::now();
1484 let json = match serde_json::from_str::<serde_json::Value>(&text) {
1485 Ok(j) => Value::from_json(&j),
1486 Err(_) => Value::Null,
1487 };
1488 JSON_NANOS.fetch_add(__json_t0.elapsed().as_nanos() as u64,
1489 std::sync::atomic::Ordering::Relaxed);
1490 if status >= 400 {
1491 crate::exchange::DerivedExchange::handle_errors(
1493 self,
1494 Value::Int(status as i64),
1495 Value::Null,
1496 Value::Str(url.to_string()),
1497 Value::Str(method.to_string()),
1498 Value::Null,
1499 Value::Str(text.clone()),
1500 json.clone(),
1501 Value::Null,
1502 Value::Null,
1503 );
1504 return Err(ExchangeError::new(
1505 if status == 429 { "RateLimitExceeded" }
1506 else if status >= 500 { "ExchangeNotAvailable" }
1507 else { "ExchangeError" },
1508 format!("HTTP {status}: {text}"),
1509 ));
1510 }
1511 if matches!(json, Value::Null) {
1512 return Ok(Value::Str(text));
1513 }
1514 Ok(json)
1515 } }
1516
1517 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 {
1518 if matches!(self.mock_response, Value::Null) && matches!(self.mock_response_by_url, Value::Null) {
1520 self.throttle(&[cost]).await;
1521 }
1522 let api_arg = if scope_segments.len() == 1 {
1523 Value::Str(scope_segments[0].clone())
1524 } else {
1525 Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone())).collect())
1526 };
1527 let scope_lookup: String = scope_segments.first().cloned().unwrap_or_default();
1528 let signed = crate::exchange::DerivedExchange::sign(
1530 self,
1531 Value::Str(path.to_string()),
1532 api_arg,
1533 Value::Str(verb.to_string()),
1534 params.clone(),
1535 Value::Null,
1536 Value::Null,
1537 );
1538 if let Value::Dict(m) = &signed {
1539 let url = match m.get("url") { Some(Value::Str(s)) => s.clone(), _ => String::new() };
1540 let method = match m.get("method") { Some(Value::Str(s)) => s.clone(), _ => verb.to_string() };
1541 let body = match m.get("body") { Some(Value::Str(s)) => Some(s.clone()), _ => None };
1542 let headers = match m.get("headers") {
1543 Some(Value::Dict(h)) => h.iter()
1544 .filter_map(|(k, v)| match v { Value::Str(s) => Some((k.clone(), s.clone())), _ => None })
1545 .collect::<HashMap<_, _>>(),
1546 _ => HashMap::new(),
1547 };
1548 if !url.is_empty() {
1549 return self.fetch_typed(&url, &method, headers, body).await;
1550 }
1551 }
1552 let base = self.url_for_scope(&scope_lookup).ok_or_else(|| ExchangeError::new(
1553 "BadRequest",
1554 format!("no URL configured for api scope `{scope_lookup}`"),
1555 ))?;
1556 let imploded = self.implode_params(Value::Str(path.to_string()), params.clone());
1557 let path_str = match &imploded { Value::Str(s) => s.clone(), _ => path.to_string() };
1558 let consumed_keys = self.extract_path_params(path);
1559 let remaining_params = match params {
1560 Value::Dict(m) => {
1561 let mut keep = HashMap::new();
1562 let m = Arc::try_unwrap(m).unwrap_or_else(|a| (*a).clone());
1563 for (k, v) in m {
1564 if !consumed_keys.contains(&k) { keep.insert(k, v); }
1565 }
1566 Value::Map(keep)
1567 }
1568 other => other,
1569 };
1570 let mut url = format!("{}/{}", base.trim_end_matches('/'), path_str.trim_start_matches('/'));
1571 let mut body: Option<String> = None;
1572 let qs = match &remaining_params {
1573 Value::Dict(m) if !m.is_empty() => self.urlencode_kv(&remaining_params),
1574 _ => String::new(),
1575 };
1576 if verb == "GET" || verb == "DELETE" {
1577 if !qs.is_empty() {
1578 url = format!("{}?{}", url, qs);
1579 }
1580 } else if !qs.is_empty() {
1581 body = Some(qs);
1582 }
1583 let mut headers = HashMap::new();
1584 if scope_lookup != "public" {
1585 if let Value::Str(k) = &self.apiKey {
1586 headers.insert("X-MBX-APIKEY".to_string(), k.clone());
1587 }
1588 }
1589 self.fetch_typed(&url, verb, headers, body).await
1590 } }
1591
1592 fn implicit_api_call(&mut self, name: &str, params: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1594 if self.internals.implicit_api.is_empty() {
1595 self.build_implicit_api();
1596 }
1597 let entry = self.internals.implicit_api.get(name).cloned();
1598 let (path, scope_segments, verb, config) = match entry {
1599 Some(t) => t,
1600 None => return Err(ExchangeError::new(
1601 "NotSupported",
1602 format!("implicit API method {name} not found in api block"),
1603 )),
1604 };
1605 let api = if scope_segments.len() == 1 {
1606 Value::Str(scope_segments[0].clone())
1607 } else {
1608 Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone())).collect())
1609 };
1610 let cost = if matches!(self.enableRateLimit, Value::Bool(true)) {
1611 self.call_dynamic(
1612 "calculate_rate_limiter_cost",
1613 vec![api, Value::Str(verb.clone()), Value::Str(path.clone()), params.clone(), config],
1614 ).await
1615 } else {
1616 Value::Null
1617 };
1618 self.request_typed(&path, &scope_segments, &verb, params, cost).await
1619 } }
1620
1621 #[cfg(test)]
1622 fn implicit_api_rate_limit_cost(&mut self, name: &str, params: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1623 if self.internals.implicit_api.is_empty() {
1624 self.build_implicit_api();
1625 }
1626 let (path, scope_segments, verb, config) = self.internals.implicit_api
1627 .get(name)
1628 .cloned()
1629 .ok_or_else(|| ExchangeError::new("NotSupported", format!("implicit API method {name} not found in api block")))?;
1630 let api = if scope_segments.len() == 1 {
1631 Value::Str(scope_segments[0].clone())
1632 } else {
1633 Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone())).collect())
1634 };
1635 Ok(self.call_dynamic(
1636 "calculate_rate_limiter_cost",
1637 vec![api, Value::Str(verb), Value::Str(path), params, config],
1638 ).await)
1639 } }
1640
1641 fn call_method(&mut self, name: Value, args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1643 let n = match name { Value::Str(s) => s, _ => return Value::Null };
1644 let params = args.get(0).cloned().unwrap_or(Value::Map(HashMap::new()));
1645 match self.implicit_api_call(&n, params).await {
1646 Ok(v) => v,
1647 Err(e) => {
1648 if matches!(self.verbose, Value::Bool(true)) {
1649 eprintln!("[ccxt] {n} failed: {e}");
1650 }
1651 panic!("{e}");
1652 }
1653 }
1654 } }
1655
1656 fn load_markets(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1659 let reload = optional_args.get(0).cloned().unwrap_or(Value::Bool(false));
1660 let reload_b = matches!(reload, Value::Bool(true));
1661 if !reload_b && !self.markets.is_null() {
1662 return self.markets.clone();
1663 }
1664 let has_fetch_currencies = matches!(
1665 crate::get_value(&self.has, &Value::Str("fetchCurrencies".to_string())),
1666 Value::Bool(true),
1667 );
1668 let mut currencies = Value::Null;
1669 if has_fetch_currencies {
1670 if let Some(v) = self.dispatch_to_derived("fetch_currencies", Vec::new()).await {
1671 currencies = v;
1672 }
1673 }
1674 let fetched = match self.dispatch_to_derived("fetch_markets", Vec::new()).await {
1675 Some(v) => v,
1676 None => return Value::Null,
1677 };
1678 if matches!(fetched, Value::Null) {
1679 return self.markets.clone();
1680 }
1681 let preloaded_non_empty = matches!(&self.currencies, Value::Dict(m) if !m.is_empty());
1682 let currencies_arg = if matches!(¤cies, Value::Dict(m) if !m.is_empty()) {
1683 currencies
1684 } else if preloaded_non_empty {
1685 self.currencies.clone()
1686 } else {
1687 crate::exchange_stubs::synthesize_currencies_from_markets(&fetched, &self.precisionMode)
1688 };
1689 let is_prediction = matches!(
1690 crate::get_value(&self.has, &Value::Str("prediction".to_string())),
1691 Value::Bool(true),
1692 );
1693 if is_prediction {
1694 let _ = self.dispatch_to_derived("set_markets", vec![fetched, currencies_arg]).await;
1695 } else {
1696 <Self as crate::exchange_generated::ExchangeBase>::set_markets(self, fetched, &[currencies_arg]);
1697 }
1698 let markets_snapshot = self.markets.clone();
1703 if let Value::Dict(markets) = &markets_snapshot {
1704 if let Value::Dict(by_id_arc) = &self.markets_by_id {
1705 let mut by_id = (**by_id_arc).clone();
1706 for market in markets.values() {
1707 let id = crate::get_value(market, &Value::Str("id".to_string()));
1708 let id2 = crate::get_value(market, &Value::Str("id2".to_string()));
1709 if let (Value::Str(id2s), Value::Str(ids)) = (&id2, &id) {
1710 if id2s != ids && !id2s.is_empty() && !by_id.contains_key(id2s) {
1711 by_id.insert(id2s.clone(), Value::List(vec![market.clone()]));
1712 }
1713 }
1714 }
1715 self.markets_by_id = Value::Map(by_id);
1716 }
1717 }
1718 self.markets.clone()
1719 } }
1720
1721 fn super_describe(&self) -> Value {
1724 <Self as crate::exchange_generated::ExchangeBase>::describe(self)
1725 }
1726 fn super_set_sandbox_mode(&mut self, enabled: Value) {
1727 <Self as crate::exchange_generated::ExchangeBase>::set_sandbox_mode(self, enabled);
1728 }
1729 fn super_safe_market(&self, id: Value, market: Value, delim: Value, market_type: Value) -> Value {
1730 <Self as crate::exchange_generated::ExchangeBase>::safe_market(self, &[id, market, delim, market_type])
1731 }
1732 fn super_handle_market_type_and_params(&self, method_name: Value, market: Value, params: Value, default_value: Value) -> Value {
1733 <Self as crate::exchange_generated::ExchangeBase>::handle_market_type_and_params(self, method_name, &[market, params, default_value])
1734 }
1735 fn super_market(&self, symbol: Value) -> Value {
1736 <Self as crate::exchange_generated::ExchangeBase>::market(self, symbol)
1737 }
1738 fn super_amount_to_precision(&self, symbol: Value, amount: Value) -> Value {
1739 <Self as crate::exchange_generated::ExchangeBase>::amount_to_precision(self, symbol, amount)
1740 }
1741 fn super_handle_margin_mode_and_params(&self, method_name: Value, params: Value, default_value: Value) -> Value {
1742 <Self as crate::exchange_generated::ExchangeBase>::handle_margin_mode_and_params(self, method_name, &[params, default_value])
1743 }
1744 fn super_safe_currency_code(&self, currency_id: Value, currency: Value) -> Value {
1745 <Self as crate::exchange_generated::ExchangeBase>::safe_currency_code(self, currency_id, &[currency])
1746 }
1747 fn super_set_markets(&mut self, markets: Value, currencies: Value) -> Value {
1748 <Self as crate::exchange_generated::ExchangeBase>::set_markets(self, markets, &[currencies])
1749 }
1750 fn super_network_id_to_code(&self, optional_args: &[Value]) -> Value {
1751 <Self as crate::exchange_generated::ExchangeBase>::network_id_to_code(self, optional_args)
1752 }
1753 fn super_network_code_to_id(&self, network_code: Value, optional_args: &[Value]) -> Value {
1754 <Self as crate::exchange_generated::ExchangeBase>::network_code_to_id(self, network_code, optional_args)
1755 }
1756 fn super_fetch_deposit_address(&mut self, code: Value, params: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
1757 self.fetch_deposit_address(code, &[params]).await
1758 } }
1759 fn super_load_markets(&mut self, reload: Value, params: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
1760 self.load_markets(&[reload, params]).await
1761 } }
1762}
1763
1764impl<T: crate::exchange_generated::ExchangeBase> ExchangeRuntime for T {}
1765
1766pub fn method_name_to_snake_case(name: &Value) -> String {
1782 let name = match name {
1783 Value::Str(name) if !name.is_empty() => name,
1784 _ => panic!(
1785 "{}",
1786 crate::exchange_errors::not_supported(format!(
1787 "dynamic method dispatch requires a non-empty string method name, got {name:?}"
1788 )),
1789 ),
1790 };
1791 let chars: Vec<char> = name.chars().collect();
1792 let mut out = String::with_capacity(name.len() + 4);
1793 for (i, &c) in chars.iter().enumerate() {
1794 if c.is_ascii_uppercase() {
1795 let lower_before = i > 0
1796 && (chars[i - 1].is_ascii_lowercase() || chars[i - 1].is_ascii_digit());
1797 let acronym_end = i > 0 && chars[i - 1].is_ascii_uppercase()
1798 && chars.get(i + 1).map(|next| next.is_ascii_lowercase()).unwrap_or(false);
1799 if lower_before || acronym_end {
1800 out.push('_');
1801 }
1802 out.push(c.to_ascii_lowercase());
1803 } else {
1804 out.push(c);
1805 }
1806 }
1807 out
1808}
1809
1810pub trait CallDynamicChecked: crate::exchange_generated::ExchangeBase {
1819 fn call_dynamic_checked(&mut self, name: Value, args: Vec<Value>) -> impl ::std::future::Future<Output = Value> + Send { async move {
1820 let snake = method_name_to_snake_case(&name);
1821 self.internals.dynamic_dispatch_miss = None;
1824 let out = self.call_dynamic(&snake, args).await;
1825 if self.internals.dynamic_dispatch_miss.as_deref() == Some(snake.as_str()) {
1828 self.internals.dynamic_dispatch_miss = None;
1829 panic!(
1830 "{}",
1831 crate::exchange_errors::not_supported(format!(
1832 "{} dynamic method {snake}() resolved to no dispatch arm and no implicit API endpoint",
1833 crate::runtime::stringify_param(&self.id),
1834 )),
1835 );
1836 }
1837 out
1838 } }
1839}
1840
1841impl<T: crate::exchange_generated::ExchangeBase> CallDynamicChecked for T {}
1842
1843pub struct BaseCore {
1849 pub exchange: Exchange,
1850}
1851impl BaseCore {
1852 pub fn new(exchange: Exchange) -> Self { Self { exchange } }
1853 pub fn into_inner(self) -> Exchange { self.exchange }
1854}
1855impl std::ops::Deref for BaseCore {
1856 type Target = Exchange;
1857 fn deref(&self) -> &Exchange { &self.exchange }
1858}
1859impl std::ops::DerefMut for BaseCore {
1860 fn deref_mut(&mut self) -> &mut Exchange { &mut self.exchange }
1861}
1862impl DerivedExchange for BaseCore {}
1863impl crate::exchange_generated::ExchangeBase for BaseCore {
1864 fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<Value>)
1865 -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>>
1866 {
1867 Box::pin(async move { self.call_dynamic_base(method, args).await })
1868 }
1869}
1870
1871impl Exchange {
1874 pub fn build_implicit_api(&mut self) {
1884 let mut map: HashMap<String, (String, Vec<String>, String, Value)> = HashMap::new();
1885 Self::walk_api_node(&self.api, &[], &mut map);
1886 self.internals.implicit_api = map;
1887 }
1888
1889 fn walk_api_node(
1890 node: &Value,
1891 crumbs: &[String],
1892 out: &mut HashMap<String, (String, Vec<String>, String, Value)>,
1893 ) {
1894 let known_verbs = ["get", "post", "put", "delete", "patch"];
1895 let last_is_verb = crumbs.last()
1896 .map(|c| known_verbs.iter().any(|v| *v == c.to_lowercase().as_str()))
1897 .unwrap_or(false);
1898 match node {
1899 Value::Dict(m) if last_is_verb => {
1903 let verb = crumbs.last().unwrap().to_lowercase();
1904 let scope_snake = Self::api_scope_from_crumbs(&crumbs[..crumbs.len() - 1]);
1906 let scope_segments: Vec<String> = crumbs[..crumbs.len() - 1].to_vec();
1912 for (path_key, endpoint_config) in m.iter() {
1913 let config = match endpoint_config {
1914 Value::Dict(_) => endpoint_config.clone(),
1915 Value::Int(_) | Value::Float(_) => Value::Map({
1916 let mut config = crate::value::HashMap::new();
1917 config.insert("cost".to_string(), endpoint_config.clone());
1918 config
1919 }),
1920 _ => Value::Map(crate::value::HashMap::new()),
1921 };
1922 Self::register_implicit(&verb, &scope_snake, &scope_segments, path_key, config, out);
1923 }
1924 }
1925 Value::Dict(m) => {
1926 for (key, child) in m.iter() {
1927 let mut next = crumbs.to_vec();
1928 next.push(key.clone());
1929 Self::walk_api_node(child, &next, out);
1930 }
1931 }
1932 Value::Arr(a) if last_is_verb => {
1934 let verb = crumbs.last().unwrap().to_lowercase();
1935 let scope_snake = Self::api_scope_from_crumbs(&crumbs[..crumbs.len() - 1]);
1936 let scope_segments: Vec<String> = crumbs[..crumbs.len() - 1].to_vec();
1937 for path in a.iter() {
1938 let (path_str, config) = match path {
1939 Value::Str(s) => (s.clone(), Value::Map(crate::value::HashMap::new())),
1940 Value::Dict(pm) => match pm.get("method").or_else(|| pm.get("path")) {
1941 Some(Value::Str(s)) => (s.clone(), path.clone()),
1942 _ => continue,
1943 },
1944 _ => continue,
1945 };
1946 Self::register_implicit(&verb, &scope_snake, &scope_segments, &path_str, config, out);
1947 }
1948 }
1949 _ => {}
1950 }
1951 }
1952
1953 fn api_scope_from_crumbs(crumbs: &[String]) -> String {
1954 crumbs.iter()
1958 .map(|s| s
1959 .chars()
1960 .enumerate()
1961 .flat_map(|(i, c)| {
1962 if c.is_ascii_uppercase() && i > 0 {
1963 vec!['_', c.to_ascii_lowercase()]
1964 } else {
1965 vec![c.to_ascii_lowercase()]
1966 }
1967 })
1968 .collect::<String>())
1969 .collect::<Vec<_>>()
1970 .join("_")
1971 }
1972
1973 fn register_implicit(
1974 verb: &str,
1975 scope_snake: &str,
1976 scope_segments: &[String],
1977 path: &str,
1978 config: Value,
1979 out: &mut HashMap<String, (String, Vec<String>, String, Value)>,
1980 ) {
1981 let camel: String = path
1990 .split(|c: char| !c.is_ascii_alphanumeric())
1991 .filter(|s| !s.is_empty())
1992 .map(|seg| {
1993 let mut chars = seg.chars();
1994 match chars.next() {
1995 None => String::new(),
1996 Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
1997 }
1998 })
1999 .collect();
2000 let snake = Self::to_snake_case(&camel);
2004 let snake_name = if snake.is_empty() {
2008 format!("{scope_snake}_{verb}")
2009 } else {
2010 format!("{scope_snake}_{verb}_{snake}")
2011 };
2012 let scope_camel: String = scope_segments.iter()
2017 .enumerate()
2018 .map(|(i, s)| {
2019 if i == 0 {
2020 s.to_string()
2021 } else {
2022 let mut chars = s.chars();
2023 match chars.next() {
2024 None => String::new(),
2025 Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
2026 }
2027 }
2028 })
2029 .collect();
2030 let verb_camel = {
2031 let mut chars = verb.chars();
2032 match chars.next() {
2033 None => String::new(),
2034 Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str().to_lowercase().as_str(),
2035 }
2036 };
2037 let camel_name = format!("{scope_camel}{verb_camel}{camel}");
2038 let camel_snake_name = Self::to_snake_case(&camel_name);
2048 let entry = (path.to_string(), scope_segments.to_vec(), verb.to_uppercase(), config);
2049 out.insert(snake_name, entry.clone());
2050 if !out.contains_key(&camel_snake_name) {
2051 out.insert(camel_snake_name, entry.clone());
2052 }
2053 if !out.contains_key(&camel_name) {
2054 out.insert(camel_name, entry);
2055 }
2056 }
2057
2058 fn to_snake_case(s: &str) -> String {
2059 let bytes: Vec<char> = s.chars().collect();
2061 let mut out = String::with_capacity(s.len() + 4);
2062 for i in 0..bytes.len() {
2063 let c = bytes[i];
2064 let prev = if i > 0 { Some(bytes[i - 1]) } else { None };
2065 let next = if i + 1 < bytes.len() { Some(bytes[i + 1]) } else { None };
2066 if c.is_ascii_uppercase() {
2067 let prev_lower_or_digit = prev
2068 .map(|p| p.is_ascii_lowercase() || p.is_ascii_digit())
2069 .unwrap_or(false);
2070 let prev_upper = prev.map(|p| p.is_ascii_uppercase()).unwrap_or(false);
2071 let next_lower = next.map(|n| n.is_ascii_lowercase()).unwrap_or(false);
2072 if prev_lower_or_digit {
2073 out.push('_');
2074 } else if prev_upper && next_lower {
2075 out.push('_');
2076 }
2077 }
2078 out.push(c.to_ascii_lowercase());
2079 }
2080 while out.contains("__") {
2082 out = out.replace("__", "_");
2083 }
2084 out.trim_matches('_').to_string()
2085 }
2086
2087 fn url_for_scope(&self, scope: &str) -> Option<String> {
2090 let api = crate::get_value(&self.urls, &Value::Str("api".to_string()));
2091 let scoped = crate::get_value(&api, &Value::Str(scope.to_string()));
2093 let raw = match scoped {
2094 Value::Str(s) => s,
2095 Value::Dict(m) => match m.get("rest").or_else(|| m.get("current")) {
2096 Some(Value::Str(s)) => s.clone(),
2097 _ => return self.fallback_rest_url(&api),
2098 },
2099 _ => return self.fallback_rest_url(&api),
2100 };
2101 Some(self.implode_hostname_typed(&raw))
2102 }
2103
2104 fn fallback_rest_url(&self, api: &Value) -> Option<String> {
2108 let rest = crate::get_value(api, &Value::Str("rest".to_string()));
2109 if let Value::Str(s) = rest {
2110 return Some(self.implode_hostname_typed(&s));
2111 }
2112 if let Value::Str(s) = api {
2114 return Some(self.implode_hostname_typed(s));
2115 }
2116 None
2117 }
2118
2119 fn implode_hostname_typed(&self, url: &str) -> String {
2121 let host = match &self.hostname {
2122 Value::Str(s) => s.clone(),
2123 _ => return url.to_string(),
2124 };
2125 url.replace("{hostname}", &host)
2126 }
2127
2128 fn extract_path_params(&self, path: &str) -> Vec<String> {
2134 let mut out: Vec<String> = vec![];
2135 let mut chars = path.chars().peekable();
2136 while let Some(c) = chars.next() {
2137 if c == '{' {
2138 let mut name = String::new();
2139 while let Some(&nc) = chars.peek() {
2140 if nc == '}' { chars.next(); break; }
2141 name.push(nc); chars.next();
2142 }
2143 if !name.is_empty() { out.push(name); }
2144 }
2145 }
2146 out
2147 }
2148}
2149
2150pub(crate) fn hash_raw(data: &[u8], algo: &str) -> Vec<u8> {
2153 match algo.to_ascii_lowercase().as_str() {
2154 "sha256" => { let mut h = Sha256::new(); h.update(data); h.finalize().to_vec() }
2155 "sha512" => { let mut h = Sha512::new(); h.update(data); h.finalize().to_vec() }
2156 "sha1" => { let mut h = Sha1::new(); h.update(data); h.finalize().to_vec() }
2157 "md5" => { let mut h = Md5::new(); h.update(data); h.finalize().to_vec() }
2158 "keccak" | "keccak256" => {
2159 use sha3::{Keccak256, Digest as _};
2160 let mut h = Keccak256::new();
2161 h.update(data);
2162 h.finalize().to_vec()
2163 }
2164 _ => Vec::new(),
2165 }
2166}
2167
2168type Eip712Types = std::collections::BTreeMap<String, Vec<(String, String)>>;
2172
2173fn eip712_base_type(ty: &str) -> &str {
2176 match ty.find('[') { Some(i) => &ty[..i], None => ty }
2177}
2178
2179fn eip712_encode_type(primary: &str, types: &Eip712Types) -> String {
2183 fn collect(name: &str, types: &Eip712Types, deps: &mut std::collections::BTreeSet<String>) {
2184 if let Some(fields) = types.get(name) {
2185 for (_, ty) in fields {
2186 let base = eip712_base_type(ty).to_string();
2187 if types.contains_key(&base) && deps.insert(base.clone()) {
2188 collect(&base, types, deps);
2189 }
2190 }
2191 }
2192 }
2193 let fmt = |name: &str| -> String {
2194 let fields = types.get(name).cloned().unwrap_or_default();
2195 let inner: Vec<String> = fields.iter().map(|(n, t)| format!("{t} {n}")).collect();
2196 format!("{}({})", name, inner.join(","))
2197 };
2198 let mut deps = std::collections::BTreeSet::new();
2199 collect(primary, types, &mut deps);
2200 deps.remove(primary);
2201 let mut out = fmt(primary);
2202 for dep in &deps { out.push_str(&fmt(dep)); } out
2204}
2205
2206pub(crate) fn eip712_encode(domain: &Value, types: &Value, message: &Value) -> Vec<u8> {
2207 let dm = match domain { Value::Dict(m) => m, _ => return Vec::new() };
2208 let mut domain_fields: Vec<(String, String)> = Vec::new();
2210 for (n, t) in [("name", "string"), ("version", "string"), ("chainId", "uint256"),
2211 ("verifyingContract", "address"), ("salt", "bytes32")] {
2212 if dm.contains_key(n) { domain_fields.push((n.to_string(), t.to_string())); }
2213 }
2214 let mut domain_types: Eip712Types = Eip712Types::new();
2216 domain_types.insert("EIP712Domain".to_string(), domain_fields);
2217 let domain_sep = eip712_hash_struct("EIP712Domain", domain, &domain_types);
2218
2219 let mut type_map: Eip712Types = Eip712Types::new();
2221 if let Value::Dict(m) = types {
2222 for (name, def) in m.iter() {
2223 if name == "EIP712Domain" { continue; }
2224 if let Value::Arr(arr) = def {
2225 let fields: Vec<(String, String)> = arr.iter().filter_map(|it| match it {
2226 Value::Dict(fm) => Some((
2227 fm.get("name")?.as_str()?.to_string(),
2228 fm.get("type")?.as_str()?.to_string(),
2229 )),
2230 _ => None,
2231 }).collect();
2232 type_map.insert(name.clone(), fields);
2233 }
2234 }
2235 }
2236 if type_map.is_empty() { return Vec::new(); }
2237 let referenced: std::collections::HashSet<String> = type_map.values()
2240 .flat_map(|fs| fs.iter().map(|(_, t)| eip712_base_type(t).to_string()))
2241 .collect();
2242 let primary = type_map.keys().find(|k| !referenced.contains(*k)).cloned()
2243 .unwrap_or_else(|| type_map.keys().next().cloned().unwrap_or_default());
2244 let struct_hash = eip712_hash_struct(&primary, message, &type_map);
2245 let mut out = vec![0x19u8, 0x01u8];
2246 out.extend_from_slice(&domain_sep);
2247 out.extend_from_slice(&struct_hash);
2248 out
2249}
2250
2251fn eip712_hash_struct(type_name: &str, data: &Value, types: &Eip712Types) -> Vec<u8> {
2254 let type_str = eip712_encode_type(type_name, types);
2255 let mut enc = hash_raw(type_str.as_bytes(), "keccak"); let dm = match data { Value::Dict(m) => Some(m), _ => None };
2257 let fields = types.get(type_name).cloned().unwrap_or_default();
2258 for (name, ty) in &fields {
2259 let v = dm.and_then(|m| m.get(name)).cloned().unwrap_or(Value::Null);
2260 let base = eip712_base_type(ty);
2261 if types.contains_key(base) {
2262 enc.extend_from_slice(&eip712_hash_struct(base, &v, types));
2264 } else {
2265 enc.extend_from_slice(&eip712_encode_value(ty, &v));
2266 }
2267 }
2268 hash_raw(&enc, "keccak")
2269}
2270
2271pub(crate) fn eip712_int_word(ty: &str, n: &num_bigint::BigInt) -> [u8; 32] {
2279 use num_bigint::{BigInt, Sign};
2280 let signed = ty.starts_with("int");
2281 let digits = ty.trim_start_matches(if signed { "int" } else { "uint" });
2282 let mut width: usize = if digits.is_empty() { 256 } else { digits.parse().unwrap_or(256) };
2283 if !((8..=256).contains(&width) && width % 8 == 0) { width = 256; }
2284 let mut out = [0u8; 32];
2285 if !signed {
2286 if n.sign() == Sign::Minus {
2287 panic!("eip712/abi: negative value {n} supplied for unsigned type {ty}");
2288 }
2289 let max = (BigInt::from(1) << width) - 1;
2290 if n > &max {
2291 panic!("eip712/abi: value {n} overflows {ty} (max {max})");
2292 }
2293 let (_, be) = n.to_bytes_be();
2294 let take = be.len().min(32);
2295 out[32 - take..].copy_from_slice(&be[be.len() - take..]);
2296 } else {
2297 let min = -(BigInt::from(1) << (width - 1));
2298 let max = (BigInt::from(1) << (width - 1)) - 1;
2299 if n < &min || n > &max {
2300 panic!("eip712/abi: value {n} out of range for {ty} ([{min}, {max}])");
2301 }
2302 if n.sign() == Sign::Minus { out = [0xff; 32]; }
2303 let be = n.to_signed_bytes_be();
2304 let take = be.len().min(32);
2305 out[32 - take..].copy_from_slice(&be[be.len() - take..]);
2306 }
2307 out
2308}
2309
2310fn eip712_encode_value(ty: &str, v: &Value) -> [u8; 32] {
2311 let mut out = [0u8; 32];
2312 if ty == "string" || ty == "bytes" {
2313 out.copy_from_slice(&hash_raw(&value_to_bytes(v), "keccak"));
2314 } else if ty.starts_with("bytes") {
2315 let b = eip712_bytes(v);
2317 let n = b.len().min(32);
2318 out[..n].copy_from_slice(&b[..n]);
2319 } else if ty == "address" {
2320 let b = eip712_bytes(v);
2322 let take = b.len().min(20);
2323 out[32 - take..].copy_from_slice(&b[b.len() - take..]);
2324 } else if ty == "bool" {
2325 if matches!(v, Value::Bool(true)) { out[31] = 1; }
2326 } else if ty.starts_with("uint") || ty.starts_with("int") {
2327 use num_bigint::BigInt;
2330 let n: BigInt = match v {
2331 Value::Int(i) => BigInt::from(*i),
2332 Value::Float(f) => BigInt::from(*f as i64),
2333 Value::Str(s) => {
2334 let t = s.trim();
2335 if let Some(h) = t.strip_prefix("0x") {
2336 BigInt::parse_bytes(h.as_bytes(), 16).unwrap_or_default()
2337 } else {
2338 BigInt::parse_bytes(t.as_bytes(), 10).unwrap_or_default()
2339 }
2340 }
2341 _ => BigInt::from(0),
2342 };
2343 out = eip712_int_word(ty, &n);
2344 }
2345 out
2346}
2347
2348fn eip712_bytes(v: &Value) -> Vec<u8> {
2350 match v {
2351 Value::Str(s) => {
2352 let h = s.strip_prefix("0x").unwrap_or(s);
2353 hex::decode(h).unwrap_or_else(|_| s.as_bytes().to_vec())
2354 }
2355 _ => value_to_bytes(v),
2356 }
2357}
2358
2359pub(crate) fn value_to_bytes(v: &Value) -> Vec<u8> {
2360 match v {
2361 Value::Str(s) => s.as_bytes().to_vec(),
2362 Value::Arr(a) => a.iter().filter_map(|x| match x {
2363 Value::Int(n) => Some(*n as u8),
2364 _ => None,
2365 }).collect(),
2366 _ => Vec::new(),
2367 }
2368}
2369
2370pub(crate) fn url_pct(s: &str) -> String {
2371 s.bytes().map(|b| match b {
2372 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
2373 _ => format!("%{b:02X}"),
2374 }).collect()
2375}
2376
2377#[cfg(all(test, feature = "transpiled-base"))]
2384mod response_mock_tests {
2385 use super::ExchangeRuntime;
2386 use crate::{get_value, Value};
2387
2388 #[tokio::test]
2389 async fn response_mock_serves_multiple_requests_until_reset() {
2390 let config = Value::from_json(&serde_json::json!({
2392 "httpProxy": "http://fake:8080", "httpsProxy": "http://fake:8080",
2393 "enableRateLimit": false,
2394 }));
2395 let mut exchange = crate::exchanges::binance::BinanceCore::new(Some(config));
2396 let response = Value::from_json(&serde_json::json!({ "price": "100" }));
2397 exchange.exchange.mock_response = response.clone();
2398 for symbol in ["BTCUSDT", "ETHUSDT"] {
2399 let params = Value::from_json(&serde_json::json!({ "symbol": symbol }));
2400 let result = exchange.request_typed(
2401 "ticker/price", &["public".to_string()], "GET", params, Value::Int(1),
2402 ).await.expect("each request must use the same mock without network access");
2403 assert_eq!(result, response);
2404 assert_eq!(exchange.exchange.last_request_url, Value::Str(format!(
2405 "https://api.binance.com/api/v3/ticker/price?symbol={symbol}",
2406 )));
2407 }
2408 exchange.exchange.mock_response = Value::Null;
2409 let error = exchange.request_typed(
2410 "ticker/price", &["public".to_string()], "GET", Value::Null, Value::Int(1),
2411 ).await.expect_err("reset must restore the normal transport path");
2412 assert!(error.to_string().contains("InvalidProxySettings"));
2413 }
2414
2415 #[tokio::test]
2416 async fn response_mock_preserves_public_request_url() {
2417 let mut exchange = crate::exchanges::binance::BinanceCore::new(None);
2418 let response = Value::from_json(&serde_json::json!({ "price": "100" }));
2419 exchange.exchange.mock_response = response.clone();
2420 let params = Value::from_json(&serde_json::json!({ "symbol": "BTCUSDT" }));
2421 let result = exchange.request_typed(
2422 "ticker/price", &["public".to_string()], "GET", params, Value::Int(1),
2423 ).await.expect("mock response must not require network access");
2424 assert_eq!(result, response);
2425 assert_eq!(exchange.exchange.last_request_url, Value::Str(
2426 "https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT".to_string(),
2427 ));
2428 assert_eq!(exchange.exchange.last_request_body, Value::Null);
2429 }
2430
2431 #[tokio::test]
2432 async fn response_mock_preserves_private_request_headers_and_body() {
2433 let config = Value::from_json(&serde_json::json!({
2434 "apiKey": "fixture-key", "secret": "fixture-secret",
2435 }));
2436 let mut exchange = crate::exchanges::binance::BinanceCore::new(Some(config));
2437 let response = Value::from_json(&serde_json::json!({ "orderId": 123 }));
2438 exchange.exchange.mock_response = response.clone();
2439 let params = Value::from_json(&serde_json::json!({
2440 "symbol": "BTCUSDT", "side": "BUY", "type": "MARKET", "quantity": "1",
2441 }));
2442 let result = exchange.request_typed(
2443 "order", &["private".to_string()], "POST", params, Value::Int(1),
2444 ).await.expect("signed mock response must not require network access");
2445 assert_eq!(result, response);
2446 assert_eq!(exchange.exchange.last_request_url, Value::Str(
2447 "https://api.binance.com/api/v3/order".to_string(),
2448 ));
2449 assert_eq!(get_value(&exchange.exchange.last_request_headers,
2450 &Value::Str("X-MBX-APIKEY".to_string())), Value::Str("fixture-key".to_string()));
2451 let Value::Str(body) = &exchange.exchange.last_request_body else {
2452 panic!("signed POST must retain its encoded body");
2453 };
2454 assert!(body.contains("symbol=BTCUSDT"));
2455 assert!(body.contains("signature="));
2456 }
2457}
2458
2459#[cfg(test)]
2466mod method_name_snake_case_tests {
2467 use super::{method_name_to_snake_case, Exchange};
2468 use crate::Value;
2469
2470 fn snake(name: &str) -> String {
2471 method_name_to_snake_case(&Value::Str(name.to_string()))
2472 }
2473
2474 #[test]
2477 fn matches_the_transpiler_dispatch_arm_names() {
2478 assert_eq!(snake("fetchTransfers"), "fetch_transfers");
2480 assert_eq!(snake("fetchOHLCV"), "fetch_ohlcv"); assert_eq!(snake("fetchOpenOrdersWs"), "fetch_open_orders_ws");
2482 assert_eq!(snake("fetchL2OrderBook"), "fetch_l2_order_book"); assert_eq!(snake("getLeverageTiersPaginated"), "get_leverage_tiers_paginated");
2484 assert_eq!(snake("publicGetTicker24hr"), "public_get_ticker24hr"); assert_eq!(snake("webExchangeGetV3Assets"), "web_exchange_get_v3_assets");
2488 assert_eq!(snake("webApiGetAjaxCoinCoinInfo"), "web_api_get_ajax_coin_coin_info");
2489 assert_eq!(snake("parseHTTPResponse"), "parse_http_response");
2491 assert_eq!(snake("fetchOHLCVWs"), "fetch_ohlcv_ws");
2492 assert_eq!(snake("fetch"), "fetch");
2494 assert_eq!(snake("fetch_transfers"), "fetch_transfers");
2495 }
2496
2497 #[test]
2502 fn agrees_with_exchange_to_snake_case() {
2503 for name in [
2504 "fetchTransfers", "fetchOHLCV", "fetchOpenOrdersWs", "publicGetTicker24hr",
2505 "fetchL2OrderBook", "webExchangeGetV3Assets", "webApiGetAjaxCoinCoinInfo",
2506 "parseHTTPResponse", "fetchOHLCVWs", "privatePostSPEIWithdrawal",
2507 "sapiV3GetAsset", "fapiPublicGetTicker24hr", "publicGet10PublicTickers",
2508 "fetch", "fetchPositionsRisk", "createOrderWs", "fetchMyLiquidations",
2509 ] {
2510 assert_eq!(
2511 snake(name),
2512 Exchange::to_snake_case(name),
2513 "method_name_to_snake_case and Exchange::to_snake_case diverge on {name}",
2514 );
2515 }
2516 }
2517
2518 #[test]
2521 #[should_panic(expected = "NotSupported")]
2522 fn non_string_method_name_is_loud() {
2523 let _ = method_name_to_snake_case(&Value::Int(7));
2524 }
2525
2526 #[test]
2527 #[should_panic(expected = "NotSupported")]
2528 fn empty_method_name_is_loud() {
2529 let _ = method_name_to_snake_case(&Value::Str(String::new()));
2530 }
2531}
2532
2533#[cfg(test)]
2534mod eip712_int_tests {
2535 use super::eip712_int_word;
2536 use num_bigint::BigInt;
2537
2538 #[test]
2539 fn uint8_max_ok_and_int8_bounds_ok() {
2540 assert_eq!(eip712_int_word("uint8", &BigInt::from(255))[31], 255);
2541 let _ = eip712_int_word("int8", &BigInt::from(127));
2542 let _ = eip712_int_word("int8", &BigInt::from(-128));
2543 }
2544
2545 #[test]
2546 fn i64_u64_boundaries_ok() {
2547 let _ = eip712_int_word("int64", &BigInt::from(i64::MAX));
2548 let _ = eip712_int_word("int64", &BigInt::from(i64::MIN));
2549 let _ = eip712_int_word("uint64", &BigInt::from(u64::MAX));
2550 }
2551
2552 #[test]
2555 fn u64_plus_one_preserved_in_uint256() {
2556 let n = BigInt::from(u64::MAX) + 1;
2557 assert_eq!(eip712_int_word("uint256", &n)[23], 1);
2558 }
2559
2560 #[test]
2561 fn negative_int_is_twos_complement() {
2562 assert_eq!(eip712_int_word("int256", &BigInt::from(-1)), [0xff; 32]);
2563 }
2564
2565 #[test]
2566 #[should_panic(expected = "overflows")]
2567 fn uint8_overflow_rejected() { let _ = eip712_int_word("uint8", &BigInt::from(256)); }
2568
2569 #[test]
2570 #[should_panic(expected = "negative")]
2571 fn uint_negative_rejected() { let _ = eip712_int_word("uint256", &BigInt::from(-1)); }
2572
2573 #[test]
2574 #[should_panic(expected = "out of range")]
2575 fn int8_overflow_rejected() { let _ = eip712_int_word("int8", &BigInt::from(128)); }
2576
2577 #[test]
2578 #[should_panic(expected = "overflows")]
2579 fn uint64_plus_one_rejected() {
2580 let _ = eip712_int_word("uint64", &(BigInt::from(u64::MAX) + 1));
2581 }
2582}
2583
2584#[cfg(test)]
2585mod throttle_tests {
2586 use super::Exchange;
2587 use crate::Value;
2588
2589 #[test]
2590 fn implicit_api_retains_endpoint_cost_config() {
2591 let mut by_limit = crate::value::HashMap::new();
2592 by_limit.insert("cost".to_string(), Value::Int(2));
2593 by_limit.insert("byLimit".to_string(), Value::List(vec![
2594 Value::List(vec![Value::Int(100), Value::Int(5)]),
2595 ]));
2596 let mut endpoints = crate::value::HashMap::new();
2597 endpoints.insert("ticker".to_string(), Value::Float(0.1));
2598 endpoints.insert("depth".to_string(), Value::Map(by_limit.clone()));
2599 let mut verbs = crate::value::HashMap::new();
2600 verbs.insert("get".to_string(), Value::Map(endpoints));
2601 let mut api = crate::value::HashMap::new();
2602 api.insert("public".to_string(), Value::Map(verbs));
2603 let mut exchange = Exchange::new(None);
2604 exchange.api = Value::Map(api);
2605 exchange.build_implicit_api();
2606 let ticker_config = &exchange.internals.implicit_api["public_get_ticker"].3;
2607 assert_eq!(
2608 crate::get_value(ticker_config, &Value::Str("cost".to_string())),
2609 Value::Float(0.1),
2610 "numeric endpoint costs must be normalized to a config object"
2611 );
2612 let depth_config = &exchange.internals.implicit_api["public_get_depth"].3;
2613 assert_eq!(depth_config, &Value::Map(by_limit), "object endpoint config must be retained");
2614 }
2615
2616 #[tokio::test]
2618 async fn spaces_requests_by_rate_limit() {
2619 let mut ex = Exchange::new(None);
2620 ex.enableRateLimit = Value::Bool(true);
2621 ex.rateLimit = Value::Int(15); let start = std::time::Instant::now();
2623 for _ in 0..5 { ex.throttle(&[]).await; }
2624 let elapsed = start.elapsed().as_millis();
2625 assert!(elapsed >= 45, "throttle did not space requests: {elapsed}ms");
2627 }
2628
2629 #[tokio::test]
2631 async fn disabled_is_noop() {
2632 let mut ex = Exchange::new(None);
2633 ex.enableRateLimit = Value::Bool(false);
2634 ex.rateLimit = Value::Int(1000);
2635 let start = std::time::Instant::now();
2636 for _ in 0..5 { ex.throttle(&[]).await; }
2637 assert!(start.elapsed().as_millis() < 50, "disabled throttle slept");
2638 }
2639}
2640
2641#[cfg(all(test, feature = "transpiled-base"))]
2642mod rate_limit_config_tests {
2643 use crate::exchange::ExchangeRuntime;
2644 use crate::exchange_generated::ExchangeBase;
2645 use crate::Value;
2646
2647 #[test]
2651 fn binance_init_applies_describe_rate_limit() {
2652 let b = crate::exchanges::binance::BinanceCore::new(None);
2653 assert_eq!(
2654 b.exchange.rateLimit,
2655 Value::Int(50),
2656 "init() dropped describe().rateLimit; got {:?}",
2657 b.exchange.rateLimit
2658 );
2659 }
2660
2661 #[test]
2663 fn config_rate_limit_overrides_describe() {
2664 let mut cfg = crate::value::HashMap::new();
2665 cfg.insert("rateLimit".to_string(), Value::Int(123));
2666 let b = crate::exchanges::binance::BinanceCore::new(Some(Value::Map(cfg)));
2667 assert_eq!(b.exchange.rateLimit, Value::Int(123), "config rateLimit was clobbered by describe()");
2668 }
2669
2670 #[tokio::test]
2671 async fn implicit_api_preserves_and_calculates_endpoint_cost() {
2672 let mut binance = crate::exchanges::binance::BinanceCore::new(None);
2673 binance.build_implicit_api();
2674 let config = binance
2675 .exchange
2676 .internals
2677 .implicit_api
2678 .get("fapi_public_get_depth")
2679 .expect("Binance futures depth endpoint must be registered")
2680 .3
2681 .clone();
2682 assert_eq!(
2683 crate::get_value(&config, &Value::Str("cost".to_string())),
2684 Value::Int(2),
2685 "the implicit API table dropped the endpoint's base cost"
2686 );
2687 let params = Value::Map({
2688 let mut map = crate::value::HashMap::new();
2689 map.insert("limit".to_string(), Value::Int(100));
2690 map
2691 });
2692 let cost = binance
2693 .implicit_api_rate_limit_cost("fapi_public_get_depth", params)
2694 .await
2695 .expect("registered endpoint must have a calculable cost");
2696 assert_eq!(cost, Value::Int(5), "Binance byLimit cost was not applied");
2697 }
2698}
2699
2700#[cfg(all(test, feature = "transpiled-base"))]
2701mod sandbox_mode_tests {
2702 use crate::Value;
2703
2704 #[test]
2709 fn binance_sandbox_swaps_api_url() {
2710 let mut b = crate::exchanges::binance::BinanceCore::new(None);
2711 let test_url = crate::get_value(&b.exchange.urls, &Value::Str("test".to_string()));
2712 assert!(!matches!(test_url, Value::Null), "binance describe() has no test url");
2713 b.set_sandbox_mode(Value::Bool(true));
2714 assert_eq!(b.exchange.isSandboxModeEnabled, Value::Bool(true));
2715 let api_url = crate::get_value(&b.exchange.urls, &Value::Str("api".to_string()));
2716 assert_eq!(api_url, test_url, "sandbox mode did not switch urls['api'] to urls['test']");
2717 }
2718}
2719
2720#[cfg(all(test, feature = "transpiled-base"))]
2721mod dynamic_dispatch_tests {
2722 use crate::exchange::CallDynamicChecked;
2723 use crate::exchange_generated::ExchangeBase;
2724 use crate::Value;
2725
2726 #[tokio::test]
2739 async fn unified_method_reaches_a_dispatch_arm_not_the_null_fallthrough() {
2740 let mut b = crate::exchanges::binance::BinanceCore::new(None);
2741 let snake = crate::exchange::method_name_to_snake_case(
2742 &Value::Str("fetchOHLCV".to_string()));
2743 assert_eq!(snake, "fetch_ohlcv");
2744 b.exchange.internals.dynamic_dispatch_miss = None;
2745 let _ = futures::FutureExt::catch_unwind(
2746 std::panic::AssertUnwindSafe(b.call_dynamic(&snake, vec![])),
2747 ).await;
2748 assert_eq!(
2749 b.exchange.internals.dynamic_dispatch_miss, None,
2750 "`{snake}` fell through to the `_ => Null` arm — a paginated \
2751 re-entry would have silently returned an empty page",
2752 );
2753 let _ = b.call_dynamic("fetch_definitely_not_an_arm", vec![]).await;
2755 assert_eq!(
2756 b.exchange.internals.dynamic_dispatch_miss.as_deref(),
2757 Some("fetch_definitely_not_an_arm"),
2758 "the miss probe is inert — the assertion above proves nothing",
2759 );
2760 }
2761
2762 #[tokio::test]
2766 async fn implicit_endpoint_is_still_reachable_and_is_not_a_miss() {
2767 let mut b = crate::exchanges::binance::BinanceCore::new(None);
2768 b.exchange.build_implicit_api();
2769 let snake = crate::exchange::method_name_to_snake_case(
2770 &Value::Str("publicGetTicker24hr".to_string()));
2771 assert!(
2772 b.exchange.internals.implicit_api.contains_key(&snake),
2773 "implicit api has no `{snake}` entry — the `_` arm would treat a real \
2774 endpoint as an unknown name",
2775 );
2776 }
2777
2778 #[tokio::test]
2783 #[should_panic(expected = "NotSupported")]
2784 async fn unknown_dynamic_name_is_loud_not_null() {
2785 let mut b = crate::exchanges::binance::BinanceCore::new(None);
2786 let _ = b.call_dynamic_checked(
2787 Value::Str("fetchNoSuchThingAtAll".to_string()),
2788 vec![],
2789 ).await;
2790 }
2791
2792 #[tokio::test]
2795 async fn bare_call_dynamic_still_returns_null_for_optional_probes() {
2796 let mut b = crate::exchanges::binance::BinanceCore::new(None);
2797 let out = b.call_dynamic("fetch_no_such_thing_at_all", vec![]).await;
2798 assert_eq!(out, Value::Null);
2799 assert_eq!(
2800 b.exchange.internals.dynamic_dispatch_miss.as_deref(),
2801 Some("fetch_no_such_thing_at_all"),
2802 "the `_` arm did not record the miss, so call_dynamic_checked \
2803 could never raise on it",
2804 );
2805 }
2806}
2807
2808#[cfg(all(test, feature = "transpiled-base"))]
2809mod cow_alias_tests {
2810 use super::Exchange;
2811 use crate::Value;
2812 use crate::runtime::get_array_length;
2813
2814 #[test]
2818 fn convert_ohlcv_to_trading_view_preserves_pushes() {
2819 use crate::exchange_generated::ExchangeBase;
2820 let ex = super::BaseCore::new(Exchange::new(None));
2821 let row = Value::List(vec![
2822 Value::Int(1_700_000_000_000), Value::Int(1), Value::Int(2),
2823 Value::Int(0), Value::Int(1), Value::Int(10),
2824 ]);
2825 let ohlcvs = Value::List(vec![row.clone(), row]);
2826 let r = ex.convert_ohlcv_to_trading_view(ohlcvs, &[]);
2827 for key in ["t", "o", "h", "l", "c", "v"] {
2828 let col = crate::get_value(&r, &Value::Str(key.to_string()));
2829 assert_eq!(get_array_length(&col), Value::Int(2),
2830 "result['{key}'] lost its pushes — COW write-back failed");
2831 }
2832 }
2833}