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 market(&self, _symbol: Value) -> Value { Value::Null }
143 fn parse_prediction_trade(&self, _trade: Value, _market: Value) -> Value { Value::Null }
145 fn parse_prediction_order(&self, _order: Value, _market: Value) -> Value { Value::Null }
146 fn parse_prediction_position(&self, _position: Value, _market: Value) -> Value { Value::Null }
147 fn nonce(&self) -> Value { Value::Null }
156 fn sign(&self, _path: Value, _api: Value, _method: Value, _params: Value, _headers: Value, _body: Value) -> Value { Value::Null }
157 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 }
158}
159
160impl Clone for Internals {
170 fn clone(&self) -> Self { Internals::default() }
171}
172
173impl Default for Internals {
174 fn default() -> Self {
175 Self {
176 http_client: None,
177 describe_cb: None,
178 last_rest_ts: 0,
179 headers: HashMap::new(),
180 throttle: std::sync::Arc::new(tokio::sync::Mutex::new((0.0, 0))),
181 implicit_api: HashMap::new(),
182 dispatch_stack: Vec::new(),
183 dynamic_dispatch_miss: None,
184 }
185 }
186}
187
188#[derive(Clone)]
194pub struct Exchange {
195 pub id: Value,
197 pub name: Value,
198 pub countries: Value,
199 pub version: Value,
200 pub alias: Value,
201 pub certified: Value,
202 pub pro: Value,
203 pub hostname: Value,
204
205 pub apiKey: Value,
207 pub secret: Value,
208 pub password: Value,
209 pub uid: Value,
210 pub walletAddress: Value,
211 pub privateKey: Value,
212 pub twofa: Value,
213 pub token: Value,
214 pub login: Value,
215 pub accountId: Value,
216 pub requiredCredentials: Value,
217
218 pub timeout: Value,
220 pub rateLimit: Value,
221 pub enableRateLimit: Value,
222 pub rateLimiterAlgorithm: Value,
223 pub rollingWindowSize: Value,
224 pub tokenBucket: Value,
225 pub userConfig: Value,
230 pub verbose: Value,
231 pub isSandboxModeEnabled: Value,
232
233 pub proxy: Value,
235 pub proxyUrl: Value,
236 pub proxy_url: Value,
237 pub proxyUrlCallback: Value,
238 pub proxy_url_callback: Value,
239 pub httpProxy: Value,
240 pub http_proxy: Value,
241 pub httpProxyCallback: Value,
242 pub http_proxy_callback: Value,
243 pub httpsProxy: Value,
244 pub https_proxy: Value,
245 pub httpsProxyCallback: Value,
246 pub https_proxy_callback: Value,
247 pub socksProxy: Value,
248 pub socks_proxy: Value,
249 pub socksProxyCallback: Value,
250 pub socks_proxy_callback: Value,
251 pub wsProxy: Value,
252 pub ws_proxy: Value,
253 pub wssProxy: Value,
254 pub wss_proxy: Value,
255 pub wsSocksProxy: Value,
256 pub ws_socks_proxy: Value,
257
258 pub markets: Value,
260 pub markets_by_id: Value,
261 pub currencies: Value,
262 pub currencies_by_id: Value,
263 pub commonCurrencies: Value,
264 pub baseCurrencies: Value,
265 pub quoteCurrencies: Value,
266 pub symbols: Value,
267 pub ids: Value,
268 pub codes: Value,
269 pub timeframes: Value,
270 pub precision: Value,
271 pub limits: Value,
272 pub fees: Value,
273 pub features: Value,
274 pub has: Value,
275 pub exceptions: Value,
276 pub urls: Value,
277 pub api: Value,
278 pub options: Value,
279 pub headers: Value,
280 pub accounts: Value,
281 pub accountsById: Value,
282
283 pub orderbooks: Value,
285 pub orders: Value,
286 pub trades: Value,
287 pub myTrades: Value,
288 pub positions: Value,
289 pub newUpdates: Value,
294 pub tickers: Value,
295 pub bidsasks: Value,
296 pub ohlcvs: Value,
297 pub clients: Value,
298 pub balance: Value,
299 pub liquidations: Value,
300 pub myLiquidations: Value,
301 pub fundingRates: Value,
302 pub triggerOrders: Value,
303 pub transactions: Value,
304 pub reloadingMarkets: Value,
305 pub marketsLoading: Value,
306
307 pub last_request_url: Value,
309 pub last_request_headers: Value,
310 pub last_request_body: Value,
311 pub last_http_response: Value,
312 pub last_response_headers: Value,
313 pub mock_response: Value,
319 pub mock_response_by_url: Value,
323 pub last_json_response: Value,
324 pub lastRestRequestTimestamp: Value,
325 pub fetchHistoryCache: Value,
329 pub fetchHistoryCacheSize: Value,
330
331 pub paddingMode: Value,
333 pub precisionMode: Value,
334 pub substituteCommonCurrencyCodes: Value,
335 pub reduceFees: Value,
336 pub minFundingAddressLength: Value,
337 pub networkAliases: Value,
338 pub MAX_VALUE: Value,
339 pub returnResponseHeaders: Value,
340 pub httpExceptions: Value,
341 pub status: Value,
342
343 pub userAgent: Value,
345 pub user_agent: Value,
346 pub userAgents: Value,
347
348 pub describe_data: Value,
350 pub derived_describe: Option<DescribeCallback>,
351
352 pub internals: Internals,
354}
355
356impl Default for Exchange {
357 fn default() -> Self { Self::new(None) }
358}
359
360fn vmap(pairs: &[(&str, Value)]) -> Value {
366 let mut m = HashMap::new();
367 for (k, v) in pairs { m.insert((*k).to_string(), v.clone()); }
368 Value::Map(m)
369}
370
371fn min_max() -> Value { vmap(&[("min", Value::Null), ("max", Value::Null)]) }
372
373fn base_limits() -> Value {
374 vmap(&[
375 ("leverage", min_max()),
376 ("amount", min_max()),
377 ("price", min_max()),
378 ("cost", min_max()),
379 ])
380}
381
382fn base_fees() -> Value {
383 vmap(&[
384 ("trading", vmap(&[
385 ("tierBased", Value::Null),
386 ("percentage", Value::Null),
387 ("taker", Value::Null),
388 ("maker", Value::Null),
389 ])),
390 ("funding", vmap(&[
391 ("tierBased", Value::Null),
392 ("percentage", Value::Null),
393 ("withdraw", Value::Map(HashMap::new())),
394 ("deposit", Value::Map(HashMap::new())),
395 ])),
396 ])
397}
398
399fn base_urls() -> Value {
400 vmap(&[
401 ("logo", Value::Null), ("api", Value::Null), ("test", Value::Null),
402 ("www", Value::Null), ("doc", Value::Null), ("api_management", Value::Null),
403 ("fees", Value::Null), ("referral", Value::Null),
404 ])
405}
406
407fn base_status() -> Value {
408 vmap(&[
409 ("status", Value::Str("ok".into())),
410 ("updated", Value::Null),
411 ("eta", Value::Null),
412 ("url", Value::Null),
413 ("info", Value::Null),
414 ])
415}
416
417fn deep_merge(a: &Value, b: &Value) -> Value {
420 match (a, b) {
421 (Value::Dict(am), Value::Dict(bm)) => {
422 let mut out = (**am).clone();
423 for (k, bv) in bm.iter() {
424 let merged = match out.get(k) {
425 Some(av) => deep_merge(av, bv),
426 None => bv.clone(),
427 };
428 out.insert(k.clone(), merged);
429 }
430 Value::Map(out)
431 }
432 _ => b.clone(),
433 }
434}
435
436fn base_http_exceptions() -> Value {
437 let mut m = HashMap::new();
438 for (code, class) in [
439 ("422", "ExchangeError"), ("418", "DDoSProtection"),
440 ("429", "RateLimitExceeded"), ("404", "ExchangeNotAvailable"),
441 ("409", "ExchangeNotAvailable"), ("410", "ExchangeNotAvailable"),
442 ("451", "ExchangeNotAvailable"), ("500", "ExchangeNotAvailable"),
443 ("501", "ExchangeNotAvailable"), ("502", "ExchangeNotAvailable"),
444 ("520", "ExchangeNotAvailable"), ("521", "ExchangeNotAvailable"),
445 ("522", "ExchangeNotAvailable"), ("525", "ExchangeNotAvailable"),
446 ("526", "ExchangeNotAvailable"), ("400", "ExchangeNotAvailable"),
447 ("403", "ExchangeNotAvailable"), ("405", "ExchangeNotAvailable"),
448 ("503", "ExchangeNotAvailable"), ("530", "ExchangeNotAvailable"),
449 ("408", "RequestTimeout"), ("504", "RequestTimeout"),
450 ("401", "AuthenticationError"), ("407", "AuthenticationError"),
451 ("511", "AuthenticationError"),
452 ] {
453 m.insert(code.to_string(), Value::Str(class.to_string().into()));
454 }
455 Value::Map(m)
456}
457
458impl Exchange {
459 pub fn new(config: Option<Value>) -> Self {
460 let mut ex = Exchange {
461 id: Value::Str("Exchange".into()),
464 name: Value::Null,
465 countries: Value::Null,
466 version: Value::Null,
467 alias: Value::Bool(false),
468 certified: Value::Bool(false),
469 pro: Value::Bool(false),
470 hostname: Value::Null,
471
472 apiKey: Value::Null,
473 secret: Value::Null,
474 password: Value::Null,
475 uid: Value::Null,
476 walletAddress: Value::Null,
477 privateKey: Value::Null,
478 twofa: Value::Null,
479 token: Value::Null,
480 login: Value::Null,
481 accountId: Value::Null,
482 requiredCredentials: {
486 let mut m = HashMap::new();
487 m.insert("apiKey".to_string(), Value::Bool(true));
488 m.insert("secret".to_string(), Value::Bool(true));
489 m.insert("uid".to_string(), Value::Bool(false));
490 m.insert("accountId".to_string(), Value::Bool(false));
491 m.insert("login".to_string(), Value::Bool(false));
492 m.insert("password".to_string(), Value::Bool(false));
493 m.insert("twofa".to_string(), Value::Bool(false));
494 m.insert("privateKey".to_string(), Value::Bool(false));
495 m.insert("walletAddress".to_string(), Value::Bool(false));
496 m.insert("token".to_string(), Value::Bool(false));
497 Value::Map(m)
498 },
499
500 timeout: Value::Int(10_000),
501 rateLimit: Value::Int(2_000),
502 enableRateLimit: Value::Bool(true),
503 rateLimiterAlgorithm: Value::Str("leakyBucket".into()),
504 rollingWindowSize: Value::Int(60_000),
505 tokenBucket: Value::Map(HashMap::new()),
506 userConfig: Value::Null,
507 verbose: Value::Bool(false),
508 isSandboxModeEnabled: Value::Bool(false),
509
510 proxy: Value::Null,
511 proxyUrl: Value::Null,
512 proxy_url: Value::Null,
513 proxyUrlCallback: Value::Null,
514 proxy_url_callback: Value::Null,
515 httpProxy: Value::Null,
516 http_proxy: Value::Null,
517 httpProxyCallback: Value::Null,
518 http_proxy_callback: Value::Null,
519 httpsProxy: Value::Null,
520 https_proxy: Value::Null,
521 httpsProxyCallback: Value::Null,
522 https_proxy_callback: Value::Null,
523 socksProxy: Value::Null,
524 socks_proxy: Value::Null,
525 socksProxyCallback: Value::Null,
526 socks_proxy_callback: Value::Null,
527 wsProxy: Value::Null,
528 ws_proxy: Value::Null,
529 wssProxy: Value::Null,
530 wss_proxy: Value::Null,
531 wsSocksProxy: Value::Null,
532 ws_socks_proxy: Value::Null,
533
534 markets: Value::Null,
535 markets_by_id: Value::Null,
536 currencies: Value::Map(HashMap::new()),
537 currencies_by_id: Value::Null,
538 commonCurrencies: {
539 let mut m = HashMap::new();
540 m.insert("XBT".to_string(), Value::Str("BTC".into()));
541 m.insert("BCHSV".to_string(), Value::Str("BSV".into()));
542 Value::Map(m)
543 },
544 baseCurrencies: Value::Null,
545 quoteCurrencies: Value::Null,
546 symbols: Value::Null,
547 ids: Value::Null,
548 codes: Value::Null,
549 timeframes: Value::Null,
550 precision: Value::Null,
551 limits: base_limits(),
552 fees: base_fees(),
553 features: Value::Null,
554 has: Value::Map(HashMap::new()),
555 exceptions: Value::Null,
556 urls: base_urls(),
557 api: Value::Null,
558 options: {
562 let mk = |p: &str, s: &str, d: &str| {
563 let mut e = HashMap::new();
564 e.insert("primary".to_string(), Value::Str(p.to_string().into()));
565 e.insert("secondary".to_string(), Value::Str(s.to_string().into()));
566 e.insert("default".to_string(), Value::Str(d.to_string().into()));
567 Value::Map(e)
568 };
569 let mut repl = HashMap::new();
570 repl.insert("ETH".to_string(), mk("ETH", "ERC20", "secondary"));
571 repl.insert("CRO".to_string(), mk("CRONOS", "CRC20", "secondary"));
572 repl.insert("TRX".to_string(), mk("TRX", "TRC20", "secondary"));
573 repl.insert("BTC".to_string(), mk("BTC", "BRC20", "primary"));
574 let mut o = HashMap::new();
575 o.insert("defaultNetworkCodeReplacements".to_string(), Value::Map(repl));
576 Value::Map(o)
577 },
578 headers: Value::Map(HashMap::new()),
579 accounts: Value::Null,
580 accountsById: Value::Null,
581
582 orderbooks: Value::Map(HashMap::new()),
583 orders: Value::Null,
584 trades: Value::Map(HashMap::new()),
585 myTrades: Value::Null,
586 positions: Value::Null,
587 newUpdates: Value::Bool(true),
588 tickers: Value::Map(HashMap::new()),
589 bidsasks: Value::Map(HashMap::new()),
590 ohlcvs: Value::Map(HashMap::new()),
591 clients: Value::Map(HashMap::new()),
592 balance: Value::Map(HashMap::new()),
593 liquidations: Value::Null,
594 myLiquidations: Value::Null,
595 fundingRates: Value::Null,
596 triggerOrders: Value::Null,
597 transactions: Value::Map(HashMap::new()),
598 reloadingMarkets: Value::Null,
599 marketsLoading: Value::Null,
600
601 last_request_url: Value::Null,
602 last_request_headers: Value::Null,
603 last_request_body: Value::Null,
604 last_http_response: Value::Null,
605 last_response_headers: Value::Null,
606 mock_response: Value::Null,
607 mock_response_by_url: Value::Null,
608 last_json_response: Value::Null,
609 lastRestRequestTimestamp: Value::Int(0),
610 fetchHistoryCache: Value::List(vec![]),
611 fetchHistoryCacheSize: Value::Int(0),
612
613 paddingMode: Value::Null,
614 precisionMode: Value::Null,
615 substituteCommonCurrencyCodes: Value::Bool(true),
616 reduceFees: Value::Bool(true),
617 minFundingAddressLength: Value::Int(1),
618 networkAliases: Value::Dict(std::sync::Arc::new([("ETH".to_string(), Value::Str("ERC20".into())), ("TRX".to_string(), Value::Str("TRC20".into())), ("BSC".to_string(), Value::Str("BEP20".into())), ("BSC20".to_string(), Value::Str("BEP20".into())), ("CRONOS".to_string(), Value::Str("CRC20".into())), ("ARB".to_string(), Value::Str("ARBITRUM".into())), ("ARBONE".to_string(), Value::Str("ARBITRUM".into())), ("ARBNOVA".to_string(), Value::Str("ARBITRUM_NOVA".into()))].into_iter().collect())),
619 MAX_VALUE: Value::Float(f64::MAX),
620 returnResponseHeaders: Value::Bool(false),
621 httpExceptions: base_http_exceptions(),
622 status: base_status(),
623
624 userAgent: Value::Null,
625 user_agent: Value::Null,
626 userAgents: {
627 let mut m = HashMap::new();
628 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()));
629 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()));
630 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()));
631 Value::Map(m)
632 },
633
634 describe_data: Value::Null,
635 derived_describe: None,
636
637 internals: Internals::default(),
638 };
639 if let Some(cfg) = config {
640 ex.userConfig = cfg.clone();
641 ex.apply_config(&cfg);
642 }
643 ex
653 }
654
655 pub fn initialize_properties(&mut self, described: Value) {
671 let props = if matches!(self.userConfig, Value::Null) {
672 described
673 } else {
674 crate::runtime::deep_merge_dict(&described, &self.userConfig.clone())
675 };
676 let get = |k: &str| crate::get_value(&props, &Value::Str(k.to_string().into()));
677 let assign = |field: &mut Value, v: Value| {
678 if !matches!(v, Value::Null) {
679 *field = v;
680 }
681 };
682 assign(&mut self.api, get("api"));
683 assign(&mut self.urls, get("urls"));
684 assign(&mut self.has, get("has"));
685 assign(&mut self.hostname, get("hostname"));
686 assign(&mut self.version, get("version"));
687 assign(&mut self.id, get("id"));
688 assign(&mut self.name, get("name"));
689 assign(&mut self.exceptions, get("exceptions"));
690 assign(&mut self.requiredCredentials, get("requiredCredentials"));
691 assign(&mut self.precisionMode, get("precisionMode"));
692 assign(&mut self.timeframes, get("timeframes"));
693 assign(&mut self.fees, get("fees"));
694 assign(&mut self.features, get("features"));
695 let rate_limit = get("rateLimit");
696 if matches!(rate_limit, Value::Int(_) | Value::Float(_)) {
697 self.rateLimit = rate_limit;
698 }
699 if let Value::Dict(extra) = get("options") {
703 let mut merged = match &self.options {
704 Value::Dict(m) => (**m).clone(),
705 _ => HashMap::new(),
706 };
707 let extra = Arc::try_unwrap(extra).unwrap_or_else(|a| (*a).clone());
708 for (k, v) in extra { merged.insert(k, v); }
709 self.options = Value::Map(merged);
710 }
711 if let Value::Dict(extra) = get("commonCurrencies") {
712 let mut merged = match &self.commonCurrencies {
713 Value::Dict(m) => (**m).clone(),
714 _ => HashMap::new(),
715 };
716 let extra = Arc::try_unwrap(extra).unwrap_or_else(|a| (*a).clone());
717 for (k, v) in extra { merged.insert(k, v); }
718 self.commonCurrencies = Value::Map(merged);
719 }
720 let described_markets = get("markets");
724 if matches!(&described_markets, Value::Dict(m) if !m.is_empty())
725 && matches!(self.markets, Value::Null)
726 {
727 self.set_markets_inline(described_markets);
728 }
729 self.build_implicit_api();
730 }
731
732 fn apply_config(&mut self, cfg: &Value) {
733 use crate::value::safe_string;
734 if let Some(v) = safe_string(cfg, "id", None) { self.id = Value::Str(v.into()); }
735 if let Some(v) = safe_string(cfg, "name", None) { self.name = Value::Str(v.into()); }
736 if let Some(v) = safe_string(cfg, "hostname", None) { self.hostname = Value::Str(v.into()); }
737 let rate_limit = crate::get_value(cfg, &Value::Str("rateLimit".into()));
738 if matches!(rate_limit, Value::Int(_) | Value::Float(_)) { self.rateLimit = rate_limit; }
739 let timeout = crate::get_value(cfg, &Value::Str("timeout".into()));
740 if matches!(timeout, Value::Int(_) | Value::Float(_)) { self.timeout = timeout; }
741 let fetch_history_cache_size = crate::get_value(cfg, &Value::Str("fetchHistoryCacheSize".into()));
742 if matches!(fetch_history_cache_size, Value::Int(_) | Value::Float(_)) { self.fetchHistoryCacheSize = fetch_history_cache_size; }
743 let urls = crate::get_value(cfg, &Value::Str("urls".into()));
744 if let Value::Dict(_) = urls { self.urls = deep_merge(&self.urls, &urls); }
745 if let Some(v) = safe_string(cfg, "apiKey", None) { self.apiKey = Value::Str(v.into()); }
746 if let Some(v) = safe_string(cfg, "secret", None) { self.secret = Value::Str(v.into()); }
747 if let Some(v) = safe_string(cfg, "password", None) { self.password = Value::Str(v.into()); }
748 if let Some(v) = safe_string(cfg, "uid", None) { self.uid = Value::Str(v.into()); }
749 if let Some(v) = safe_string(cfg, "walletAddress", None) { self.walletAddress = Value::Str(v.into()); }
750 if let Some(v) = safe_string(cfg, "privateKey", None) { self.privateKey = Value::Str(v.into()); }
751 if let Some(v) = safe_string(cfg, "token", None) { self.token = Value::Str(v.into()); }
752 if let Some(v) = safe_string(cfg, "login", None) { self.login = Value::Str(v.into()); }
753 if let Some(v) = safe_string(cfg, "accountId", None) { self.accountId = Value::Str(v.into()); }
754 if let Some(v) = safe_string(cfg, "httpProxy", None) { self.httpProxy = Value::Str(v.into()); }
755 if let Some(v) = safe_string(cfg, "httpsProxy", None) { self.httpsProxy = Value::Str(v.into()); }
756 if let Some(v) = safe_string(cfg, "socksProxy", None) { self.socksProxy = Value::Str(v.into()); }
757 if let Some(v) = safe_string(cfg, "wsProxy", None) { self.wsProxy = Value::Str(v.into()); }
761 if let Some(v) = safe_string(cfg, "wssProxy", None) { self.wssProxy = Value::Str(v.into()); }
762 if let Some(b) = crate::value::safe_bool(cfg, "verbose", None) { self.verbose = Value::Bool(b); }
763 if let Some(b) = crate::value::safe_bool(cfg, "enableRateLimit", None) { self.enableRateLimit = Value::Bool(b); }
764 let markets = crate::get_value(cfg, &Value::Str("markets".into()));
769 let currencies = crate::get_value(cfg, &Value::Str("currencies".into()));
770 if !matches!(markets, Value::Null) { self.set_markets_inline(markets); }
771 if !matches!(currencies, Value::Null) { self.currencies = currencies; }
772 let opts = crate::get_value(cfg, &Value::Str("options".into()));
773 if let Value::Dict(extra) = opts {
774 let mut merged = match &self.options {
775 Value::Dict(m) => (**m).clone(),
776 _ => HashMap::new(),
777 };
778 let extra = Arc::try_unwrap(extra).unwrap_or_else(|a| (*a).clone());
779 for (k, v) in extra { merged.insert(k, v); }
780 self.options = Value::Map(merged);
781 }
782 let accounts = crate::get_value(cfg, &Value::Str("accounts".into()));
783 if !matches!(accounts, Value::Null) { self.accounts = accounts; }
784 }
785
786 fn set_markets_inline(&mut self, markets: Value) {
789 let arr: Vec<Value> = match &markets {
790 Value::Dict(m) => m.values().cloned().collect(),
791 Value::Arr(a) => (**a).clone(),
792 _ => return,
793 };
794 let mut by_symbol = HashMap::new();
795 let mut by_id: HashMap<String, Vec<Value>> = HashMap::new();
799 let mut symbols = Vec::new();
800 for m in &arr {
801 if let Some(s) = crate::value::safe_string(m, "symbol", None) {
802 by_symbol.insert(s.clone(), m.clone());
803 symbols.push(Value::Str(s.into()));
804 }
805 if let Some(i) = crate::value::safe_string(m, "id", None) {
806 by_id.entry(i).or_default().push(m.clone());
807 }
808 }
809 self.markets = if by_symbol.is_empty() { markets } else { Value::Map(by_symbol) };
810 self.markets_by_id = Value::Map(
811 by_id.into_iter().map(|(k, v)| (k, Value::Array(v))).collect()
812 );
813 self.symbols = Value::Array(symbols);
814 }
815
816 fn http_client(&mut self) -> &reqwest::Client {
819 if self.internals.http_client.is_none() {
820 let mut b = reqwest::Client::builder()
821 .timeout(std::time::Duration::from_millis(self.timeout_ms()))
822 .gzip(true);
827 if let Some(ua) = self.user_agent_str() { b = b.user_agent(ua); }
828 let mut proxies: Vec<reqwest::Proxy> = Vec::new();
837 for field in [&self.socksProxy, &self.socks_proxy] {
838 if let Value::Str(s) = field {
839 if !s.is_empty() {
840 if let Ok(p) = reqwest::Proxy::all(s.as_ref()) { proxies.push(p); }
841 }
842 }
843 }
844 for field in [&self.httpsProxy, &self.https_proxy] {
845 if let Value::Str(s) = field {
846 if !s.is_empty() {
847 if let Ok(p) = reqwest::Proxy::https(s.as_ref()) { proxies.push(p); }
848 }
849 }
850 }
851 for field in [&self.httpProxy, &self.http_proxy] {
852 if let Value::Str(s) = field {
853 if !s.is_empty() {
854 if let Ok(p) = reqwest::Proxy::http(s.as_ref()) { proxies.push(p); }
855 }
856 }
857 }
858 if proxies.is_empty() {
861 if let Value::Str(s) = &self.proxy {
862 if !s.is_empty() {
863 if let Ok(p) = reqwest::Proxy::all(s.as_ref()) { proxies.push(p); }
864 }
865 }
866 }
867 for p in proxies { b = b.proxy(p); }
868 self.internals.http_client = Some(b.build().expect("reqwest client"));
869 }
870 self.internals.http_client.as_ref().unwrap()
871 }
872
873 fn timeout_ms(&self) -> u64 {
874 match &self.timeout {
875 Value::Int(n) => *n as u64,
876 Value::Float(f) => *f as u64,
877 _ => 10_000,
878 }
879 }
880
881 fn user_agent_str(&self) -> Option<&str> {
882 match &self.userAgent { Value::Str(s) => Some(s.as_ref()), _ => match &self.user_agent {
883 Value::Str(s) => Some(s.as_ref()), _ => None
884 }}
885 }
886
887
888 fn is_verbose(&self) -> bool {
889 matches!(self.verbose, Value::Bool(true))
890 }
891
892
893 pub fn urlencode_kv(&self, params: &Value) -> String {
896 let m = match params { Value::Dict(m) => m, _ => return String::new() };
897 m.iter().map(|(k, v)| format!(
898 "{}={}",
899 url_pct(k),
900 url_pct(&crate::runtime::stringify_param(v)),
901 )).collect::<Vec<_>>().join("&")
902 }
903
904 pub fn implode_params(&self, path: Value, params: Value) -> Value {
905 let path_str = match &path { Value::Str(s) => s.clone(), _ => return path };
906 let m = match ¶ms { Value::Dict(m) => m, _ => return Value::Str(path_str) };
907 let mut out = path_str;
908 for (k, v) in m.iter() {
909 let needle = format!("{{{k}}}");
910 if out.contains(&needle) {
911 out = out.replace(&needle, &crate::runtime::stringify_param(v)).into();
912 }
913 }
914 Value::Str(out)
915 }
916
917 pub fn json_str(&self, v: &Value) -> String {
918 serde_json::to_string(&v.to_json()).unwrap_or_default()
919 }
920
921 pub fn hmac(&self, data: Value, secret: Value, hash: Value, optional_args: &[Value]) -> Value {
924 let dbytes = value_to_bytes(&data);
927 let sbytes = value_to_bytes(&secret);
928 let h = match &hash { Value::Str(s) => s.clone(), _ => "sha256".to_string().into() };
929 let digest = match optional_args.get(0) {
930 Some(Value::Str(d)) => d.clone(),
931 _ => "hex".to_string().into(),
932 };
933 match self.hmac_typed(&dbytes, &sbytes, &h, &digest) {
934 Ok(v) => Value::Str(v.into()),
935 Err(_) => Value::Null,
936 }
937 }
938
939 pub fn hmac_typed(&self, data: &[u8], secret: &[u8], hash: &str, digest: &str) -> Result<String> {
940 let dbytes = data;
941 let sbytes = secret;
942 let raw: Vec<u8> = match hash.to_ascii_lowercase().as_str() {
943 "sha256" => { let mut m = HmacSha256::new_from_slice(sbytes).unwrap(); m.update(dbytes); m.finalize().into_bytes().to_vec() }
944 "sha512" => { let mut m = HmacSha512::new_from_slice(sbytes).unwrap(); m.update(dbytes); m.finalize().into_bytes().to_vec() }
945 "sha1" => { let mut m = HmacSha1::new_from_slice(sbytes).unwrap(); m.update(dbytes); m.finalize().into_bytes().to_vec() }
946 "md5" => { let mut m = HmacMd5::new_from_slice(sbytes).unwrap(); m.update(dbytes); m.finalize().into_bytes().to_vec() }
947 other => return Err(ExchangeError::new("BadRequest", format!("unknown hmac: {other}"))),
948 };
949 Ok(match digest {
950 "base64" => B64.encode(&raw),
951 _ => hex::encode(&raw),
952 })
953 }
954
955 pub fn hash(&self, data: Value, algo: Value, optional_args: &[Value]) -> Value {
956 let dbytes = value_to_bytes(&data);
958 let a = match &algo { Value::Str(s) => s.clone(), _ => "sha256".to_string().into() };
959 let digest = match optional_args.get(0) {
960 Some(Value::Str(d)) => d.clone(),
961 _ => "hex".to_string().into(),
962 };
963 let raw = hash_raw(&dbytes, &a);
964 match digest.as_ref() {
965 "binary" => Value::Array(raw.iter().map(|b| Value::Int(*b as i64)).collect()),
967 "base64" => Value::Str(B64.encode(&raw).into()),
968 _ => Value::Str(hex::encode(&raw).into()),
969 }
970 }
971
972 pub fn hash_typed(&self, data: &[u8], algo: &str, digest: &str) -> String {
973 let raw = hash_raw(data, algo);
974 match digest {
975 "base64" => B64.encode(&raw),
976 _ => hex::encode(&raw),
977 }
978 }
979
980 pub fn binary_to_base64(&self, data: Value, _optional_args: &[Value]) -> Value {
981 let bytes = value_to_bytes(&data);
982 Value::Str(B64.encode(&bytes).into())
983 }
984 pub fn base64_to_binary(&self, s: Value, _optional_args: &[Value]) -> Value {
985 let str_val = match &s { Value::Str(s) => s.clone(), _ => return Value::Null };
986 match B64.decode(&*str_val) {
987 Ok(b) => Value::Array(b.into_iter().map(|n| Value::Int(n as i64)).collect()),
988 Err(_) => Value::Null,
989 }
990 }
991 pub fn binary_to_base16(&self, data: Value, _optional_args: &[Value]) -> Value {
992 let bytes = value_to_bytes(&data);
993 Value::Str(hex::encode(&bytes).into())
994 }
995 pub fn base16_to_binary(&self, s: Value, _optional_args: &[Value]) -> Value {
996 let str_val = match &s { Value::Str(s) => s.clone(), _ => return Value::Null };
997 match hex::decode(&*str_val) {
998 Ok(b) => Value::Array(b.into_iter().map(|n| Value::Int(n as i64)).collect()),
999 Err(_) => Value::Null,
1000 }
1001 }
1002
1003 pub fn milliseconds(&self) -> Value {
1006 let n = std::time::SystemTime::now()
1007 .duration_since(std::time::UNIX_EPOCH)
1008 .map(|d| d.as_millis() as i64).unwrap_or(0);
1009 Value::Int(n)
1010 }
1011 pub fn seconds(&self) -> Value {
1012 match self.milliseconds() { Value::Int(n) => Value::Int(n / 1000), v => v }
1013 }
1014 pub fn microseconds(&self) -> Value {
1015 match self.milliseconds() { Value::Int(n) => Value::Int(n * 1000), v => v }
1016 }
1017
1018 pub fn iso8601(&self, ts: Value) -> Value {
1019 let n = match ts {
1020 Value::Int(n) => n,
1021 Value::Float(f) => f as i64,
1022 Value::Str(ref s) => match s.parse::<i64>() { Ok(v) => v, Err(_) => return Value::Null },
1023 _ => return Value::Null,
1024 };
1025 if n < 0 {
1026 return Value::Null;
1027 }
1028 chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n)
1029 .map(|t| Value::Str(t.to_rfc3339_opts(chrono::SecondsFormat::Millis, true).into()))
1030 .unwrap_or(Value::Null)
1031 }
1032
1033 pub fn parse8601(&self, s: Value) -> Value {
1034 let str_val = match s { Value::Str(s) => s, _ => return Value::Null };
1035 if str_val.is_empty() {
1036 return Value::Null;
1037 }
1038 if let Ok(t) = chrono::DateTime::parse_from_rfc3339(&str_val) {
1040 return Value::Int(t.timestamp_millis());
1041 }
1042 for fmt in [
1046 "%Y-%m-%dT%H:%M:%S%.f%z", "%Y-%m-%dT%H:%M:%S%z",
1047 "%Y-%m-%d %H:%M:%S%.f%z", "%Y-%m-%d %H:%M:%S%z",
1048 ] {
1049 if let Ok(t) = chrono::DateTime::parse_from_str(&str_val, fmt) {
1050 return Value::Int(t.timestamp_millis());
1051 }
1052 }
1053 for fmt in [
1055 "%Y-%m-%d %H:%M:%S%.f", "%Y-%m-%d %H:%M:%S",
1056 "%Y-%m-%dT%H:%M:%S%.f", "%Y-%m-%dT%H:%M:%S",
1057 "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M",
1058 ] {
1059 if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(&str_val, fmt) {
1060 return Value::Int(ndt.and_utc().timestamp_millis());
1061 }
1062 }
1063 if let Ok(d) = chrono::NaiveDate::parse_from_str(&str_val, "%Y-%m-%d") {
1064 if let Some(ndt) = d.and_hms_opt(0, 0, 0) {
1065 return Value::Int(ndt.and_utc().timestamp_millis());
1066 }
1067 }
1068 Value::Null
1069 }
1070
1071 }
1078
1079impl Exchange {
1091 pub fn dispatch_guard_enter(&mut self, method: &str) -> bool {
1095 if self.internals.dispatch_stack.iter().any(|m| m == method) { return false; }
1096 self.internals.dispatch_stack.push(method.to_string());
1097 true
1098 }
1099
1100 pub fn dispatch_guard_exit(&mut self) {
1102 self.internals.dispatch_stack.pop();
1103 }
1104}
1105
1106fn ws_string_list(v: &Value) -> Vec<String> {
1118 match v {
1119 Value::Str(s) => vec![s.to_string()],
1120 Value::Arr(a) => a
1121 .iter()
1122 .filter_map(|x| match x {
1123 Value::Str(s) => Some(s.to_string()),
1124 _ => None,
1125 })
1126 .collect(),
1127 _ => Vec::new(),
1128 }
1129}
1130
1131pub trait ExchangeRuntime: crate::exchange_generated::ExchangeBase {
1132 fn fetch(&mut self, url: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1133 let url_str = match &url { Value::Str(s) => s.to_string(), _ => crate::runtime::stringify_param(&url).into() };
1134 let method = optional_args.get(0).cloned().unwrap_or(Value::Str("GET".into()));
1135 let headers = optional_args.get(1).cloned().unwrap_or(Value::Null);
1136 let body = optional_args.get(2).cloned().unwrap_or(Value::Null);
1137 let method_str = match &method { Value::Str(s) => s.to_string(), _ => "GET".to_string().into() };
1138 let body_str = match &body { Value::Str(s) => Some(s.to_string()), _ => None };
1139 let headers_map: HashMap<String, String> = match &headers {
1140 Value::Dict(m) => m.iter().filter_map(|(k, v)| match v {
1141 Value::Str(s) => Some((k.clone(), s.to_string())),
1142 _ => None,
1143 }).collect(),
1144 _ => HashMap::new(),
1145 };
1146 match self.fetch_typed(&url_str, &method_str, headers_map, body_str).await {
1147 Ok(v) => v,
1148 Err(e) => panic!("{}", e),
1151 }
1152 } }
1153
1154 fn ws_run(
1171 &mut self,
1172 url: String,
1173 hashes: Vec<String>,
1174 message: Value,
1175 subscribe_hashes: Vec<String>,
1176 subscription: Value,
1177 ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1178 let __ws_proxy = [&self.wsProxy, &self.ws_proxy, &self.wssProxy]
1179 .iter()
1180 .find_map(|v| match v { Value::Str(s) if !s.is_empty() => Some(s.to_string()), _ => None });
1181 let __decompress_binary = !matches!(crate::get_value(&self.options, &Value::Str("decompressBinary".into())), Value::Bool(false));
1183 let __ws_options = crate::get_value(&crate::get_value(&self.options, &Value::Str("ws".into())), &Value::Str("options".into()));
1185 let __ws_headers: Vec<(String, String)> = match crate::get_value(&__ws_options, &Value::Str("headers".into())) {
1186 Value::Dict(m) => m.iter().filter_map(|(k, v)| match v {
1187 Value::Str(s) => Some((k.clone(), s.to_string())),
1188 Value::Int(n) => Some((k.clone(), n.to_string())),
1189 _ => None,
1190 }).collect(),
1191 _ => Vec::new(),
1192 };
1193 let client = match crate::pro::ws_client::ensure_client_with_headers(&url, &__ws_headers, __ws_proxy, __decompress_binary).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.to_string(),
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().into()),
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).into(),
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_ref(), _ => "" }).into());
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".into()));
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".into()), 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.to_string(), v => crate::runtime::stringify_param(v) };
1384 let hash_s = match &message_hash { Value::Str(s) => s.to_string(), 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.to_string(), 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.to_string(), 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().into());
1415 self.last_request_headers = Value::Map(headers.iter()
1416 .map(|(k, v)| (k.clone(), Value::Str(v.clone().into())))
1417 .collect());
1418 self.last_request_body = match &body {
1419 Some(b) => Value::Str(b.clone().into()),
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_ref(), _ => "" }),
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 reason = resp.status().canonical_reason().unwrap_or("");
1470 let text = resp.text().await?;
1471 HTTP_NANOS.fetch_add(__http_t0.elapsed().as_nanos() as u64,
1472 std::sync::atomic::Ordering::Relaxed);
1473 if self.is_verbose() {
1474 eprintln!("[ccxt] ← {status} {} bytes", text.len());
1475 const CAP: usize = 16384;
1476 if text.len() > CAP {
1477 eprintln!("[ccxt] response body: {}… ({} bytes total)",
1478 &text[..text.char_indices().take_while(|(i, _)| *i < CAP).last().map(|(i, c)| i + c.len_utf8()).unwrap_or(0)],
1479 text.len());
1480 } else {
1481 eprintln!("[ccxt] response body: {text}");
1482 }
1483 }
1484 let __json_t0 = std::time::Instant::now();
1485 let json = match serde_json::from_str::<serde_json::Value>(&text) {
1486 Ok(j) => Value::from_json(&j),
1487 Err(_) => Value::Null,
1488 };
1489 JSON_NANOS.fetch_add(__json_t0.elapsed().as_nanos() as u64,
1490 std::sync::atomic::Ordering::Relaxed);
1491 let handled = crate::exchange::DerivedExchange::handle_errors(
1494 self,
1495 Value::Int(status as i64),
1496 Value::Str(reason.into()),
1497 Value::Str(url.to_string().into()),
1498 Value::Str(method.to_string().into()),
1499 Value::Null,
1500 Value::Str(text.clone().into()),
1501 json.clone(),
1502 Value::Null,
1503 Value::Null,
1504 );
1505 if matches!(handled, Value::Null) {
1506 self.handle_http_status_code(
1507 Value::Int(status as i64),
1508 Value::Str(reason.into()),
1509 Value::Str(url.to_string().into()),
1510 Value::Str(method.to_string().into()),
1511 Value::Str(text.clone().into()),
1512 );
1513 }
1514 if status >= 400 {
1515 return Err(ExchangeError::new(
1516 if status == 429 { "RateLimitExceeded" }
1517 else if status >= 500 { "ExchangeNotAvailable" }
1518 else { "ExchangeError" },
1519 format!("HTTP {status}: {text}"),
1520 ));
1521 }
1522 if matches!(json, Value::Null) {
1523 return Ok(Value::Str(text.into()));
1524 }
1525 Ok(json)
1526 } }
1527
1528 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 {
1529 if matches!(self.mock_response, Value::Null) && matches!(self.mock_response_by_url, Value::Null) {
1531 self.throttle(&[cost]).await;
1532 }
1533 let api_arg = Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect());
1534 let scope_lookup: String = scope_segments.first().cloned().unwrap_or_default();
1535 let signed = crate::exchange::DerivedExchange::sign(
1537 self,
1538 Value::Str(path.to_string().into()),
1539 api_arg,
1540 Value::Str(verb.to_string().into()),
1541 params.clone(),
1542 Value::Null,
1543 Value::Null,
1544 );
1545 if let Value::Dict(m) = &signed {
1546 let url = match m.get("url") { Some(Value::Str(s)) => s.to_string(), _ => String::new().into() };
1547 let method = match m.get("method") { Some(Value::Str(s)) => s.to_string(), _ => verb.to_string().into() };
1548 let body = match m.get("body") { Some(Value::Str(s)) => Some(s.to_string()), _ => None };
1549 let headers = match m.get("headers") {
1550 Some(Value::Dict(h)) => h.iter()
1551 .filter_map(|(k, v)| match v { Value::Str(s) => Some((k.clone(), s.to_string())), _ => None })
1552 .collect::<HashMap<_, _>>(),
1553 _ => HashMap::new(),
1554 };
1555 if !url.is_empty() {
1556 return self.fetch_typed(&url, &method, headers, body).await;
1557 }
1558 }
1559 let base = self.url_for_scope(&scope_lookup).ok_or_else(|| ExchangeError::new(
1560 "BadRequest",
1561 format!("no URL configured for api scope `{scope_lookup}`"),
1562 ))?;
1563 let imploded = self.implode_params(Value::Str(path.to_string().into()), params.clone());
1564 let path_str = match &imploded { Value::Str(s) => s.clone(), _ => path.to_string().into() };
1565 let consumed_keys = self.extract_path_params(path);
1566 let remaining_params = match params {
1567 Value::Dict(m) => {
1568 let mut keep = HashMap::new();
1569 let m = Arc::try_unwrap(m).unwrap_or_else(|a| (*a).clone());
1570 for (k, v) in m {
1571 if !consumed_keys.contains(&k) { keep.insert(k, v); }
1572 }
1573 Value::Map(keep)
1574 }
1575 other => other,
1576 };
1577 let mut url = format!("{}/{}", base.trim_end_matches('/'), path_str.trim_start_matches('/'));
1578 let mut body: Option<String> = None;
1579 let qs = match &remaining_params {
1580 Value::Dict(m) if !m.is_empty() => self.urlencode_kv(&remaining_params),
1581 _ => String::new(),
1582 };
1583 if verb == "GET" || verb == "DELETE" {
1584 if !qs.is_empty() {
1585 url = format!("{}?{}", url, qs);
1586 }
1587 } else if !qs.is_empty() {
1588 body = Some(qs);
1589 }
1590 let mut headers = HashMap::new();
1591 if scope_lookup != "public" {
1592 if let Value::Str(k) = &self.apiKey {
1593 headers.insert("X-MBX-APIKEY".to_string(), k.to_string());
1594 }
1595 }
1596 self.fetch_typed(&url, verb, headers, body).await
1597 } }
1598
1599 fn implicit_api_call(&mut self, name: &str, params: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1601 if self.internals.implicit_api.is_empty() {
1602 self.build_implicit_api();
1603 }
1604 let entry = self.internals.implicit_api.get(name).cloned();
1605 let (path, scope_segments, verb, config) = match entry {
1606 Some(t) => t,
1607 None => return Err(ExchangeError::new(
1608 "NotSupported",
1609 format!("implicit API method {name} not found in api block"),
1610 )),
1611 };
1612 let api = Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect());
1613 let cost = if matches!(self.enableRateLimit, Value::Bool(true)) {
1614 self.call_dynamic(
1615 "calculate_rate_limiter_cost",
1616 vec![api, Value::Str(verb.clone().into()), Value::Str(path.clone().into()), params.clone(), config],
1617 ).await
1618 } else {
1619 Value::Null
1620 };
1621 self.request_typed(&path, &scope_segments, &verb, params, cost).await
1622 } }
1623
1624 #[doc(hidden)]
1625 fn implicit_api_rate_limit_cost(&mut self, name: &str, params: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1626 if self.internals.implicit_api.is_empty() {
1627 self.build_implicit_api();
1628 }
1629 let (path, scope_segments, verb, config) = self.internals.implicit_api
1630 .get(name)
1631 .cloned()
1632 .ok_or_else(|| ExchangeError::new("NotSupported", format!("implicit API method {name} not found in api block")))?;
1633 let api = Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect());
1634 Ok(self.call_dynamic(
1635 "calculate_rate_limiter_cost",
1636 vec![api, Value::Str(verb.into()), Value::Str(path.into()), params, config],
1637 ).await)
1638 } }
1639
1640 fn call_method(&mut self, name: Value, args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1642 let n = match name { Value::Str(s) => s, _ => return Value::Null };
1643 let params = args.get(0).cloned().unwrap_or(Value::Map(HashMap::new()));
1644 match self.implicit_api_call(&n, params).await {
1645 Ok(v) => v,
1646 Err(e) => {
1647 if matches!(self.verbose, Value::Bool(true)) {
1648 eprintln!("[ccxt] {n} failed: {e}");
1649 }
1650 panic!("{e}");
1651 }
1652 }
1653 } }
1654
1655 fn load_markets(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1658 let reload = optional_args.get(0).cloned().unwrap_or(Value::Bool(false));
1659 let reload_b = matches!(reload, Value::Bool(true));
1660 if !reload_b && !self.markets.is_null() {
1661 return self.markets.clone();
1662 }
1663 let has_fetch_currencies = matches!(
1664 crate::get_value(&self.has, &Value::Str("fetchCurrencies".into())),
1665 Value::Bool(true),
1666 );
1667 let mut currencies = Value::Null;
1668 if has_fetch_currencies {
1669 if let Some(v) = self.dispatch_to_derived("fetch_currencies", Vec::new()).await {
1670 currencies = v;
1671 }
1672 }
1673 let fetched = match self.dispatch_to_derived("fetch_markets", Vec::new()).await {
1674 Some(v) => v,
1675 None => return Value::Null,
1676 };
1677 if matches!(fetched, Value::Null) {
1678 return self.markets.clone();
1679 }
1680 let preloaded_non_empty = matches!(&self.currencies, Value::Dict(m) if !m.is_empty());
1681 let currencies_arg = if matches!(¤cies, Value::Dict(m) if !m.is_empty()) {
1682 currencies
1683 } else if preloaded_non_empty {
1684 self.currencies.clone()
1685 } else {
1686 crate::exchange_stubs::synthesize_currencies_from_markets(&fetched, &self.precisionMode)
1687 };
1688 let is_prediction = matches!(
1689 crate::get_value(&self.has, &Value::Str("prediction".into())),
1690 Value::Bool(true),
1691 );
1692 if is_prediction {
1693 let _ = self.dispatch_to_derived("set_markets", vec![fetched, currencies_arg]).await;
1694 } else {
1695 <Self as crate::exchange_generated::ExchangeBase>::set_markets(self, fetched, &[currencies_arg]);
1696 }
1697 let markets_snapshot = self.markets.clone();
1702 if let Value::Dict(markets) = &markets_snapshot {
1703 if let Value::Dict(by_id_arc) = &self.markets_by_id {
1704 let mut by_id = (**by_id_arc).clone();
1705 for market in markets.values() {
1706 let id = crate::get_value(market, &Value::Str("id".into()));
1707 let id2 = crate::get_value(market, &Value::Str("id2".into()));
1708 if let (Value::Str(id2s), Value::Str(ids)) = (&id2, &id) {
1709 if id2s != ids && !id2s.is_empty() && !by_id.contains_key(id2s.as_ref()) {
1710 by_id.insert(id2s.to_string(), Value::List(vec![market.clone()]));
1711 }
1712 }
1713 }
1714 self.markets_by_id = Value::Map(by_id);
1715 }
1716 }
1717 self.markets.clone()
1718 } }
1719
1720 fn super_describe(&self) -> Value {
1723 <Self as crate::exchange_generated::ExchangeBase>::describe(self)
1724 }
1725 fn super_set_sandbox_mode(&mut self, enabled: Value) {
1726 <Self as crate::exchange_generated::ExchangeBase>::set_sandbox_mode(self, enabled);
1727 }
1728 fn super_safe_market(&self, id: Value, market: Value, delim: Value, market_type: Value) -> Value {
1729 <Self as crate::exchange_generated::ExchangeBase>::safe_market(self, &[id, market, delim, market_type])
1730 }
1731 fn super_handle_market_type_and_params(&self, method_name: Value, market: Value, params: Value, default_value: Value) -> Value {
1732 <Self as crate::exchange_generated::ExchangeBase>::handle_market_type_and_params(self, method_name, &[market, params, default_value])
1733 }
1734 fn super_market(&self, symbol: Value) -> Value {
1735 <Self as crate::exchange_generated::ExchangeBase>::market_non_virtual(self, symbol)
1736 }
1737 fn super_amount_to_precision(&self, symbol: Value, amount: Value) -> Value {
1738 <Self as crate::exchange_generated::ExchangeBase>::amount_to_precision(self, symbol, amount)
1739 }
1740 fn super_handle_margin_mode_and_params(&self, method_name: Value, params: Value, default_value: Value) -> Value {
1741 <Self as crate::exchange_generated::ExchangeBase>::handle_margin_mode_and_params(self, method_name, &[params, default_value])
1742 }
1743 fn super_safe_currency_code(&self, currency_id: Value, currency: Value) -> Value {
1744 <Self as crate::exchange_generated::ExchangeBase>::safe_currency_code(self, currency_id, &[currency])
1745 }
1746 fn super_set_markets(&mut self, markets: Value, currencies: Value) -> Value {
1747 <Self as crate::exchange_generated::ExchangeBase>::set_markets(self, markets, &[currencies])
1748 }
1749 fn super_network_id_to_code(&self, optional_args: &[Value]) -> Value {
1750 <Self as crate::exchange_generated::ExchangeBase>::network_id_to_code(self, optional_args)
1751 }
1752 fn super_network_code_to_id(&self, network_code: Value, optional_args: &[Value]) -> Value {
1753 <Self as crate::exchange_generated::ExchangeBase>::network_code_to_id(self, network_code, optional_args)
1754 }
1755 fn super_fetch_deposit_address(&mut self, code: Value, params: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
1756 self.fetch_deposit_address(code, &[params]).await
1757 } }
1758 fn super_load_markets(&mut self, reload: Value, params: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
1759 self.load_markets(&[reload, params]).await
1760 } }
1761}
1762
1763impl<T: crate::exchange_generated::ExchangeBase> ExchangeRuntime for T {}
1764
1765pub fn method_name_to_snake_case(name: &Value) -> String {
1781 let name = match name {
1782 Value::Str(name) if !name.is_empty() => name,
1783 _ => panic!(
1784 "{}",
1785 crate::exchange_errors::not_supported(format!(
1786 "dynamic method dispatch requires a non-empty string method name, got {name:?}"
1787 )),
1788 ),
1789 };
1790 let chars: Vec<char> = name.chars().collect();
1791 let mut out = String::with_capacity(name.len() + 4);
1792 for (i, &c) in chars.iter().enumerate() {
1793 if c.is_ascii_uppercase() {
1794 let lower_before = i > 0
1795 && (chars[i - 1].is_ascii_lowercase() || chars[i - 1].is_ascii_digit());
1796 let acronym_end = i > 0 && chars[i - 1].is_ascii_uppercase()
1797 && chars.get(i + 1).map(|next| next.is_ascii_lowercase()).unwrap_or(false);
1798 if lower_before || acronym_end {
1799 out.push('_');
1800 }
1801 out.push(c.to_ascii_lowercase());
1802 } else {
1803 out.push(c);
1804 }
1805 }
1806 out
1807}
1808
1809pub trait CallDynamicChecked: crate::exchange_generated::ExchangeBase {
1818 fn call_dynamic_checked(&mut self, name: Value, args: Vec<Value>) -> impl ::std::future::Future<Output = Value> + Send { async move {
1819 let snake = method_name_to_snake_case(&name);
1820 self.internals.dynamic_dispatch_miss = None;
1823 let out = self.call_dynamic(&snake, args).await;
1824 if self.internals.dynamic_dispatch_miss.as_deref() == Some(snake.as_str()) {
1827 self.internals.dynamic_dispatch_miss = None;
1828 panic!(
1829 "{}",
1830 crate::exchange_errors::not_supported(format!(
1831 "{} dynamic method {snake}() resolved to no dispatch arm and no implicit API endpoint",
1832 crate::runtime::stringify_param(&self.id),
1833 )),
1834 );
1835 }
1836 out
1837 } }
1838}
1839
1840impl<T: crate::exchange_generated::ExchangeBase> CallDynamicChecked for T {}
1841
1842pub struct BaseCore {
1848 pub exchange: Exchange,
1849}
1850impl BaseCore {
1851 pub fn new(exchange: Exchange) -> Self { Self { exchange } }
1852 pub fn into_inner(self) -> Exchange { self.exchange }
1853}
1854impl std::ops::Deref for BaseCore {
1855 type Target = Exchange;
1856 fn deref(&self) -> &Exchange { &self.exchange }
1857}
1858impl std::ops::DerefMut for BaseCore {
1859 fn deref_mut(&mut self) -> &mut Exchange { &mut self.exchange }
1860}
1861impl DerivedExchange for BaseCore {}
1862impl crate::exchange_generated::ExchangeBase for BaseCore {
1863 fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<Value>)
1864 -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>>
1865 {
1866 Box::pin(async move { self.call_dynamic_base(method, args).await })
1867 }
1868}
1869
1870impl Exchange {
1873 pub fn build_implicit_api(&mut self) {
1883 let mut map: HashMap<String, (String, Vec<String>, String, Value)> = HashMap::new();
1884 Self::walk_api_node(&self.api, &[], &mut map);
1885 self.internals.implicit_api = map;
1886 }
1887
1888 fn walk_api_node(
1889 node: &Value,
1890 crumbs: &[String],
1891 out: &mut HashMap<String, (String, Vec<String>, String, Value)>,
1892 ) {
1893 let known_verbs = ["get", "post", "put", "delete", "patch"];
1894 let last_is_verb = crumbs.last()
1895 .map(|c| known_verbs.iter().any(|v| *v == c.to_lowercase().as_str()))
1896 .unwrap_or(false);
1897 match node {
1898 Value::Dict(m) if last_is_verb => {
1902 let verb = crumbs.last().unwrap().to_lowercase();
1903 let scope_snake = Self::api_scope_from_crumbs(&crumbs[..crumbs.len() - 1]);
1905 let scope_segments: Vec<String> = crumbs[..crumbs.len() - 1].to_vec();
1911 for (path_key, endpoint_config) in m.iter() {
1912 let config = match endpoint_config {
1913 Value::Dict(_) => endpoint_config.clone(),
1914 Value::Int(_) | Value::Float(_) => Value::Map({
1915 let mut config = crate::value::HashMap::new();
1916 config.insert("cost".to_string(), endpoint_config.clone());
1917 config
1918 }),
1919 _ => Value::Map(crate::value::HashMap::new()),
1920 };
1921 Self::register_implicit(&verb, &scope_snake, &scope_segments, path_key, config, out);
1922 }
1923 }
1924 Value::Dict(m) => {
1925 for (key, child) in m.iter() {
1926 let mut next = crumbs.to_vec();
1927 next.push(key.clone());
1928 Self::walk_api_node(child, &next, out);
1929 }
1930 }
1931 Value::Arr(a) if last_is_verb => {
1933 let verb = crumbs.last().unwrap().to_lowercase();
1934 let scope_snake = Self::api_scope_from_crumbs(&crumbs[..crumbs.len() - 1]);
1935 let scope_segments: Vec<String> = crumbs[..crumbs.len() - 1].to_vec();
1936 for path in a.iter() {
1937 let (path_str, config) = match path {
1938 Value::Str(s) => (s.clone(), Value::Map(crate::value::HashMap::new())),
1939 Value::Dict(pm) => match pm.get("method").or_else(|| pm.get("path")) {
1940 Some(Value::Str(s)) => (s.clone(), path.clone()),
1941 _ => continue,
1942 },
1943 _ => continue,
1944 };
1945 Self::register_implicit(&verb, &scope_snake, &scope_segments, &path_str, config, out);
1946 }
1947 }
1948 _ => {}
1949 }
1950 }
1951
1952 fn api_scope_from_crumbs(crumbs: &[String]) -> String {
1953 crumbs.iter()
1957 .map(|s| s
1958 .chars()
1959 .enumerate()
1960 .flat_map(|(i, c)| {
1961 if c.is_ascii_uppercase() && i > 0 {
1962 vec!['_', c.to_ascii_lowercase()]
1963 } else {
1964 vec![c.to_ascii_lowercase()]
1965 }
1966 })
1967 .collect::<String>())
1968 .collect::<Vec<_>>()
1969 .join("_")
1970 }
1971
1972 fn register_implicit(
1973 verb: &str,
1974 scope_snake: &str,
1975 scope_segments: &[String],
1976 path: &str,
1977 config: Value,
1978 out: &mut HashMap<String, (String, Vec<String>, String, Value)>,
1979 ) {
1980 let camel: String = path
1989 .split(|c: char| !c.is_ascii_alphanumeric())
1990 .filter(|s| !s.is_empty())
1991 .map(|seg| {
1992 let mut chars = seg.chars();
1993 match chars.next() {
1994 None => String::new(),
1995 Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
1996 }
1997 })
1998 .collect();
1999 let snake = Self::to_snake_case(&camel);
2003 let snake_name = if snake.is_empty() {
2007 format!("{scope_snake}_{verb}")
2008 } else {
2009 format!("{scope_snake}_{verb}_{snake}")
2010 };
2011 let scope_camel: String = scope_segments.iter()
2016 .enumerate()
2017 .map(|(i, s)| {
2018 if i == 0 {
2019 s.to_string()
2020 } else {
2021 let mut chars = s.chars();
2022 match chars.next() {
2023 None => String::new(),
2024 Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
2025 }
2026 }
2027 })
2028 .collect();
2029 let verb_camel = {
2030 let mut chars = verb.chars();
2031 match chars.next() {
2032 None => String::new(),
2033 Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str().to_lowercase().as_str(),
2034 }
2035 };
2036 let camel_name = format!("{scope_camel}{verb_camel}{camel}");
2037 let camel_snake_name = Self::to_snake_case(&camel_name);
2047 let entry = (path.to_string(), scope_segments.to_vec(), verb.to_uppercase(), config);
2048 out.insert(snake_name, entry.clone());
2049 if !out.contains_key(&camel_snake_name) {
2050 out.insert(camel_snake_name, entry.clone());
2051 }
2052 if !out.contains_key(&camel_name) {
2053 out.insert(camel_name, entry);
2054 }
2055 }
2056
2057 fn to_snake_case(s: &str) -> String {
2058 let bytes: Vec<char> = s.chars().collect();
2060 let mut out = String::with_capacity(s.len() + 4);
2061 for i in 0..bytes.len() {
2062 let c = bytes[i];
2063 let prev = if i > 0 { Some(bytes[i - 1]) } else { None };
2064 let next = if i + 1 < bytes.len() { Some(bytes[i + 1]) } else { None };
2065 if c.is_ascii_uppercase() {
2066 let prev_lower_or_digit = prev
2067 .map(|p| p.is_ascii_lowercase() || p.is_ascii_digit())
2068 .unwrap_or(false);
2069 let prev_upper = prev.map(|p| p.is_ascii_uppercase()).unwrap_or(false);
2070 let next_lower = next.map(|n| n.is_ascii_lowercase()).unwrap_or(false);
2071 if prev_lower_or_digit {
2072 out.push('_');
2073 } else if prev_upper && next_lower {
2074 out.push('_');
2075 }
2076 }
2077 out.push(c.to_ascii_lowercase());
2078 }
2079 while out.contains("__") {
2081 out = out.replace("__", "_");
2082 }
2083 out.trim_matches('_').to_string()
2084 }
2085
2086 fn url_for_scope(&self, scope: &str) -> Option<String> {
2089 let api = crate::get_value(&self.urls, &Value::Str("api".into()));
2090 let scoped = crate::get_value(&api, &Value::Str(scope.to_string().into()));
2092 let raw = match scoped {
2093 Value::Str(s) => s,
2094 Value::Dict(m) => match m.get("rest").or_else(|| m.get("current")) {
2095 Some(Value::Str(s)) => s.clone(),
2096 _ => return self.fallback_rest_url(&api),
2097 },
2098 _ => return self.fallback_rest_url(&api),
2099 };
2100 Some(self.implode_hostname_typed(&raw))
2101 }
2102
2103 fn fallback_rest_url(&self, api: &Value) -> Option<String> {
2107 let rest = crate::get_value(api, &Value::Str("rest".into()));
2108 if let Value::Str(s) = rest {
2109 return Some(self.implode_hostname_typed(&s));
2110 }
2111 if let Value::Str(s) = api {
2113 return Some(self.implode_hostname_typed(s));
2114 }
2115 None
2116 }
2117
2118 fn implode_hostname_typed(&self, url: &str) -> String {
2120 let host = match &self.hostname {
2121 Value::Str(s) => s.clone(),
2122 _ => return url.to_string(),
2123 };
2124 url.replace("{hostname}", &host)
2125 }
2126
2127 fn extract_path_params(&self, path: &str) -> Vec<String> {
2133 let mut out: Vec<String> = vec![];
2134 let mut chars = path.chars().peekable();
2135 while let Some(c) = chars.next() {
2136 if c == '{' {
2137 let mut name = String::new();
2138 while let Some(&nc) = chars.peek() {
2139 if nc == '}' { chars.next(); break; }
2140 name.push(nc); chars.next();
2141 }
2142 if !name.is_empty() { out.push(name); }
2143 }
2144 }
2145 out
2146 }
2147}
2148
2149pub(crate) fn hash_raw(data: &[u8], algo: &str) -> Vec<u8> {
2152 match algo.to_ascii_lowercase().as_str() {
2153 "sha256" => { let mut h = Sha256::new(); h.update(data); h.finalize().to_vec() }
2154 "sha512" => { let mut h = Sha512::new(); h.update(data); h.finalize().to_vec() }
2155 "sha1" => { let mut h = Sha1::new(); h.update(data); h.finalize().to_vec() }
2156 "md5" => { let mut h = Md5::new(); h.update(data); h.finalize().to_vec() }
2157 "keccak" | "keccak256" => {
2158 use sha3::{Keccak256, Digest as _};
2159 let mut h = Keccak256::new();
2160 h.update(data);
2161 h.finalize().to_vec()
2162 }
2163 _ => Vec::new(),
2164 }
2165}
2166
2167type Eip712Types = std::collections::BTreeMap<String, Vec<(String, String)>>;
2171
2172fn eip712_base_type(ty: &str) -> &str {
2175 match ty.find('[') { Some(i) => &ty[..i], None => ty }
2176}
2177
2178fn eip712_encode_type(primary: &str, types: &Eip712Types) -> String {
2182 fn collect(name: &str, types: &Eip712Types, deps: &mut std::collections::BTreeSet<String>) {
2183 if let Some(fields) = types.get(name) {
2184 for (_, ty) in fields {
2185 let base = eip712_base_type(ty).to_string();
2186 if types.contains_key(&base) && deps.insert(base.clone()) {
2187 collect(&base, types, deps);
2188 }
2189 }
2190 }
2191 }
2192 let fmt = |name: &str| -> String {
2193 let fields = types.get(name).cloned().unwrap_or_default();
2194 let inner: Vec<String> = fields.iter().map(|(n, t)| format!("{t} {n}")).collect();
2195 format!("{}({})", name, inner.join(","))
2196 };
2197 let mut deps = std::collections::BTreeSet::new();
2198 collect(primary, types, &mut deps);
2199 deps.remove(primary);
2200 let mut out = fmt(primary);
2201 for dep in &deps { out.push_str(&fmt(dep)); } out
2203}
2204
2205pub(crate) fn eip712_encode(domain: &Value, types: &Value, message: &Value) -> Vec<u8> {
2206 let dm = match domain { Value::Dict(m) => m, _ => return Vec::new() };
2207 let mut domain_fields: Vec<(String, String)> = Vec::new();
2209 for (n, t) in [("name", "string"), ("version", "string"), ("chainId", "uint256"),
2210 ("verifyingContract", "address"), ("salt", "bytes32")] {
2211 if dm.contains_key(n) { domain_fields.push((n.to_string(), t.to_string())); }
2212 }
2213 let mut domain_types: Eip712Types = Eip712Types::new();
2215 domain_types.insert("EIP712Domain".to_string(), domain_fields);
2216 let domain_sep = eip712_hash_struct("EIP712Domain", domain, &domain_types);
2217
2218 let mut type_map: Eip712Types = Eip712Types::new();
2220 if let Value::Dict(m) = types {
2221 for (name, def) in m.iter() {
2222 if name == "EIP712Domain" { continue; }
2223 if let Value::Arr(arr) = def {
2224 let fields: Vec<(String, String)> = arr.iter().filter_map(|it| match it {
2225 Value::Dict(fm) => Some((
2226 fm.get("name")?.as_str()?.to_string(),
2227 fm.get("type")?.as_str()?.to_string(),
2228 )),
2229 _ => None,
2230 }).collect();
2231 type_map.insert(name.clone(), fields);
2232 }
2233 }
2234 }
2235 if type_map.is_empty() { return Vec::new(); }
2236 let referenced: std::collections::HashSet<String> = type_map.values()
2239 .flat_map(|fs| fs.iter().map(|(_, t)| eip712_base_type(t).to_string()))
2240 .collect();
2241 let primary = type_map.keys().find(|k| !referenced.contains(*k)).cloned()
2242 .unwrap_or_else(|| type_map.keys().next().cloned().unwrap_or_default());
2243 let struct_hash = eip712_hash_struct(&primary, message, &type_map);
2244 let mut out = vec![0x19u8, 0x01u8];
2245 out.extend_from_slice(&domain_sep);
2246 out.extend_from_slice(&struct_hash);
2247 out
2248}
2249
2250fn eip712_hash_struct(type_name: &str, data: &Value, types: &Eip712Types) -> Vec<u8> {
2253 let type_str = eip712_encode_type(type_name, types);
2254 let mut enc = hash_raw(type_str.as_bytes(), "keccak"); let dm = match data { Value::Dict(m) => Some(m), _ => None };
2256 let fields = types.get(type_name).cloned().unwrap_or_default();
2257 for (name, ty) in &fields {
2258 let v = dm.and_then(|m| m.get(name)).cloned().unwrap_or(Value::Null);
2259 let base = eip712_base_type(ty);
2260 if types.contains_key(base) {
2261 enc.extend_from_slice(&eip712_hash_struct(base, &v, types));
2263 } else {
2264 enc.extend_from_slice(&eip712_encode_value(ty, &v));
2265 }
2266 }
2267 hash_raw(&enc, "keccak")
2268}
2269
2270pub(crate) fn eip712_int_word(ty: &str, n: &num_bigint::BigInt) -> [u8; 32] {
2278 use num_bigint::{BigInt, Sign};
2279 let signed = ty.starts_with("int");
2280 let digits = ty.trim_start_matches(if signed { "int" } else { "uint" });
2281 let mut width: usize = if digits.is_empty() { 256 } else { digits.parse().unwrap_or(256) };
2282 if !((8..=256).contains(&width) && width % 8 == 0) { width = 256; }
2283 let mut out = [0u8; 32];
2284 if !signed {
2285 if n.sign() == Sign::Minus {
2286 panic!("eip712/abi: negative value {n} supplied for unsigned type {ty}");
2287 }
2288 let max = (BigInt::from(1) << width) - 1;
2289 if n > &max {
2290 panic!("eip712/abi: value {n} overflows {ty} (max {max})");
2291 }
2292 let (_, be) = n.to_bytes_be();
2293 let take = be.len().min(32);
2294 out[32 - take..].copy_from_slice(&be[be.len() - take..]);
2295 } else {
2296 let min = -(BigInt::from(1) << (width - 1));
2297 let max = (BigInt::from(1) << (width - 1)) - 1;
2298 if n < &min || n > &max {
2299 panic!("eip712/abi: value {n} out of range for {ty} ([{min}, {max}])");
2300 }
2301 if n.sign() == Sign::Minus { out = [0xff; 32]; }
2302 let be = n.to_signed_bytes_be();
2303 let take = be.len().min(32);
2304 out[32 - take..].copy_from_slice(&be[be.len() - take..]);
2305 }
2306 out
2307}
2308
2309fn eip712_encode_value(ty: &str, v: &Value) -> [u8; 32] {
2310 let mut out = [0u8; 32];
2311 if ty == "string" || ty == "bytes" {
2312 out.copy_from_slice(&hash_raw(&value_to_bytes(v), "keccak"));
2313 } else if ty.starts_with("bytes") {
2314 let b = eip712_bytes(v);
2316 let n = b.len().min(32);
2317 out[..n].copy_from_slice(&b[..n]);
2318 } else if ty == "address" {
2319 let b = eip712_bytes(v);
2321 let take = b.len().min(20);
2322 out[32 - take..].copy_from_slice(&b[b.len() - take..]);
2323 } else if ty == "bool" {
2324 if matches!(v, Value::Bool(true)) { out[31] = 1; }
2325 } else if ty.starts_with("uint") || ty.starts_with("int") {
2326 use num_bigint::BigInt;
2329 let n: BigInt = match v {
2330 Value::Int(i) => BigInt::from(*i),
2331 Value::Float(f) => BigInt::from(*f as i64),
2332 Value::Str(s) => {
2333 let t = s.trim();
2334 if let Some(h) = t.strip_prefix("0x") {
2335 BigInt::parse_bytes(h.as_bytes(), 16).unwrap_or_default()
2336 } else {
2337 BigInt::parse_bytes(t.as_bytes(), 10).unwrap_or_default()
2338 }
2339 }
2340 _ => BigInt::from(0),
2341 };
2342 out = eip712_int_word(ty, &n);
2343 }
2344 out
2345}
2346
2347fn eip712_bytes(v: &Value) -> Vec<u8> {
2349 match v {
2350 Value::Str(s) => {
2351 let h = s.strip_prefix("0x").unwrap_or(s);
2352 hex::decode(h).unwrap_or_else(|_| s.as_bytes().to_vec())
2353 }
2354 _ => value_to_bytes(v),
2355 }
2356}
2357
2358pub(crate) fn value_to_bytes(v: &Value) -> Vec<u8> {
2359 match v {
2360 Value::Str(s) => s.as_bytes().to_vec(),
2361 Value::Arr(a) => a.iter().filter_map(|x| match x {
2362 Value::Int(n) => Some(*n as u8),
2363 _ => None,
2364 }).collect(),
2365 _ => Vec::new(),
2366 }
2367}
2368
2369pub(crate) fn url_pct(s: &str) -> String {
2370 s.bytes().map(|b| match b {
2371 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
2372 _ => format!("%{b:02X}"),
2373 }).collect()
2374}
2375
2376#[cfg(test)]
2390mod method_name_snake_case_tests {
2391 use super::{method_name_to_snake_case, Exchange};
2392 use crate::Value;
2393
2394 fn snake(name: &str) -> String {
2395 method_name_to_snake_case(&Value::Str(name.to_string().into()))
2396 }
2397
2398 #[test]
2401 fn matches_the_transpiler_dispatch_arm_names() {
2402 assert_eq!(snake("fetchTransfers"), "fetch_transfers");
2404 assert_eq!(snake("fetchOHLCV"), "fetch_ohlcv"); assert_eq!(snake("fetchOpenOrdersWs"), "fetch_open_orders_ws");
2406 assert_eq!(snake("fetchL2OrderBook"), "fetch_l2_order_book"); assert_eq!(snake("getLeverageTiersPaginated"), "get_leverage_tiers_paginated");
2408 assert_eq!(snake("publicGetTicker24hr"), "public_get_ticker24hr"); assert_eq!(snake("webExchangeGetV3Assets"), "web_exchange_get_v3_assets");
2412 assert_eq!(snake("webApiGetAjaxCoinCoinInfo"), "web_api_get_ajax_coin_coin_info");
2413 assert_eq!(snake("parseHTTPResponse"), "parse_http_response");
2415 assert_eq!(snake("fetchOHLCVWs"), "fetch_ohlcv_ws");
2416 assert_eq!(snake("fetch"), "fetch");
2418 assert_eq!(snake("fetch_transfers"), "fetch_transfers");
2419 }
2420
2421 #[test]
2426 fn agrees_with_exchange_to_snake_case() {
2427 for name in [
2428 "fetchTransfers", "fetchOHLCV", "fetchOpenOrdersWs", "publicGetTicker24hr",
2429 "fetchL2OrderBook", "webExchangeGetV3Assets", "webApiGetAjaxCoinCoinInfo",
2430 "parseHTTPResponse", "fetchOHLCVWs", "privatePostSPEIWithdrawal",
2431 "sapiV3GetAsset", "fapiPublicGetTicker24hr", "publicGet10PublicTickers",
2432 "fetch", "fetchPositionsRisk", "createOrderWs", "fetchMyLiquidations",
2433 ] {
2434 assert_eq!(
2435 snake(name),
2436 Exchange::to_snake_case(name),
2437 "method_name_to_snake_case and Exchange::to_snake_case diverge on {name}",
2438 );
2439 }
2440 }
2441
2442 #[test]
2445 #[should_panic(expected = "NotSupported")]
2446 fn non_string_method_name_is_loud() {
2447 let _ = method_name_to_snake_case(&Value::Int(7));
2448 }
2449
2450 #[test]
2451 #[should_panic(expected = "NotSupported")]
2452 fn empty_method_name_is_loud() {
2453 let _ = method_name_to_snake_case(&Value::Str(String::new().into()));
2454 }
2455}
2456
2457#[cfg(test)]
2458mod eip712_int_tests {
2459 use super::eip712_int_word;
2460 use num_bigint::BigInt;
2461
2462 #[test]
2463 fn uint8_max_ok_and_int8_bounds_ok() {
2464 assert_eq!(eip712_int_word("uint8", &BigInt::from(255))[31], 255);
2465 let _ = eip712_int_word("int8", &BigInt::from(127));
2466 let _ = eip712_int_word("int8", &BigInt::from(-128));
2467 }
2468
2469 #[test]
2470 fn i64_u64_boundaries_ok() {
2471 let _ = eip712_int_word("int64", &BigInt::from(i64::MAX));
2472 let _ = eip712_int_word("int64", &BigInt::from(i64::MIN));
2473 let _ = eip712_int_word("uint64", &BigInt::from(u64::MAX));
2474 }
2475
2476 #[test]
2479 fn u64_plus_one_preserved_in_uint256() {
2480 let n = BigInt::from(u64::MAX) + 1;
2481 assert_eq!(eip712_int_word("uint256", &n)[23], 1);
2482 }
2483
2484 #[test]
2485 fn negative_int_is_twos_complement() {
2486 assert_eq!(eip712_int_word("int256", &BigInt::from(-1)), [0xff; 32]);
2487 }
2488
2489 #[test]
2490 #[should_panic(expected = "overflows")]
2491 fn uint8_overflow_rejected() { let _ = eip712_int_word("uint8", &BigInt::from(256)); }
2492
2493 #[test]
2494 #[should_panic(expected = "negative")]
2495 fn uint_negative_rejected() { let _ = eip712_int_word("uint256", &BigInt::from(-1)); }
2496
2497 #[test]
2498 #[should_panic(expected = "out of range")]
2499 fn int8_overflow_rejected() { let _ = eip712_int_word("int8", &BigInt::from(128)); }
2500
2501 #[test]
2502 #[should_panic(expected = "overflows")]
2503 fn uint64_plus_one_rejected() {
2504 let _ = eip712_int_word("uint64", &(BigInt::from(u64::MAX) + 1));
2505 }
2506}
2507
2508#[cfg(test)]
2509mod throttle_tests {
2510 use super::Exchange;
2511 use crate::Value;
2512
2513 #[test]
2514 fn implicit_api_retains_endpoint_cost_config() {
2515 let mut by_limit = crate::value::HashMap::new();
2516 by_limit.insert("cost".to_string(), Value::Int(2));
2517 by_limit.insert("byLimit".to_string(), Value::List(vec![
2518 Value::List(vec![Value::Int(100), Value::Int(5)]),
2519 ]));
2520 let mut endpoints = crate::value::HashMap::new();
2521 endpoints.insert("ticker".to_string(), Value::Float(0.1));
2522 endpoints.insert("depth".to_string(), Value::Map(by_limit.clone()));
2523 let mut verbs = crate::value::HashMap::new();
2524 verbs.insert("get".to_string(), Value::Map(endpoints));
2525 let mut api = crate::value::HashMap::new();
2526 api.insert("public".to_string(), Value::Map(verbs));
2527 let mut exchange = Exchange::new(None);
2528 exchange.api = Value::Map(api);
2529 exchange.build_implicit_api();
2530 let ticker_config = &exchange.internals.implicit_api["public_get_ticker"].3;
2531 assert_eq!(
2532 crate::get_value(ticker_config, &Value::Str("cost".into())),
2533 Value::Float(0.1),
2534 "numeric endpoint costs must be normalized to a config object"
2535 );
2536 let depth_config = &exchange.internals.implicit_api["public_get_depth"].3;
2537 assert_eq!(depth_config, &Value::Map(by_limit), "object endpoint config must be retained");
2538 }
2539
2540 #[tokio::test]
2542 async fn spaces_requests_by_rate_limit() {
2543 let mut ex = Exchange::new(None);
2544 ex.enableRateLimit = Value::Bool(true);
2545 ex.rateLimit = Value::Int(15); let start = std::time::Instant::now();
2547 for _ in 0..5 { ex.throttle(&[]).await; }
2548 let elapsed = start.elapsed().as_millis();
2549 assert!(elapsed >= 45, "throttle did not space requests: {elapsed}ms");
2551 }
2552
2553 #[tokio::test]
2555 async fn disabled_is_noop() {
2556 let mut ex = Exchange::new(None);
2557 ex.enableRateLimit = Value::Bool(false);
2558 ex.rateLimit = Value::Int(1000);
2559 let start = std::time::Instant::now();
2560 for _ in 0..5 { ex.throttle(&[]).await; }
2561 assert!(start.elapsed().as_millis() < 50, "disabled throttle slept");
2562 }
2563}
2564
2565#[cfg(all(test, feature = "engine"))]
2566mod cow_alias_tests {
2567 use super::Exchange;
2568 use crate::Value;
2569 use crate::runtime::get_array_length;
2570
2571 #[test]
2575 fn convert_ohlcv_to_trading_view_preserves_pushes() {
2576 use crate::exchange_generated::ExchangeBase;
2577 let ex = super::BaseCore::new(Exchange::new(None));
2578 let row = Value::List(vec![
2579 Value::Int(1_700_000_000_000), Value::Int(1), Value::Int(2),
2580 Value::Int(0), Value::Int(1), Value::Int(10),
2581 ]);
2582 let ohlcvs = Value::List(vec![row.clone(), row]);
2583 let r = ex.convert_ohlcv_to_trading_view(ohlcvs, &[]);
2584 for key in ["t", "o", "h", "l", "c", "v"] {
2585 let col = crate::get_value(&r, &Value::Str(key.to_string().into()));
2586 assert_eq!(get_array_length(&col), Value::Int(2),
2587 "result['{key}'] lost its pushes — COW write-back failed");
2588 }
2589 }
2590}
2591
2592#[cfg(test)]
2593mod http_error_tests {
2594 use super::{BaseCore, DerivedExchange, Exchange, ExchangeRuntime};
2595 use crate::Value;
2596 use futures::FutureExt;
2597 use std::io::{Read, Write};
2598
2599 fn serve_once(status_line: &'static str, body: &'static str) -> String {
2601 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2602 let url = format!("http://{}/", listener.local_addr().unwrap());
2603 std::thread::spawn(move || {
2604 let (mut stream, _) = listener.accept().unwrap();
2605 let mut request = [0u8; 4096];
2606 let _ = stream.read(&mut request);
2607 let response = format!(
2608 "HTTP/1.1 {status_line}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
2609 body.len(),
2610 );
2611 stream.write_all(response.as_bytes()).unwrap();
2612 });
2613 url
2614 }
2615
2616 struct EnvelopeCore {
2618 exchange: Exchange,
2619 }
2620 impl std::ops::Deref for EnvelopeCore {
2621 type Target = Exchange;
2622 fn deref(&self) -> &Exchange { &self.exchange }
2623 }
2624 impl std::ops::DerefMut for EnvelopeCore {
2625 fn deref_mut(&mut self) -> &mut Exchange { &mut self.exchange }
2626 }
2627 impl DerivedExchange for EnvelopeCore {
2628 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 {
2629 let code = crate::get_value(&response, &Value::Str("code".into()));
2630 if !matches!(code, Value::Null) && code != Value::Str("0".into()) {
2631 panic!("{}", crate::exchange_errors::create_error("InsufficientFunds", "code 51008"));
2632 }
2633 Value::Null
2634 }
2635 }
2636 impl crate::exchange_generated::ExchangeBase for EnvelopeCore {
2637 fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<Value>)
2638 -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>>
2639 {
2640 Box::pin(async move { self.call_dynamic_base(method, args).await })
2641 }
2642 }
2643
2644 async fn fetch_error<C: ExchangeRuntime + Send>(core: &mut C, url: String) -> String {
2645 let outcome = std::panic::AssertUnwindSafe(core.fetch(Value::Str(url.into()), &[])).catch_unwind().await;
2646 match outcome {
2647 Ok(value) => format!("no error, returned {value:?}"),
2648 Err(payload) => payload.downcast_ref::<String>().cloned().unwrap_or_default(),
2649 }
2650 }
2651
2652 #[tokio::test]
2653 async fn an_error_in_a_2xx_body_reaches_handle_errors() {
2654 let url = serve_once("200 OK", r#"{"code":"51008","msg":"Insufficient balance"}"#);
2655 let mut core = EnvelopeCore { exchange: Exchange::new(None) };
2656 let error = fetch_error(&mut core, url).await;
2657 assert!(error.contains("InsufficientFunds"), "{error}");
2658 }
2659
2660 #[tokio::test]
2661 async fn a_status_in_http_exceptions_raises_its_class() {
2662 let url = serve_once("401 Unauthorized", "{}");
2663 let mut core = BaseCore::new(Exchange::new(None));
2664 let error = fetch_error(&mut core, url).await;
2665 assert!(error.contains("AuthenticationError"), "{error}");
2666 }
2667
2668 #[tokio::test]
2669 async fn a_status_outside_http_exceptions_still_fails() {
2670 let url = serve_once("402 Payment Required", "{}");
2671 let mut core = BaseCore::new(Exchange::new(None));
2672 let error = fetch_error(&mut core, url).await;
2673 assert!(error.contains("ExchangeError"), "{error}");
2674 }
2675}