Skip to main content

ccxt_common/
exchange.rs

1// Native Rust – Exchange base class.
2//
3// Methods BELOW the `METHODS BELOW THIS LINE ARE TRANSPILED FROM TYPESCRIPT`
4// marker in `ts/src/base/Exchange.ts` are transpiled into
5// `exchange_generated.rs` (opt-in behind the `transpiled-base` feature
6// while the transpiler-port is in progress).
7//
8// Methods ABOVE the marker are hand-written here — they are the
9// language-specific pieces that can't be transpiled:
10//   • HTTP client (reqwest)
11//   • Cryptographic primitives (HMAC-SHA256/512, SHA256/512, MD5)
12//   • Base64/hex encoding, URL-encoding, JSON
13//   • String utilities mirroring CCXT's `js/src/base/functions.ts`
14//
15// **Field layout.** The transpiler treats every field on Exchange as
16// `Value` (Python/PHP-style dynamic typing). To stay compatible without
17// fighting Rust's type system, every public field on `Exchange` is
18// `crate::Value` — transpiled code can read/write them directly.
19// Rust-typed runtime state (the HTTP client, the verbose flag, etc.)
20// lives on the private `Internals` sub-struct.
21
22#![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
38/// Callback type used by derived exchanges to provide their `describe()` data.
39pub type DescribeCallback = Arc<dyn Fn() -> Value + Send + Sync>;
40
41// HTTP/JSON timing counters — accumulated by `fetch_typed`, read+reset
42// by the CLI / benchmarks via `take_http_timings()`.
43static 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    // URLs whose WS drive loop is active on the current task's call stack. A
49    // spawned coroutine that does a nested `self.watch(sameUrl)` (bitvavo's
50    // getBook, htx's snapshot req) must NOT start a second drive loop — that
51    // would block the outer loop on a hash the outer loop is responsible for
52    // resolving. Instead it just sends its subscribe frame and returns; the
53    // outer loop processes the reply. Task-local so it survives task migration.
54    static WS_DRIVEN_URLS: std::sync::Mutex<std::collections::HashSet<String>>;
55}
56
57/// Snapshot + reset the global HTTP/JSON timings. Returns
58/// `(http_nanos, json_nanos, http_calls)` and zeroes them.
59pub 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
68// ── Internals (Rust-typed runtime state, not exposed to transpiled code) ─────
69
70pub 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    /// Leaky-bucket rate-limiter state, `(tokens, last_refill_ms)`, shared and
76    /// interior-mutable so the `&self` async `throttle()` can serialize requests
77    /// on one exchange instance. See `Exchange::throttle`.
78    pub throttle:       std::sync::Arc<tokio::sync::Mutex<(f64, i64)>>,
79    /// Cached dispatch table built from `self.api`. Maps the snake-case
80    /// implicit API name (e.g. `public_get_exchange_info`) to
81    /// `(path, api_scope, http_verb, endpoint_config)`.
82    pub implicit_api:   HashMap<String, (String, Vec<String>, String, Value)>,
83    /// Method names currently being dispatched to a derived override. Lets the
84    /// async `dispatch_to_derived` default (in `ExchangeBase`) block recursion
85    /// on a single method while allowing sibling dispatches. This is the only
86    /// dispatch state left — virtual dispatch itself is now static (review #1),
87    /// so there are no raw self-pointers to keep.
88    pub dispatch_stack:       Vec<String>,
89    /// Last snake_case name that reached `call_dynamic_base`'s `_` arm and
90    /// matched neither a dispatch arm nor an implicit-API endpoint. That arm
91    /// must keep returning `Value::Null` (a static-request test may probe an
92    /// optional name), but a dynamic re-entry from `fetchPaginatedCall*` /
93    /// `fetchWebEndpoint` treats a miss as fatal — see
94    /// `crate::exchange::call_dynamic_required`.
95    pub dynamic_dispatch_miss: Option<String>,
96}
97
98/// The Go-style "interface" that every derived exchange implements. When
99/// Exchange.ts calls `this.parseTicker(...)` (and similar), the transpiler
100/// rewrites it to `self.derived().parse_ticker(...)`; that goes through
101/// this trait's vtable to the derived exchange's override.
102///
103/// Default impls return `Value::Null` so an unbound Exchange still
104/// compiles and runs (it just gives back empty results).
105pub trait DerivedExchange {
106    // ── parsers (the dominant override surface) ──────────────────────────
107    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    // ── prediction-tier parsers (overridden by prediction venues) ────────
144    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    // ── signers / error handlers ─────────────────────────────────────────
148    /// `nonce()` — the request timestamp. The base default is `seconds()`, but
149    /// 47 venues override it (binance: `milliseconds() - timeDifference`), and
150    /// without a slot here the override is invisible to any caller that reaches
151    /// the base through a trait method — notably a pro Core, which finds
152    /// `ExchangeBase::nonce` at deref step 0 and never looks at the REST
153    /// parent's inherent one. Binance spot then signs its ws-api subscribe with
154    /// a seconds timestamp and the venue answers -1130.
155    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
160// `Internals` no longer holds raw pointers, so `Send`/`Sync` are auto-derived
161// (its fields — `reqwest::Client`, `Arc<dyn Fn + Send + Sync>`,
162// `Arc<tokio::Mutex<_>>`, maps, `Vec<String>` — are all thread-safe). No manual
163// `unsafe impl` and no `PhantomPinned` are needed now that dispatch is static
164// (review #1: thread safety is compiler-proven, not asserted).
165
166// A cloned Exchange gets a fresh `Internals` — the http client and dispatch
167// state are per-instance and must not be shared.
168// Test-only callers (`clone_self`) only read `Value` fields off the copy.
169impl 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// ── Exchange struct ─────────────────────────────────────────────────────────
189//
190// Every transpiler-visible field is `Value`. Both camelCase and snake_case
191// names appear because the TS source uses both interchangeably.
192
193#[derive(Clone)]
194pub struct Exchange {
195    // identity
196    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    // credentials
206    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    // rate limiting / connection
219    pub timeout:                Value,
220    pub rateLimit:              Value,
221    pub enableRateLimit:        Value,
222    pub rateLimiterAlgorithm:   Value,
223    pub rollingWindowSize:      Value,
224    pub tokenBucket:            Value,
225    /// The raw constructor config, kept so `initialize_properties` can merge it
226    /// over `describe()` the way Go's `InitParent` does
227    /// (`deepExtend(describe, userConfig)`) instead of relying on per-field
228    /// precedence guards in each Core's generated `init()`.
229    pub userConfig:             Value,
230    pub verbose:                Value,
231    pub isSandboxModeEnabled:   Value,
232
233    // proxy
234    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    // market data caches
259    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    // runtime state
284    pub orderbooks:        Value,
285    pub orders:            Value,
286    pub trades:            Value,
287    pub myTrades:          Value,
288    pub positions:         Value,
289    // WS state — mirrors `ts/src/base/Exchange.ts` `newUpdates: boolean = true`.
290    // Per-exchange WS code reads `self.newUpdates` to decide whether to call
291    // `cache.getLimit(...)` (return only what's new since the last call) or
292    // emit the whole rolling buffer.
293    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    // last-* tracking
308    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    /// Canned HTTP response for static *response* tests — when set,
314    /// `fetch_typed` returns it without hitting the network so the
315    /// exchange's parser runs against fixture data. Mirrors Go's
316    /// `MockResponse` field. Reused for all requests in a fixture; the test
317    /// dispatcher replaces or clears it before the next REST dispatch.
318    pub mock_response:           Value,
319    /// Response-test mock keyed by url fragment, for methods that call several
320    /// endpoints: one shared body cannot cover two endpoints of different
321    /// declared shapes. Consulted before `mock_response`.
322    pub mock_response_by_url:    Value,
323    pub last_json_response:      Value,
324    pub lastRestRequestTimestamp: Value,
325    /// Rolling cache of recent fetch results, capped at
326    /// `fetchHistoryCacheSize`. Mirrors `Exchange.ts` `fetchHistoryCache`
327    /// / `fetchHistoryCacheSize` (hand-written, above the transpile marker).
328    pub fetchHistoryCache:      Value,
329    pub fetchHistoryCacheSize:  Value,
330
331    // misc
332    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    // user-agent / fetch behavior
344    pub userAgent:                 Value,
345    pub user_agent:                Value,
346    pub userAgents:                Value,
347
348    // describe() output (legacy)
349    pub describe_data:             Value,
350    pub derived_describe:          Option<DescribeCallback>,
351
352    // private runtime state (typed)
353    pub internals: Internals,
354}
355
356impl Default for Exchange {
357    fn default() -> Self { Self::new(None) }
358}
359
360// ── base-class describe() defaults (Exchange.ts) ────────────────────────────
361// Mirrors the constant sub-objects returned by the base `describe()` so a
362// plain `Exchange` carries the same shape as CCXT (verified by the
363// transpiled `test.afterConstructor` base test).
364
365fn 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
417/// `deepExtend(a, b)` — recursive merge; `b` wins on scalar conflicts,
418/// nested maps merge key-by-key.
419fn 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            // Base-class id (Exchange.ts describe()). A derived exchange's
462            // describe() overrides this with its own id.
463            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            // Base-class default (Exchange.ts). Kept when an exchange's
483            // describe() doesn't override it — so `checkRequiredCredentials`
484            // still works even though `super.describe()` is stubbed.
485            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            // Base-class default `options` (Exchange.ts describe()). Kept
559            // when an exchange's describe() omits it — `super.describe()`
560            // is stubbed, so it wouldn't otherwise flow through.
561            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        // NOTE: `afterConstruct()` is deliberately NOT run here. In TS the
644        // constructor applies describe() and only then calls afterConstruct,
645        // so the bits it derives (networksById, the features table, the
646        // tokenBucket, the sandbox swap) see the venue's own values. Running
647        // it at this point — before the derived Core's describe() has been
648        // applied — is what made every venue throttle at the base 2000ms and
649        // forced a string of compensations in the generated `init()`. Each
650        // Core's `init()` now calls it last; a bare `Exchange` with no derived
651        // Core (base unit tests, `BaseCore`) calls `after_construct` itself.
652        ex
653    }
654
655    /// Apply a merged `describe()` + constructor-config map onto the typed
656    /// fields. The Rust counterpart of Go's `initializeProperties`
657    /// (`go/v4/exchange_options.go`) and of the TS constructor's
658    /// `deepExtend(this, describe(), userConfig)` — which Rust cannot do
659    /// directly because `Exchange` is a struct, not a dynamic object.
660    ///
661    /// Each Core's generated `init()` used to inline ~84 lines of this, which
662    /// is why every field carried its own precedence guard: config was applied
663    /// in `new()` BEFORE `describe()` ran, so `describe()` had to be stopped
664    /// from clobbering it. Here the config is merged over `describe()` first
665    /// (Go's `deepExtend(describe, userConfig)`), so last-write-wins is the
666    /// precedence rule and no guards are needed.
667    ///
668    /// Absent keys leave the base default in place — the equivalent of Go's
669    /// `SafeString(props, key, default)`.
670    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        // `options` and `commonCurrencies` MERGE rather than replace: the base
700        // Exchange seeds defaults into both, and describe() only supplies the
701        // venue's additions.
702        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        // A venue whose describe() ships its own markets (the hard-coded ones)
721        // resolves load_markets without a network call. Guarded on markets not
722        // already being loaded, so config-injected markets win.
723        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        // WS proxies: the `watch*` transport dials these through an HTTP
758        // CONNECT tunnel. Without them here a config-supplied `wsProxy` set
759        // the field on nothing and the socket quietly went direct.
760        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        // Pre-populated state (mirrors CCXT TS Exchange constructor):
765        // markets/currencies/options arrive ready to use from offline
766        // tests, the CLI, or library users seeding state. `setMarkets`
767        // also derives markets_by_id and symbols.
768        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    /// `markets`-from-config → derives `markets_by_id` + `symbols`.
787    /// Accepts either Map<symbol, market> or Array<market>.
788    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        // `markets_by_id` maps an exchange market id → the *list* of
796        // markets sharing that id (e.g. binance spot + swap both have
797        // id `BTCUSDT`); `safeMarket` disambiguates by market type.
798        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    // ── http client ─────────────────────────────────────────────────────────
817
818    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                // Transparent gzip: many exchanges return large JSON payloads
823                // (binance spot exchangeInfo is ~17 MB raw vs ~0.3 MB gzipped).
824                // Other CCXT langs request gzip by default; without this rust
825                // downloads the full uncompressed body, dominating load time.
826                .gzip(true);
827            if let Some(ua) = self.user_agent_str() { b = b.user_agent(ua); }
828            // Apply scheme-specific proxies. Order matters for reqwest's
829            // proxy matcher: SOCKS catches everything when set, HTTP/HTTPS
830            // only match their own scheme. The legacy `proxy` (and its
831            // snake_case alias) plus tests' `httpsProxy` use the catch-all
832            // form via Proxy::all(...). The `socks` feature on `reqwest`
833            // is what makes `socks5://...` URIs actually route — without
834            // it `Proxy::all` would build but the connection silently
835            // never goes through SOCKS.
836            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            // Legacy single `proxy` setter (catch-all). Only honoured if
859            // none of the scheme-specific fields fired.
860            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    // ── encoding / URL helpers ──────────────────────────────────────────────
894
895    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 &params { 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    // ── crypto ──────────────────────────────────────────────────────────────
922
923    pub fn hmac(&self, data: Value, secret: Value, hash: Value, optional_args: &[Value]) -> Value {
924        // `data`/`secret` may be a string OR the byte-array produced by
925        // `encode()` (CCXT's `hmac` takes the encoded request/secret).
926        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        // `data` may be a string OR the byte-array produced by `encode()`.
957        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` → a byte-array Value (consumed by another crypto step).
966            "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    // ── time ────────────────────────────────────────────────────────────────
1004
1005    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        // rfc3339 (`T…Z` / `+00:00` offset forms).
1039        if let Ok(t) = chrono::DateTime::parse_from_rfc3339(&str_val) {
1040            return Value::Int(t.timestamp_millis());
1041        }
1042        // Numeric timezone offset WITHOUT a colon (`+0000`) — not valid
1043        // rfc3339 but common (e.g. bitso `2024-03-13T10:59:59+0000`). JS
1044        // `Date.parse` accepts it; chrono needs an explicit `%z` format.
1045        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        // Lenient fallbacks — naive forms are interpreted as UTC.
1054        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    // safe_string/safe_number/safe_integer/safe_bool live on the transpiled
1072    // side (`exchange_generated.rs`) when the `transpiled-base` feature is
1073    // enabled. The free-functions in `crate::value` are the typed
1074    // equivalents — used internally by hand-written code below.
1075
1076
1077}
1078
1079// ── small helper used by url-encoding above ─────────────────────────────────
1080
1081// ── derived dispatch re-entry guard ─────────────────────────────────────────
1082//
1083// Virtual dispatch itself is now STATIC: `ExchangeBase`'s default methods call
1084// `DerivedExchange::X(self, ...)` and `self.call_dynamic(...)` directly on the
1085// concrete Core, with no stored self-pointer (review #1). All that remains here
1086// is the per-method re-entry guard the async `dispatch_to_derived` default (in
1087// `exchange_generated::ExchangeBase`) uses so a base method that dispatches its
1088// own name falls through to the base body instead of looping.
1089
1090impl Exchange {
1091    /// Enter the guard for `method`. Returns `false` if `method` is already on
1092    /// the dispatch stack (re-entry — caller should fall through to the base
1093    /// body); otherwise pushes it and returns `true`.
1094    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    /// Leave the guard (pop the most-recently entered method).
1101    pub fn dispatch_guard_exit(&mut self) {
1102        self.internals.dispatch_stack.pop();
1103    }
1104}
1105
1106// ── ExchangeRuntime: base methods that reach derived overrides ───────────────
1107//
1108// A handful of hand-written base methods must call a derived override
1109// (`sign`, `handle_errors`) or dispatch async-by-name, so they need the
1110// concrete Core as `Self` to resolve statically (review #1). They live in this
1111// trait, blanket-impl'd for every `ExchangeBase`, so `self.fetch(...)`,
1112// `self.request_typed(...)`, … on a Core (or inside an `ExchangeBase` default)
1113// resolve here. Bodies reach `Exchange` fields via the `DerefMut` bound, other
1114// base methods via `ExchangeBase`, and pure `impl Exchange` helpers via `Deref`.
1115/// Coerce a `Value` (string, or list of strings) into a `Vec<String>` of
1116/// message/subscribe hashes for the WS drive loop.
1117fn 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            // `panic!` is the transpiled error convention — `ExchangeError`'s Display
1149            // renders `[Kind] message`, which `is_instance` matches on.
1150            Err(e) => panic!("{}", e),
1151        }
1152    } }
1153
1154    // ── WebSocket (pro) drive loop ──────────────────────────────────────────
1155    //
1156    // Port of the runtime side of `Exchange.watch` / `watchMultiple`. These are
1157    // trait methods (not inherent on `Exchange`) so `self` is the concrete Core
1158    // and `dispatch_to_derived("handle_message", …)` reaches the venue override.
1159    //
1160    // Model: `watch` drives synchronously — it connects, sends the subscribe
1161    // frame once, then loops reading inbound frames and feeding each to the
1162    // venue's `handle_message` (which calls `client.resolve(value, hash)`),
1163    // returning as soon as one of the awaited hashes is settled. A repeated
1164    // `while true { watch_x().await }` consumer therefore gets one update per
1165    // call, exactly like the TS Future model. (Concurrently awaiting two streams
1166    // on the *same* socket via join is a known limitation — each drive loop
1167    // pulls from the shared frame queue.)
1168
1169    /// Shared drive loop for `watch` / `watch_multiple`.
1170    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        // binary frames are decompressed unless the exchange opts out (mexc, paradex)
1182        let __decompress_binary = !matches!(crate::get_value(&self.options, &Value::Str("decompressBinary".into())), Value::Bool(false));
1183        // options.ws.options.headers ride on the upgrade request, as in the other ports
1184        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        // Subscribe once per hash. Send the message if any subscribe hash was
1202        // newly added, or if none were provided (mirrors TS's
1203        // `subscribeHashes === undefined || missingSubscriptions.length`).
1204        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        // Mirror the connection into `self.clients`, the map TS venues iterate
1218        // to decide whether a stream is still worth keeping alive (binance's
1219        // `keepAliveListenKey` re-arms only while some client still holds a
1220        // subscription for the type). The handle serves `subscriptions` /
1221        // `futures` live from the registry, so this stays coherent as
1222        // subscriptions come and go.
1223        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        // If an ancestor ws_run on this task is already driving `url`, don't
1229        // start a nested loop — the subscribe frame was sent above; report the
1230        // current settled state and let the outer loop resolve `hashes`.
1231        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        // Drive the loop, marking `url` for the duration so a nested watch on
1241        // the same url takes the branch above. Establish the task-local set on
1242        // the first (top-level) drive; nested-different-url calls extend it.
1243        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    /// Read → dispatch → drain loop, split out so `ws_run` can wrap it in the
1258    /// `WS_DRIVEN_URLS` task-local scope.
1259    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            // Run coroutines scheduled via spawn/delay, inline (they need
1267            // &mut self). Drain repeatedly: a coroutine may schedule another
1268            // (handle_order_book → delay(watch_order_book_snapshot)). Runs at
1269            // the top of the iteration rather than after the dispatch below so
1270            // the `continue` on a fired deadline reaches it too.
1271            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            // Bound the read by the earliest pending `delay` deadline, so a
1298            // periodic coroutine (binance's `keepAliveListenKey`) still fires
1299            // on a stream that has gone quiet. `next_message` keeps its frames
1300            // in the client's queue, so timing out drops nothing.
1301            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                    // Deadline reached: loop back round to the drain above.
1306                    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    /// Base `loadOrderBook`: fetch the REST depth snapshot, splice the buffered
1328    /// WS cache onto it, and resolve the watcher. Venues spawn this after
1329    /// buffering enough deltas (bitstamp, …). Runs in the drive loop so it can
1330    /// reach the venue's `get_cache_index` / `handle_deltas` overrides.
1331    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        // map iteration is unordered, so sort the fragments for a deterministic pick
1423        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        // expose the response headers the way the other ports do (last_response_headers and
1471        // the `headers` argument of handle_errors): venues read them, e.g. grvt takes its
1472        // session cookie and account id from Set-Cookie / X-Grvt-Account-Id on sign-in.
1473        // reqwest lowercases header names; repeated headers are joined with ", " like node-fetch
1474        let mut response_headers: HashMap<String, Value> = HashMap::new();
1475        for name in resp.headers().keys() {
1476            let joined = resp.headers().get_all(name).iter()
1477                .filter_map(|v| v.to_str().ok())
1478                .collect::<Vec<&str>>()
1479                .join(", ");
1480            response_headers.insert(name.as_str().to_string(), Value::Str(joined.into()));
1481        }
1482        let response_headers_value = Value::Map(response_headers.into_iter().collect());
1483        self.last_response_headers = response_headers_value.clone();
1484        let text   = resp.text().await?;
1485        HTTP_NANOS.fetch_add(__http_t0.elapsed().as_nanos() as u64,
1486            std::sync::atomic::Ordering::Relaxed);
1487        if self.is_verbose() {
1488            eprintln!("[ccxt] ← {status} {} bytes", text.len());
1489            const CAP: usize = 16384;
1490            if text.len() > CAP {
1491                eprintln!("[ccxt]   response body: {}… ({} bytes total)",
1492                    &text[..text.char_indices().take_while(|(i, _)| *i < CAP).last().map(|(i, c)| i + c.len_utf8()).unwrap_or(0)],
1493                    text.len());
1494            } else {
1495                eprintln!("[ccxt]   response body: {text}");
1496            }
1497        }
1498        let __json_t0 = std::time::Instant::now();
1499        let json = match serde_json::from_str::<serde_json::Value>(&text) {
1500            Ok(j)  => Value::from_json(&j),
1501            Err(_) => Value::Null,
1502        };
1503        JSON_NANOS.fetch_add(__json_t0.elapsed().as_nanos() as u64,
1504            std::sync::atomic::Ordering::Relaxed);
1505        // Venues also report failures in a 2xx body, so every response goes through
1506        // the derived handle_errors; a Null result falls back to httpExceptions.
1507        let handled = crate::exchange::DerivedExchange::handle_errors(
1508            self,
1509            Value::Int(status as i64),
1510            Value::Str(reason.into()),
1511            Value::Str(url.to_string().into()),
1512            Value::Str(method.to_string().into()),
1513            response_headers_value,
1514            Value::Str(text.clone().into()),
1515            json.clone(),
1516            Value::Null,
1517            Value::Null,
1518        );
1519        if matches!(handled, Value::Null) {
1520            self.handle_http_status_code(
1521                Value::Int(status as i64),
1522                Value::Str(reason.into()),
1523                Value::Str(url.to_string().into()),
1524                Value::Str(method.to_string().into()),
1525                Value::Str(text.clone().into()),
1526            );
1527        }
1528        if status >= 400 {
1529            return Err(ExchangeError::new(
1530                if status == 429 { "RateLimitExceeded" }
1531                else if status >= 500 { "ExchangeNotAvailable" }
1532                else { "ExchangeError" },
1533                format!("HTTP {status}: {text}"),
1534            ));
1535        }
1536        if matches!(json, Value::Null) {
1537            return Ok(Value::Str(text.into()));
1538        }
1539        Ok(json)
1540    } }
1541
1542    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 {
1543        // Mock transport responses only; preserve the signed request metadata.
1544        if matches!(self.mock_response, Value::Null) && matches!(self.mock_response_by_url, Value::Null) {
1545            self.throttle(&[cost]).await;
1546        }
1547        let api_arg = Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect());
1548        let scope_lookup: String = scope_segments.first().cloned().unwrap_or_default();
1549        // Static dispatch to the derived exchange's sign override.
1550        let signed = crate::exchange::DerivedExchange::sign(
1551            self,
1552            Value::Str(path.to_string().into()),
1553            api_arg,
1554            Value::Str(verb.to_string().into()),
1555            params.clone(),
1556            Value::Null,
1557            Value::Null,
1558        );
1559        if let Value::Dict(m) = &signed {
1560            let url = match m.get("url") { Some(Value::Str(s)) => s.to_string(), _ => String::new().into() };
1561            let method = match m.get("method") { Some(Value::Str(s)) => s.to_string(), _ => verb.to_string().into() };
1562            let body = match m.get("body") { Some(Value::Str(s)) => Some(s.to_string()), _ => None };
1563            let headers = match m.get("headers") {
1564                Some(Value::Dict(h)) => h.iter()
1565                    .filter_map(|(k, v)| match v { Value::Str(s) => Some((k.clone(), s.to_string())), _ => None })
1566                    .collect::<HashMap<_, _>>(),
1567                _ => HashMap::new(),
1568            };
1569            if !url.is_empty() {
1570                return self.fetch_typed(&url, &method, headers, body).await;
1571            }
1572        }
1573        let base = self.url_for_scope(&scope_lookup).ok_or_else(|| ExchangeError::new(
1574            "BadRequest",
1575            format!("no URL configured for api scope `{scope_lookup}`"),
1576        ))?;
1577        let imploded = self.implode_params(Value::Str(path.to_string().into()), params.clone());
1578        let path_str = match &imploded { Value::Str(s) => s.clone(), _ => path.to_string().into() };
1579        let consumed_keys = self.extract_path_params(path);
1580        let remaining_params = match params {
1581            Value::Dict(m) => {
1582                let mut keep = HashMap::new();
1583                let m = Arc::try_unwrap(m).unwrap_or_else(|a| (*a).clone());
1584                for (k, v) in m {
1585                    if !consumed_keys.contains(&k) { keep.insert(k, v); }
1586                }
1587                Value::Map(keep)
1588            }
1589            other => other,
1590        };
1591        let mut url = format!("{}/{}", base.trim_end_matches('/'), path_str.trim_start_matches('/'));
1592        let mut body: Option<String> = None;
1593        let qs = match &remaining_params {
1594            Value::Dict(m) if !m.is_empty() => self.urlencode_kv(&remaining_params),
1595            _ => String::new(),
1596        };
1597        if verb == "GET" || verb == "DELETE" {
1598            if !qs.is_empty() {
1599                url = format!("{}?{}", url, qs);
1600            }
1601        } else if !qs.is_empty() {
1602            body = Some(qs);
1603        }
1604        let mut headers = HashMap::new();
1605        if scope_lookup != "public" {
1606            if let Value::Str(k) = &self.apiKey {
1607                headers.insert("X-MBX-APIKEY".to_string(), k.to_string());
1608            }
1609        }
1610        self.fetch_typed(&url, verb, headers, body).await
1611    } }
1612
1613    /// Route an implicit-API method name to `request_typed`.
1614    fn implicit_api_call(&mut self, name: &str, params: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1615        if self.internals.implicit_api.is_empty() {
1616            self.build_implicit_api();
1617        }
1618        let entry = self.internals.implicit_api.get(name).cloned();
1619        let (path, scope_segments, verb, config) = match entry {
1620            Some(t) => t,
1621            None => return Err(ExchangeError::new(
1622                "NotSupported",
1623                format!("implicit API method {name} not found in api block"),
1624            )),
1625        };
1626        let api = Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect());
1627        let cost = if matches!(self.enableRateLimit, Value::Bool(true)) {
1628            self.call_dynamic(
1629                "calculate_rate_limiter_cost",
1630                vec![api, Value::Str(verb.clone().into()), Value::Str(path.clone().into()), params.clone(), config],
1631            ).await
1632        } else {
1633            Value::Null
1634        };
1635        self.request_typed(&path, &scope_segments, &verb, params, cost).await
1636    } }
1637
1638    #[doc(hidden)]
1639    fn implicit_api_rate_limit_cost(&mut self, name: &str, params: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1640        if self.internals.implicit_api.is_empty() {
1641            self.build_implicit_api();
1642        }
1643        let (path, scope_segments, verb, config) = self.internals.implicit_api
1644            .get(name)
1645            .cloned()
1646            .ok_or_else(|| ExchangeError::new("NotSupported", format!("implicit API method {name} not found in api block")))?;
1647        let api = Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect());
1648        Ok(self.call_dynamic(
1649            "calculate_rate_limiter_cost",
1650            vec![api, Value::Str(verb.into()), Value::Str(path.into()), params, config],
1651        ).await)
1652    } }
1653
1654    /// Dispatch an implicit-API method by name (from transpiled `_api.rs`).
1655    fn call_method(&mut self, name: Value, args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1656        let n = match name { Value::Str(s) => s, _ => return Value::Null };
1657        let params = args.get(0).cloned().unwrap_or(Value::Map(HashMap::new()));
1658        match self.implicit_api_call(&n, params).await {
1659            Ok(v) => v,
1660            Err(e) => {
1661                if matches!(self.verbose, Value::Bool(true)) {
1662                    eprintln!("[ccxt] {n} failed: {e}");
1663                }
1664                panic!("{e}");
1665            }
1666        }
1667    } }
1668
1669    /// Loads markets (and currencies), dispatching `fetch_markets` /
1670    /// `fetch_currencies` / `set_markets` to the derived overrides.
1671    fn load_markets(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1672        let reload = optional_args.get(0).cloned().unwrap_or(Value::Bool(false));
1673        let reload_b = matches!(reload, Value::Bool(true));
1674        if !reload_b && !self.markets.is_null() {
1675            return self.markets.clone();
1676        }
1677        let has_fetch_currencies = matches!(
1678            crate::get_value(&self.has, &Value::Str("fetchCurrencies".into())),
1679            Value::Bool(true),
1680        );
1681        let mut currencies = Value::Null;
1682        if has_fetch_currencies {
1683            if let Some(v) = self.dispatch_to_derived("fetch_currencies", Vec::new()).await {
1684                currencies = v;
1685            }
1686        }
1687        let fetched = match self.dispatch_to_derived("fetch_markets", Vec::new()).await {
1688            Some(v) => v,
1689            None => return Value::Null,
1690        };
1691        if matches!(fetched, Value::Null) {
1692            return self.markets.clone();
1693        }
1694        let preloaded_non_empty = matches!(&self.currencies, Value::Dict(m) if !m.is_empty());
1695        let currencies_arg = if matches!(&currencies, Value::Dict(m) if !m.is_empty()) {
1696            currencies
1697        } else if preloaded_non_empty {
1698            self.currencies.clone()
1699        } else {
1700            crate::exchange_stubs::synthesize_currencies_from_markets(&fetched, &self.precisionMode)
1701        };
1702        let is_prediction = matches!(
1703            crate::get_value(&self.has, &Value::Str("prediction".into())),
1704            Value::Bool(true),
1705        );
1706        if is_prediction {
1707            let _ = self.dispatch_to_derived("set_markets", vec![fetched, currencies_arg]).await;
1708        } else {
1709            <Self as crate::exchange_generated::ExchangeBase>::set_markets(self, fetched, &[currencies_arg]);
1710        }
1711        // Index markets_by_id by the secondary id (`id2`, e.g. apex's
1712        // crossSymbolName) too, so a WS handler that resolves a market from the
1713        // id2-based stream id (`safeMarket(data['s'])`) reaches the unified
1714        // symbol instead of a synthetic one.
1715        let markets_snapshot = self.markets.clone();
1716        if let Value::Dict(markets) = &markets_snapshot {
1717            if let Value::Dict(by_id_arc) = &self.markets_by_id {
1718                let mut by_id = (**by_id_arc).clone();
1719                for market in markets.values() {
1720                    let id  = crate::get_value(market, &Value::Str("id".into()));
1721                    let id2 = crate::get_value(market, &Value::Str("id2".into()));
1722                    if let (Value::Str(id2s), Value::Str(ids)) = (&id2, &id) {
1723                        if id2s != ids && !id2s.is_empty() && !by_id.contains_key(id2s.as_ref()) {
1724                            by_id.insert(id2s.to_string(), Value::List(vec![market.clone()]));
1725                        }
1726                    }
1727                }
1728                self.markets_by_id = Value::Map(by_id);
1729            }
1730        }
1731        self.markets.clone()
1732    } }
1733
1734    // ── super.X() shims — call the BASE (ExchangeBase) method, fully-qualified
1735    // so a derived override is bypassed (that is what `super.X()` means).
1736    fn super_describe(&self) -> Value {
1737        <Self as crate::exchange_generated::ExchangeBase>::describe(self)
1738    }
1739    fn super_set_sandbox_mode(&mut self, enabled: Value) {
1740        <Self as crate::exchange_generated::ExchangeBase>::set_sandbox_mode(self, enabled);
1741    }
1742    fn super_safe_market(&self, id: Value, market: Value, delim: Value, market_type: Value) -> Value {
1743        <Self as crate::exchange_generated::ExchangeBase>::safe_market(self, &[id, market, delim, market_type])
1744    }
1745    fn super_handle_market_type_and_params(&self, method_name: Value, market: Value, params: Value, default_value: Value) -> Value {
1746        <Self as crate::exchange_generated::ExchangeBase>::handle_market_type_and_params(self, method_name, &[market, params, default_value])
1747    }
1748    fn super_market(&self, symbol: Value) -> Value {
1749        <Self as crate::exchange_generated::ExchangeBase>::market_non_virtual(self, symbol)
1750    }
1751    fn super_amount_to_precision(&self, symbol: Value, amount: Value) -> Value {
1752        <Self as crate::exchange_generated::ExchangeBase>::amount_to_precision(self, symbol, amount)
1753    }
1754    fn super_handle_margin_mode_and_params(&self, method_name: Value, params: Value, default_value: Value) -> Value {
1755        <Self as crate::exchange_generated::ExchangeBase>::handle_margin_mode_and_params(self, method_name, &[params, default_value])
1756    }
1757    fn super_safe_currency_code(&self, currency_id: Value, currency: Value) -> Value {
1758        <Self as crate::exchange_generated::ExchangeBase>::safe_currency_code(self, currency_id, &[currency])
1759    }
1760    fn super_set_markets(&mut self, markets: Value, currencies: Value) -> Value {
1761        <Self as crate::exchange_generated::ExchangeBase>::set_markets(self, markets, &[currencies])
1762    }
1763    fn super_network_id_to_code(&self, optional_args: &[Value]) -> Value {
1764        <Self as crate::exchange_generated::ExchangeBase>::network_id_to_code(self, optional_args)
1765    }
1766    fn super_network_code_to_id(&self, network_code: Value, optional_args: &[Value]) -> Value {
1767        <Self as crate::exchange_generated::ExchangeBase>::network_code_to_id(self, network_code, optional_args)
1768    }
1769    fn super_fetch_deposit_address(&mut self, code: Value, params: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
1770        self.fetch_deposit_address(code, &[params]).await
1771    } }
1772    fn super_load_markets(&mut self, reload: Value, params: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
1773        self.load_markets(&[reload, params]).await
1774    } }
1775}
1776
1777impl<T: crate::exchange_generated::ExchangeBase> ExchangeRuntime for T {}
1778
1779/// Normalize a TS dynamic method name for the generated Rust dispatch table.
1780///
1781/// Must stay byte-identical to the transpiler's `toSnakeCase`
1782/// (`build/rustTranspiler.ts`) and to `Exchange::to_snake_case` (which names
1783/// the implicit-API entries `call_dynamic`'s fall-through looks up) — it is the
1784/// only thing deciding whether a paginated `this[method](...)` re-entry lands
1785/// on a dispatch arm. `method_name_snake_case_tests` pins all three.
1786///
1787/// A name that is not a `Value::Str` (or is empty) is a hard bug: TS
1788/// `this[name](...)` always indexes with a string. Returning `""` here would
1789/// resolve to no dispatch arm and no implicit endpoint, so `call_dynamic`
1790/// would hand back `Value::Null` and the caller would silently see an empty
1791/// page instead of an error — exactly the failure this PR set out to remove.
1792/// Panic instead, mirroring the TS `TypeError: this[method] is not a function`
1793/// (the transpiled try/catch turns it back into a catchable error).
1794pub fn method_name_to_snake_case(name: &Value) -> String {
1795    let name = match name {
1796        Value::Str(name) if !name.is_empty() => name,
1797        _ => panic!(
1798            "{}",
1799            crate::exchange_errors::not_supported(format!(
1800                "dynamic method dispatch requires a non-empty string method name, got {name:?}"
1801            )),
1802        ),
1803    };
1804    let chars: Vec<char> = name.chars().collect();
1805    let mut out = String::with_capacity(name.len() + 4);
1806    for (i, &c) in chars.iter().enumerate() {
1807        if c.is_ascii_uppercase() {
1808            let lower_before = i > 0
1809                && (chars[i - 1].is_ascii_lowercase() || chars[i - 1].is_ascii_digit());
1810            let acronym_end = i > 0 && chars[i - 1].is_ascii_uppercase()
1811                && chars.get(i + 1).map(|next| next.is_ascii_lowercase()).unwrap_or(false);
1812            if lower_before || acronym_end {
1813                out.push('_');
1814            }
1815            out.push(c.to_ascii_lowercase());
1816        } else {
1817            out.push(c);
1818        }
1819    }
1820    out
1821}
1822
1823/// Wraps a `call_dynamic` re-entry that MUST resolve. `call_dynamic_base`'s
1824/// `_` arm returns `Value::Null` for a name that is neither a dispatch arm nor
1825/// an implicit-API endpoint — fine for an optional probe, but a dynamic
1826/// re-entry from `fetchPaginatedCall*` / `fetchWebEndpoint` would then hand the
1827/// caller an empty page instead of an error. That arm records the miss on
1828/// `internals.dynamic_dispatch_miss`; this raises it as a loud `NotSupported`,
1829/// the way `call_method` used to fail, so a dispatch regression surfaces as an
1830/// error rather than as null data (review on #30385).
1831pub trait CallDynamicChecked: crate::exchange_generated::ExchangeBase {
1832    fn call_dynamic_checked(&mut self, name: Value, args: Vec<Value>) -> impl ::std::future::Future<Output = Value> + Send { async move {
1833        let snake = method_name_to_snake_case(&name);
1834        // Clear first: a miss recorded by an unrelated earlier probe must not
1835        // be attributed to this call.
1836        self.internals.dynamic_dispatch_miss = None;
1837        let out = self.call_dynamic(&snake, args).await;
1838        // Only OUR name counts — a nested optional probe inside the dispatched
1839        // method legitimately misses and must stay silent.
1840        if self.internals.dynamic_dispatch_miss.as_deref() == Some(snake.as_str()) {
1841            self.internals.dynamic_dispatch_miss = None;
1842            panic!(
1843                "{}",
1844                crate::exchange_errors::not_supported(format!(
1845                    "{} dynamic method {snake}() resolved to no dispatch arm and no implicit API endpoint",
1846                    crate::runtime::stringify_param(&self.id),
1847                )),
1848            );
1849        }
1850        out
1851    } }
1852}
1853
1854impl<T: crate::exchange_generated::ExchangeBase> CallDynamicChecked for T {}
1855
1856/// A minimal Core wrapping a bare `Exchange` with NO overrides. Lets code that
1857/// only has an `Exchange` value — `Value` snapshots (value.rs), the constructor
1858/// (`after_construct`), and base unit tests — call `ExchangeBase`/`ExchangeRuntime`
1859/// trait methods, which all resolve to the base defaults (review #1: base
1860/// methods are trait methods now, so a bare `Exchange` can't call them directly).
1861pub struct BaseCore {
1862    pub exchange: Exchange,
1863}
1864impl BaseCore {
1865    pub fn new(exchange: Exchange) -> Self { Self { exchange } }
1866    pub fn into_inner(self) -> Exchange { self.exchange }
1867}
1868impl std::ops::Deref for BaseCore {
1869    type Target = Exchange;
1870    fn deref(&self) -> &Exchange { &self.exchange }
1871}
1872impl std::ops::DerefMut for BaseCore {
1873    fn deref_mut(&mut self) -> &mut Exchange { &mut self.exchange }
1874}
1875impl DerivedExchange for BaseCore {}
1876impl crate::exchange_generated::ExchangeBase for BaseCore {
1877    fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<Value>)
1878        -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>>
1879    {
1880        Box::pin(async move { self.call_dynamic_base(method, args).await })
1881    }
1882}
1883
1884// ── implicit API dispatch ───────────────────────────────────────────────────
1885
1886impl Exchange {
1887    /// Builds the `name → (path, scope, verb)` dispatch table by walking
1888    /// the `self.api` Value::Map. Called lazily on first dynamic call.
1889    ///
1890    /// The `api` block layout is:
1891    ///   { <scope>: { <verb>: [path, path, ...] } }
1892    ///   { <scope>: { <subscope>: { <verb>: [path, ...] } } }
1893    /// — arbitrary nesting before the verb level. The verb is one of
1894    /// `get`/`post`/`put`/`delete`/`patch` (any case). All path components
1895    /// before the verb concatenate into the scope (joined by `_`).
1896    pub fn build_implicit_api(&mut self) {
1897        let mut map: HashMap<String, (String, Vec<String>, String, Value)> = HashMap::new();
1898        Self::walk_api_node(&self.api, &[], &mut map);
1899        self.internals.implicit_api = map;
1900    }
1901
1902    fn walk_api_node(
1903        node: &Value,
1904        crumbs: &[String],
1905        out: &mut HashMap<String, (String, Vec<String>, String, Value)>,
1906    ) {
1907        let known_verbs = ["get", "post", "put", "delete", "patch"];
1908        let last_is_verb = crumbs.last()
1909            .map(|c| known_verbs.iter().any(|v| *v == c.to_lowercase().as_str()))
1910            .unwrap_or(false);
1911        match node {
1912            // If the current level is a verb (`get`/`post`/…) and its child
1913            // is a Map, the keys ARE the paths (and values are rate-limit
1914            // costs — exchange-specific).
1915            Value::Dict(m) if last_is_verb => {
1916                let verb = crumbs.last().unwrap().to_lowercase();
1917                // Method name uses snake-cased scope (`fapi_public_get_X`).
1918                let scope_snake = Self::api_scope_from_crumbs(&crumbs[..crumbs.len() - 1]);
1919                // But sign()/urls.api lookup uses the original segments
1920                // (camelCase, e.g. `["fapiPublic"]` for binance,
1921                //  `["public","common"]` for bitget, `["public","spot"]`
1922                //  for gate). Preserve as Vec<String> so the dispatcher
1923                //  can choose Value::Str (single) vs Value::Array (multi).
1924                let scope_segments: Vec<String> = crumbs[..crumbs.len() - 1].to_vec();
1925                for (path_key, endpoint_config) in m.iter() {
1926                    let config = match endpoint_config {
1927                        Value::Dict(_) => endpoint_config.clone(),
1928                        Value::Int(_) | Value::Float(_) => Value::Map({
1929                            let mut config = crate::value::HashMap::new();
1930                            config.insert("cost".to_string(), endpoint_config.clone());
1931                            config
1932                        }),
1933                        _ => Value::Map(crate::value::HashMap::new()),
1934                    };
1935                    Self::register_implicit(&verb, &scope_snake, &scope_segments, path_key, config, out);
1936                }
1937            }
1938            Value::Dict(m) => {
1939                for (key, child) in m.iter() {
1940                    let mut next = crumbs.to_vec();
1941                    next.push(key.clone());
1942                    Self::walk_api_node(child, &next, out);
1943                }
1944            }
1945            // Some exchanges use `Array<path-string>` at the verb level.
1946            Value::Arr(a) if last_is_verb => {
1947                let verb = crumbs.last().unwrap().to_lowercase();
1948                let scope_snake = Self::api_scope_from_crumbs(&crumbs[..crumbs.len() - 1]);
1949                let scope_segments: Vec<String> = crumbs[..crumbs.len() - 1].to_vec();
1950                for path in a.iter() {
1951                    let (path_str, config) = match path {
1952                        Value::Str(s) => (s.clone(), Value::Map(crate::value::HashMap::new())),
1953                        Value::Dict(pm) => match pm.get("method").or_else(|| pm.get("path")) {
1954                            Some(Value::Str(s)) => (s.clone(), path.clone()),
1955                            _ => continue,
1956                        },
1957                        _ => continue,
1958                    };
1959                    Self::register_implicit(&verb, &scope_snake, &scope_segments, &path_str, config, out);
1960                }
1961            }
1962            _ => {}
1963        }
1964    }
1965
1966    fn api_scope_from_crumbs(crumbs: &[String]) -> String {
1967        // The scope identifier in TS is camelCase (e.g. `fapiPrivate`),
1968        // but transpiled call sites are snake_case (`fapi_private_get_X`).
1969        // Convert each crumb camelCase → snake_case and join with `_`.
1970        crumbs.iter()
1971            .map(|s| s
1972                .chars()
1973                .enumerate()
1974                .flat_map(|(i, c)| {
1975                    if c.is_ascii_uppercase() && i > 0 {
1976                        vec!['_', c.to_ascii_lowercase()]
1977                    } else {
1978                        vec![c.to_ascii_lowercase()]
1979                    }
1980                })
1981                .collect::<String>())
1982            .collect::<Vec<_>>()
1983            .join("_")
1984    }
1985
1986    fn register_implicit(
1987        verb: &str,
1988        scope_snake: &str,
1989        scope_segments: &[String],
1990        path: &str,
1991        config: Value,
1992        out: &mut HashMap<String, (String, Vec<String>, String, Value)>,
1993    ) {
1994        // CCXT's TS `defineRestApiEndpoint` builds the method name by
1995        // splitting the path on EVERY non-alphanumeric character:
1996        //   `path.split(/[^a-zA-Z0-9]/)` → capitalize each part → join.
1997        // So `:`, `{`, `}`, `/`, `.`, `-` are all separators. Examples:
1998        //   `ticker/24hr`                      → `Ticker24hr` → `ticker24hr`
1999        //   `lending/auto-invest`              → `LendingAutoInvest` → `lending_auto_invest`
2000        //   `candles/trade:{tf}:{sym}/hist`    → `CandlesTradeTfSymHist`
2001        //                                      → `candles_trade_tf_sym_hist`
2002        let camel: String = path
2003            .split(|c: char| !c.is_ascii_alphanumeric())
2004            .filter(|s| !s.is_empty())
2005            .map(|seg| {
2006                let mut chars = seg.chars();
2007                match chars.next() {
2008                    None => String::new(),
2009                    Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
2010                }
2011            })
2012            .collect();
2013        // snake_case from camel: insert `_` between [a-z\d] and [A-Z],
2014        // and between [A-Z]+ and [A-Z][a-z]. Mirrors the transpiler's
2015        // toSnakeCase exactly.
2016        let snake = Self::to_snake_case(&camel);
2017        // An empty path (e.g. nado's `archive: { post: { '': 1 } }`, method
2018        // name `archivePost`) must NOT append a trailing `_` — the transpiled
2019        // call site looks up `archive_post`, not `archive_post_`.
2020        let snake_name = if snake.is_empty() {
2021            format!("{scope_snake}_{verb}")
2022        } else {
2023            format!("{scope_snake}_{verb}_{snake}")
2024        };
2025        // CamelCase variant: `<scope_camel><Verb><PathCamel>` — TS often
2026        // constructs method names dynamically as camelCase (e.g. bit2c's
2027        // `"privatePostOrderAddOrder"`). `self.call_method(name, ...)`
2028        // looks up by exact string, so register both keys.
2029        let scope_camel: String = scope_segments.iter()
2030            .enumerate()
2031            .map(|(i, s)| {
2032                if i == 0 {
2033                    s.to_string()
2034                } else {
2035                    let mut chars = s.chars();
2036                    match chars.next() {
2037                        None => String::new(),
2038                        Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
2039                    }
2040                }
2041            })
2042            .collect();
2043        let verb_camel = {
2044            let mut chars = verb.chars();
2045            match chars.next() {
2046                None => String::new(),
2047                Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str().to_lowercase().as_str(),
2048            }
2049        };
2050        let camel_name = format!("{scope_camel}{verb_camel}{camel}");
2051        // Snake-cased from the WHOLE camel name, which is what the transpiler
2052        // does to produce the call site. It usually equals `snake_name` above,
2053        // but the two diverge when a path segment starts with a digit: joining
2054        // pre-snaked parts forces a separator the transpiler never inserts, so
2055        // revolutx's `1.0/public/tickers` registers as
2056        // `public_get_10_public_tickers` while the generated code calls
2057        // `public_get10_public_tickers` (toSnakeCase puts no `_` between a
2058        // digit and the preceding letter). Register both spellings so either
2059        // resolves.
2060        let camel_snake_name = Self::to_snake_case(&camel_name);
2061        let entry = (path.to_string(), scope_segments.to_vec(), verb.to_uppercase(), config);
2062        out.insert(snake_name, entry.clone());
2063        if !out.contains_key(&camel_snake_name) {
2064            out.insert(camel_snake_name, entry.clone());
2065        }
2066        if !out.contains_key(&camel_name) {
2067            out.insert(camel_name, entry);
2068        }
2069    }
2070
2071    fn to_snake_case(s: &str) -> String {
2072        // 1st pass: `[A-Z]+([A-Z][a-z])` → `$1_$2`
2073        let bytes: Vec<char> = s.chars().collect();
2074        let mut out = String::with_capacity(s.len() + 4);
2075        for i in 0..bytes.len() {
2076            let c = bytes[i];
2077            let prev = if i > 0 { Some(bytes[i - 1]) } else { None };
2078            let next = if i + 1 < bytes.len() { Some(bytes[i + 1]) } else { None };
2079            if c.is_ascii_uppercase() {
2080                let prev_lower_or_digit = prev
2081                    .map(|p| p.is_ascii_lowercase() || p.is_ascii_digit())
2082                    .unwrap_or(false);
2083                let prev_upper = prev.map(|p| p.is_ascii_uppercase()).unwrap_or(false);
2084                let next_lower = next.map(|n| n.is_ascii_lowercase()).unwrap_or(false);
2085                if prev_lower_or_digit {
2086                    out.push('_');
2087                } else if prev_upper && next_lower {
2088                    out.push('_');
2089                }
2090            }
2091            out.push(c.to_ascii_lowercase());
2092        }
2093        // Collapse any `__` runs introduced by underscores already in input.
2094        while out.contains("__") {
2095            out = out.replace("__", "_");
2096        }
2097        out.trim_matches('_').to_string()
2098    }
2099
2100    /// Resolves the base URL for a given api scope. Looks up
2101    /// `urls.api.<scope>`; if that's itself a map, prefers `rest`.
2102    fn url_for_scope(&self, scope: &str) -> Option<String> {
2103        let api = crate::get_value(&self.urls, &Value::Str("api".into()));
2104        // Try scoped first (binance-style: urls.api.public, urls.api.private).
2105        let scoped = crate::get_value(&api, &Value::Str(scope.to_string().into()));
2106        let raw = match scoped {
2107            Value::Str(s) => s,
2108            Value::Dict(m) => match m.get("rest").or_else(|| m.get("current")) {
2109                Some(Value::Str(s)) => s.clone(),
2110                _ => return self.fallback_rest_url(&api),
2111            },
2112            _ => return self.fallback_rest_url(&api),
2113        };
2114        Some(self.implode_hostname_typed(&raw))
2115    }
2116
2117    /// Many exchanges (okx, kucoin, bitget, gate, hyperliquid, …) use
2118    /// a single `urls.api.rest` URL for all scopes. Fall back to it
2119    /// when the per-scope lookup misses.
2120    fn fallback_rest_url(&self, api: &Value) -> Option<String> {
2121        let rest = crate::get_value(api, &Value::Str("rest".into()));
2122        if let Value::Str(s) = rest {
2123            return Some(self.implode_hostname_typed(&s));
2124        }
2125        // Last resort: if urls.api itself is a string, use it.
2126        if let Value::Str(s) = api {
2127            return Some(self.implode_hostname_typed(s));
2128        }
2129        None
2130    }
2131
2132    /// Internal typed `{hostname}` substitution.
2133    fn implode_hostname_typed(&self, url: &str) -> String {
2134        let host = match &self.hostname {
2135            Value::Str(s) => s.clone(),
2136            _ => return url.to_string(),
2137        };
2138        url.replace("{hostname}", &host)
2139    }
2140
2141    // Dispatches an implicit API call. Looks the method up in the dispatch
2142    // table (building it on first use) and routes through `request`.
2143    // Public-endpoint request: imploding params into the path/query and
2144    // hitting `fetch`. Private endpoints need per-exchange signing — for
2145    // now we treat anything outside `public` as a stub that returns Null.
2146    fn extract_path_params(&self, path: &str) -> Vec<String> {
2147        let mut out: Vec<String> = vec![];
2148        let mut chars = path.chars().peekable();
2149        while let Some(c) = chars.next() {
2150            if c == '{' {
2151                let mut name = String::new();
2152                while let Some(&nc) = chars.peek() {
2153                    if nc == '}' { chars.next(); break; }
2154                    name.push(nc); chars.next();
2155                }
2156                if !name.is_empty() { out.push(name); }
2157            }
2158        }
2159        out
2160    }
2161}
2162
2163/// Raw digest bytes for a named hash algorithm — includes Keccak-256
2164/// (`keccak`), used by ETH-style signing (hyperliquid, etc.).
2165pub(crate) fn hash_raw(data: &[u8], algo: &str) -> Vec<u8> {
2166    match algo.to_ascii_lowercase().as_str() {
2167        "sha256" => { let mut h = Sha256::new(); h.update(data); h.finalize().to_vec() }
2168        "sha512" => { let mut h = Sha512::new(); h.update(data); h.finalize().to_vec() }
2169        "sha1"   => { let mut h = Sha1::new();   h.update(data); h.finalize().to_vec() }
2170        "md5"    => { let mut h = Md5::new();    h.update(data); h.finalize().to_vec() }
2171        "keccak" | "keccak256" => {
2172            use sha3::{Keccak256, Digest as _};
2173            let mut h = Keccak256::new();
2174            h.update(data);
2175            h.finalize().to_vec()
2176        }
2177        _ => Vec::new(),
2178    }
2179}
2180
2181/// EIP-712 `encode` — produces the `\x19\x01 || domainSeparator ||
2182/// hashStruct(message)` preimage. The caller keccak-hashes this into the
2183/// 32-byte digest that gets ECDSA-signed (hyperliquid, etc.).
2184type Eip712Types = std::collections::BTreeMap<String, Vec<(String, String)>>;
2185
2186/// Strip a trailing `[...]` array suffix from an EIP-712 field type, so
2187/// `Order[]` and `Order` both resolve to the struct name `Order`.
2188fn eip712_base_type(ty: &str) -> &str {
2189    match ty.find('[') { Some(i) => &ty[..i], None => ty }
2190}
2191
2192/// EIP-712 `encodeType`: the primary type's signature followed by every
2193/// referenced struct type, sorted alphabetically (per the spec), so a nested
2194/// `TypedDataSign(Order contents,…)` correctly appends `Order(uint256 salt,…)`.
2195fn eip712_encode_type(primary: &str, types: &Eip712Types) -> String {
2196    fn collect(name: &str, types: &Eip712Types, deps: &mut std::collections::BTreeSet<String>) {
2197        if let Some(fields) = types.get(name) {
2198            for (_, ty) in fields {
2199                let base = eip712_base_type(ty).to_string();
2200                if types.contains_key(&base) && deps.insert(base.clone()) {
2201                    collect(&base, types, deps);
2202                }
2203            }
2204        }
2205    }
2206    let fmt = |name: &str| -> String {
2207        let fields = types.get(name).cloned().unwrap_or_default();
2208        let inner: Vec<String> = fields.iter().map(|(n, t)| format!("{t} {n}")).collect();
2209        format!("{}({})", name, inner.join(","))
2210    };
2211    let mut deps = std::collections::BTreeSet::new();
2212    collect(primary, types, &mut deps);
2213    deps.remove(primary);
2214    let mut out = fmt(primary);
2215    for dep in &deps { out.push_str(&fmt(dep)); } // BTreeSet iterates sorted
2216    out
2217}
2218
2219pub(crate) fn eip712_encode(domain: &Value, types: &Value, message: &Value) -> Vec<u8> {
2220    let dm = match domain { Value::Dict(m) => m, _ => return Vec::new() };
2221    // EIP712Domain field set — canonical order, only the keys present.
2222    let mut domain_fields: Vec<(String, String)> = Vec::new();
2223    for (n, t) in [("name", "string"), ("version", "string"), ("chainId", "uint256"),
2224                   ("verifyingContract", "address"), ("salt", "bytes32")] {
2225        if dm.contains_key(n) { domain_fields.push((n.to_string(), t.to_string())); }
2226    }
2227    // Domain has no nested structs — a flat (empty type-map) hash.
2228    let mut domain_types: Eip712Types = Eip712Types::new();
2229    domain_types.insert("EIP712Domain".to_string(), domain_fields);
2230    let domain_sep = eip712_hash_struct("EIP712Domain", domain, &domain_types);
2231
2232    // Collect all user-defined types (name → fields), excluding EIP712Domain.
2233    let mut type_map: Eip712Types = Eip712Types::new();
2234    if let Value::Dict(m) = types {
2235        for (name, def) in m.iter() {
2236            if name == "EIP712Domain" { continue; }
2237            if let Value::Arr(arr) = def {
2238                let fields: Vec<(String, String)> = arr.iter().filter_map(|it| match it {
2239                    Value::Dict(fm) => Some((
2240                        fm.get("name")?.as_str()?.to_string(),
2241                        fm.get("type")?.as_str()?.to_string(),
2242                    )),
2243                    _ => None,
2244                }).collect();
2245                type_map.insert(name.clone(), fields);
2246            }
2247        }
2248    }
2249    if type_map.is_empty() { return Vec::new(); }
2250    // Primary type = the one not referenced as a field type by any other type
2251    // (the top-level struct). Falls back to the first key.
2252    let referenced: std::collections::HashSet<String> = type_map.values()
2253        .flat_map(|fs| fs.iter().map(|(_, t)| eip712_base_type(t).to_string()))
2254        .collect();
2255    let primary = type_map.keys().find(|k| !referenced.contains(*k)).cloned()
2256        .unwrap_or_else(|| type_map.keys().next().cloned().unwrap_or_default());
2257    let struct_hash = eip712_hash_struct(&primary, message, &type_map);
2258    let mut out = vec![0x19u8, 0x01u8];
2259    out.extend_from_slice(&domain_sep);
2260    out.extend_from_slice(&struct_hash);
2261    out
2262}
2263
2264/// EIP-712 `hashStruct(typeName, data)`: keccak(typeHash ‖ encoded-fields),
2265/// where a field whose type is itself a struct in `types` is hashed recursively.
2266fn eip712_hash_struct(type_name: &str, data: &Value, types: &Eip712Types) -> Vec<u8> {
2267    let type_str = eip712_encode_type(type_name, types);
2268    let mut enc = hash_raw(type_str.as_bytes(), "keccak"); // typeHash (32 bytes)
2269    let dm = match data { Value::Dict(m) => Some(m), _ => None };
2270    let fields = types.get(type_name).cloned().unwrap_or_default();
2271    for (name, ty) in &fields {
2272        let v = dm.and_then(|m| m.get(name)).cloned().unwrap_or(Value::Null);
2273        let base = eip712_base_type(ty);
2274        if types.contains_key(base) {
2275            // Nested struct field — recurse.
2276            enc.extend_from_slice(&eip712_hash_struct(base, &v, types));
2277        } else {
2278            enc.extend_from_slice(&eip712_encode_value(ty, &v));
2279        }
2280    }
2281    hash_raw(&enc, "keccak")
2282}
2283
2284/// Encodes an integer into a 32-byte EIP-712 / ABI word for a `uintN`/`intN`
2285/// type, validating the declared bit width. Fails closed (panics) on a negative
2286/// value in an unsigned type, or any value that overflows the declared width,
2287/// instead of silently truncating to 32 bytes or routing a negative through the
2288/// unsigned branch (review #15). Valid, in-range values encode exactly as
2289/// before (big-endian right-aligned for uint; two's-complement sign-extended
2290/// for int), so signing of well-formed payloads is unchanged.
2291pub(crate) fn eip712_int_word(ty: &str, n: &num_bigint::BigInt) -> [u8; 32] {
2292    use num_bigint::{BigInt, Sign};
2293    let signed = ty.starts_with("int");
2294    let digits = ty.trim_start_matches(if signed { "int" } else { "uint" });
2295    let mut width: usize = if digits.is_empty() { 256 } else { digits.parse().unwrap_or(256) };
2296    if !((8..=256).contains(&width) && width % 8 == 0) { width = 256; }
2297    let mut out = [0u8; 32];
2298    if !signed {
2299        if n.sign() == Sign::Minus {
2300            panic!("eip712/abi: negative value {n} supplied for unsigned type {ty}");
2301        }
2302        let max = (BigInt::from(1) << width) - 1;
2303        if n > &max {
2304            panic!("eip712/abi: value {n} overflows {ty} (max {max})");
2305        }
2306        let (_, be) = n.to_bytes_be();
2307        let take = be.len().min(32);
2308        out[32 - take..].copy_from_slice(&be[be.len() - take..]);
2309    } else {
2310        let min = -(BigInt::from(1) << (width - 1));
2311        let max = (BigInt::from(1) << (width - 1)) - 1;
2312        if n < &min || n > &max {
2313            panic!("eip712/abi: value {n} out of range for {ty} ([{min}, {max}])");
2314        }
2315        if n.sign() == Sign::Minus { out = [0xff; 32]; }
2316        let be = n.to_signed_bytes_be();
2317        let take = be.len().min(32);
2318        out[32 - take..].copy_from_slice(&be[be.len() - take..]);
2319    }
2320    out
2321}
2322
2323fn eip712_encode_value(ty: &str, v: &Value) -> [u8; 32] {
2324    let mut out = [0u8; 32];
2325    if ty == "string" || ty == "bytes" {
2326        out.copy_from_slice(&hash_raw(&value_to_bytes(v), "keccak"));
2327    } else if ty.starts_with("bytes") {
2328        // bytesN — left-aligned.
2329        let b = eip712_bytes(v);
2330        let n = b.len().min(32);
2331        out[..n].copy_from_slice(&b[..n]);
2332    } else if ty == "address" {
2333        // 20-byte address, right-aligned (left-padded with zeros).
2334        let b = eip712_bytes(v);
2335        let take = b.len().min(20);
2336        out[32 - take..].copy_from_slice(&b[b.len() - take..]);
2337    } else if ty == "bool" {
2338        if matches!(v, Value::Bool(true)) { out[31] = 1; }
2339    } else if ty.starts_with("uint") || ty.starts_with("int") {
2340        // uint256 (e.g. polymarket tokenId) exceeds u128 — use BigInt. Signed
2341        // intN uses two's-complement, sign-extended to 32 bytes.
2342        use num_bigint::BigInt;
2343        let n: BigInt = match v {
2344            Value::Int(i)   => BigInt::from(*i),
2345            Value::Float(f) => BigInt::from(*f as i64),
2346            Value::Str(s)   => {
2347                let t = s.trim();
2348                if let Some(h) = t.strip_prefix("0x") {
2349                    BigInt::parse_bytes(h.as_bytes(), 16).unwrap_or_default()
2350                } else {
2351                    BigInt::parse_bytes(t.as_bytes(), 10).unwrap_or_default()
2352                }
2353            }
2354            _ => BigInt::from(0),
2355        };
2356        out = eip712_int_word(ty, &n);
2357    }
2358    out
2359}
2360
2361/// Decode an EIP-712 byte value: a `0x`-hex string or a byte-array Value.
2362fn eip712_bytes(v: &Value) -> Vec<u8> {
2363    match v {
2364        Value::Str(s) => {
2365            let h = s.strip_prefix("0x").unwrap_or(s);
2366            hex::decode(h).unwrap_or_else(|_| s.as_bytes().to_vec())
2367        }
2368        _ => value_to_bytes(v),
2369    }
2370}
2371
2372pub(crate) fn value_to_bytes(v: &Value) -> Vec<u8> {
2373    match v {
2374        Value::Str(s) => s.as_bytes().to_vec(),
2375        Value::Arr(a) => a.iter().filter_map(|x| match x {
2376            Value::Int(n) => Some(*n as u8),
2377            _ => None,
2378        }).collect(),
2379        _ => Vec::new(),
2380    }
2381}
2382
2383pub(crate) fn url_pct(s: &str) -> String {
2384    s.bytes().map(|b| match b {
2385        b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
2386        _ => format!("%{b:02X}"),
2387    }).collect()
2388}
2389
2390/// Pins the `mock_response` contract that `request_typed` implements: the canned
2391/// payload is returned by `fetch_typed` only AFTER the request has been built and
2392/// signed, so `last_request_url` / `_headers` / `_body` still describe the real
2393/// request a static *response* fixture would have sent; and the payload stays set
2394/// until the caller replaces or clears it, so one fixture can serve the several
2395/// `fetch_typed` calls a single paginating `fetchX` issues.
2396
2397/// Pins `method_name_to_snake_case` — the transform that decides whether a
2398/// paginated `this[method](...)` re-entry lands on a `call_dynamic` arm — against
2399/// the two implementations it must agree with: the transpiler's `toSnakeCase`
2400/// (`build/rustTranspiler.ts`, which names the arms) and `Exchange::to_snake_case`
2401/// (which names the implicit-API entries the `_` arm falls through to).
2402/// Requested in review on #30385.
2403#[cfg(test)]
2404mod method_name_snake_case_tests {
2405    use super::{method_name_to_snake_case, Exchange};
2406    use crate::Value;
2407
2408    fn snake(name: &str) -> String {
2409        method_name_to_snake_case(&Value::Str(name.to_string().into()))
2410    }
2411
2412    // The four names the review called out, plus the digit/acronym shapes that
2413    // are the only places the three transforms could plausibly diverge.
2414    #[test]
2415    fn matches_the_transpiler_dispatch_arm_names() {
2416        // unified methods re-entered by fetchPaginatedCall* — these must hit an arm
2417        assert_eq!(snake("fetchTransfers"), "fetch_transfers");
2418        assert_eq!(snake("fetchOHLCV"), "fetch_ohlcv");                 // trailing acronym
2419        assert_eq!(snake("fetchOpenOrdersWs"), "fetch_open_orders_ws");
2420        assert_eq!(snake("fetchL2OrderBook"), "fetch_l2_order_book");   // letter+digit token
2421        assert_eq!(snake("getLeverageTiersPaginated"), "get_leverage_tiers_paginated");
2422        // implicit endpoints re-entered by fetchWebEndpoint — these must hit the
2423        // `_` arm's implicit_api lookup, which is keyed by to_snake_case
2424        assert_eq!(snake("publicGetTicker24hr"), "public_get_ticker24hr"); // NO `_` before a digit
2425        assert_eq!(snake("webExchangeGetV3Assets"), "web_exchange_get_v3_assets");
2426        assert_eq!(snake("webApiGetAjaxCoinCoinInfo"), "web_api_get_ajax_coin_coin_info");
2427        // acronym runs: `[A-Z]+[A-Z][a-z]` splits before the last capital only
2428        assert_eq!(snake("parseHTTPResponse"), "parse_http_response");
2429        assert_eq!(snake("fetchOHLCVWs"), "fetch_ohlcv_ws");
2430        // already-snake and single-token names are pass-through
2431        assert_eq!(snake("fetch"), "fetch");
2432        assert_eq!(snake("fetch_transfers"), "fetch_transfers");
2433    }
2434
2435    // `method_name_to_snake_case` and `Exchange::to_snake_case` must produce the
2436    // SAME key, or a dynamic name would snake to something the implicit-api map
2437    // does not hold. Differential over the shapes above; the full 11k-name sweep
2438    // over every ts/src method + abstract endpoint also reports zero divergence.
2439    #[test]
2440    fn agrees_with_exchange_to_snake_case() {
2441        for name in [
2442            "fetchTransfers", "fetchOHLCV", "fetchOpenOrdersWs", "publicGetTicker24hr",
2443            "fetchL2OrderBook", "webExchangeGetV3Assets", "webApiGetAjaxCoinCoinInfo",
2444            "parseHTTPResponse", "fetchOHLCVWs", "privatePostSPEIWithdrawal",
2445            "sapiV3GetAsset", "fapiPublicGetTicker24hr", "publicGet10PublicTickers",
2446            "fetch", "fetchPositionsRisk", "createOrderWs", "fetchMyLiquidations",
2447        ] {
2448            assert_eq!(
2449                snake(name),
2450                Exchange::to_snake_case(name),
2451                "method_name_to_snake_case and Exchange::to_snake_case diverge on {name}",
2452            );
2453        }
2454    }
2455
2456    // A non-string / empty dynamic name used to snake to "" and then resolve to
2457    // Value::Null — a silent empty page. It must be loud instead.
2458    #[test]
2459    #[should_panic(expected = "NotSupported")]
2460    fn non_string_method_name_is_loud() {
2461        let _ = method_name_to_snake_case(&Value::Int(7));
2462    }
2463
2464    #[test]
2465    #[should_panic(expected = "NotSupported")]
2466    fn empty_method_name_is_loud() {
2467        let _ = method_name_to_snake_case(&Value::Str(String::new().into()));
2468    }
2469}
2470
2471#[cfg(test)]
2472mod eip712_int_tests {
2473    use super::eip712_int_word;
2474    use num_bigint::BigInt;
2475
2476    #[test]
2477    fn uint8_max_ok_and_int8_bounds_ok() {
2478        assert_eq!(eip712_int_word("uint8", &BigInt::from(255))[31], 255);
2479        let _ = eip712_int_word("int8", &BigInt::from(127));
2480        let _ = eip712_int_word("int8", &BigInt::from(-128));
2481    }
2482
2483    #[test]
2484    fn i64_u64_boundaries_ok() {
2485        let _ = eip712_int_word("int64", &BigInt::from(i64::MAX));
2486        let _ = eip712_int_word("int64", &BigInt::from(i64::MIN));
2487        let _ = eip712_int_word("uint64", &BigInt::from(u64::MAX));
2488    }
2489
2490    // u64::MAX + 1 (2^64) must fit a uint256 exactly: 0x01 followed by 8 zero
2491    // bytes, right-aligned → byte index 23.
2492    #[test]
2493    fn u64_plus_one_preserved_in_uint256() {
2494        let n = BigInt::from(u64::MAX) + 1;
2495        assert_eq!(eip712_int_word("uint256", &n)[23], 1);
2496    }
2497
2498    #[test]
2499    fn negative_int_is_twos_complement() {
2500        assert_eq!(eip712_int_word("int256", &BigInt::from(-1)), [0xff; 32]);
2501    }
2502
2503    #[test]
2504    #[should_panic(expected = "overflows")]
2505    fn uint8_overflow_rejected() { let _ = eip712_int_word("uint8", &BigInt::from(256)); }
2506
2507    #[test]
2508    #[should_panic(expected = "negative")]
2509    fn uint_negative_rejected() { let _ = eip712_int_word("uint256", &BigInt::from(-1)); }
2510
2511    #[test]
2512    #[should_panic(expected = "out of range")]
2513    fn int8_overflow_rejected() { let _ = eip712_int_word("int8", &BigInt::from(128)); }
2514
2515    #[test]
2516    #[should_panic(expected = "overflows")]
2517    fn uint64_plus_one_rejected() {
2518        let _ = eip712_int_word("uint64", &(BigInt::from(u64::MAX) + 1));
2519    }
2520}
2521
2522#[cfg(test)]
2523mod throttle_tests {
2524    use super::Exchange;
2525    use crate::Value;
2526
2527    #[test]
2528    fn implicit_api_retains_endpoint_cost_config() {
2529        let mut by_limit = crate::value::HashMap::new();
2530        by_limit.insert("cost".to_string(), Value::Int(2));
2531        by_limit.insert("byLimit".to_string(), Value::List(vec![
2532            Value::List(vec![Value::Int(100), Value::Int(5)]),
2533        ]));
2534        let mut endpoints = crate::value::HashMap::new();
2535        endpoints.insert("ticker".to_string(), Value::Float(0.1));
2536        endpoints.insert("depth".to_string(), Value::Map(by_limit.clone()));
2537        let mut verbs = crate::value::HashMap::new();
2538        verbs.insert("get".to_string(), Value::Map(endpoints));
2539        let mut api = crate::value::HashMap::new();
2540        api.insert("public".to_string(), Value::Map(verbs));
2541        let mut exchange = Exchange::new(None);
2542        exchange.api = Value::Map(api);
2543        exchange.build_implicit_api();
2544        let ticker_config = &exchange.internals.implicit_api["public_get_ticker"].3;
2545        assert_eq!(
2546            crate::get_value(ticker_config, &Value::Str("cost".into())),
2547            Value::Float(0.1),
2548            "numeric endpoint costs must be normalized to a config object"
2549        );
2550        let depth_config = &exchange.internals.implicit_api["public_get_depth"].3;
2551        assert_eq!(depth_config, &Value::Map(by_limit), "object endpoint config must be retained");
2552    }
2553
2554    // The leaky-bucket limiter must space requests by ~rateLimit ms (real time).
2555    #[tokio::test]
2556    async fn spaces_requests_by_rate_limit() {
2557        let mut ex = Exchange::new(None);
2558        ex.enableRateLimit = Value::Bool(true);
2559        ex.rateLimit = Value::Int(15); // 15 ms per token
2560        let start = std::time::Instant::now();
2561        for _ in 0..5 { ex.throttle(&[]).await; }
2562        let elapsed = start.elapsed().as_millis();
2563        // 1st immediate, next 4 each wait ~15ms → ≥ ~45ms (generous lower bound).
2564        assert!(elapsed >= 45, "throttle did not space requests: {elapsed}ms");
2565    }
2566
2567    // Disabled rate limiting must not sleep at all.
2568    #[tokio::test]
2569    async fn disabled_is_noop() {
2570        let mut ex = Exchange::new(None);
2571        ex.enableRateLimit = Value::Bool(false);
2572        ex.rateLimit = Value::Int(1000);
2573        let start = std::time::Instant::now();
2574        for _ in 0..5 { ex.throttle(&[]).await; }
2575        assert!(start.elapsed().as_millis() < 50, "disabled throttle slept");
2576    }
2577}
2578
2579#[cfg(all(test, feature = "engine"))]
2580mod cow_alias_tests {
2581    use super::Exchange;
2582    use crate::Value;
2583    use crate::runtime::get_array_length;
2584
2585    // convertOHLCVToTradingView does `result[key].push(...)` on an extracted
2586    // local — a COW clone in Rust. Without the write-back the result columns
2587    // stay empty. Assert the data survives (review P0-C).
2588    #[test]
2589    fn convert_ohlcv_to_trading_view_preserves_pushes() {
2590        use crate::exchange_generated::ExchangeBase;
2591        let ex = super::BaseCore::new(Exchange::new(None));
2592        let row = Value::List(vec![
2593            Value::Int(1_700_000_000_000), Value::Int(1), Value::Int(2),
2594            Value::Int(0), Value::Int(1), Value::Int(10),
2595        ]);
2596        let ohlcvs = Value::List(vec![row.clone(), row]);
2597        let r = ex.convert_ohlcv_to_trading_view(ohlcvs, &[]);
2598        for key in ["t", "o", "h", "l", "c", "v"] {
2599            let col = crate::get_value(&r, &Value::Str(key.to_string().into()));
2600            assert_eq!(get_array_length(&col), Value::Int(2),
2601                "result['{key}'] lost its pushes — COW write-back failed");
2602        }
2603    }
2604}
2605
2606#[cfg(test)]
2607mod http_error_tests {
2608    use super::{BaseCore, DerivedExchange, Exchange, ExchangeRuntime};
2609    use crate::Value;
2610    use futures::FutureExt;
2611    use std::io::{Read, Write};
2612
2613    // Answers one request on a local port with the given status line and body.
2614    fn serve_once(status_line: &'static str, body: &'static str) -> String {
2615        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2616        let url = format!("http://{}/", listener.local_addr().unwrap());
2617        std::thread::spawn(move || {
2618            let (mut stream, _) = listener.accept().unwrap();
2619            let mut request = [0u8; 4096];
2620            let _ = stream.read(&mut request);
2621            let response = format!(
2622                "HTTP/1.1 {status_line}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
2623                body.len(),
2624            );
2625            stream.write_all(response.as_bytes()).unwrap();
2626        });
2627        url
2628    }
2629
2630    // A venue that reports failures inside a 200 body, the way okx does.
2631    struct EnvelopeCore {
2632        exchange: Exchange,
2633    }
2634    impl std::ops::Deref for EnvelopeCore {
2635        type Target = Exchange;
2636        fn deref(&self) -> &Exchange { &self.exchange }
2637    }
2638    impl std::ops::DerefMut for EnvelopeCore {
2639        fn deref_mut(&mut self) -> &mut Exchange { &mut self.exchange }
2640    }
2641    impl DerivedExchange for EnvelopeCore {
2642        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 {
2643            let code = crate::get_value(&response, &Value::Str("code".into()));
2644            if !matches!(code, Value::Null) && code != Value::Str("0".into()) {
2645                panic!("{}", crate::exchange_errors::create_error("InsufficientFunds", "code 51008"));
2646            }
2647            Value::Null
2648        }
2649    }
2650    impl crate::exchange_generated::ExchangeBase for EnvelopeCore {
2651        fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<Value>)
2652            -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>>
2653        {
2654            Box::pin(async move { self.call_dynamic_base(method, args).await })
2655        }
2656    }
2657
2658    async fn fetch_error<C: ExchangeRuntime + Send>(core: &mut C, url: String) -> String {
2659        let outcome = std::panic::AssertUnwindSafe(core.fetch(Value::Str(url.into()), &[])).catch_unwind().await;
2660        match outcome {
2661            Ok(value) => format!("no error, returned {value:?}"),
2662            Err(payload) => payload.downcast_ref::<String>().cloned().unwrap_or_default(),
2663        }
2664    }
2665
2666    #[tokio::test]
2667    async fn an_error_in_a_2xx_body_reaches_handle_errors() {
2668        let url = serve_once("200 OK", r#"{"code":"51008","msg":"Insufficient balance"}"#);
2669        let mut core = EnvelopeCore { exchange: Exchange::new(None) };
2670        let error = fetch_error(&mut core, url).await;
2671        assert!(error.contains("InsufficientFunds"), "{error}");
2672    }
2673
2674    #[tokio::test]
2675    async fn a_status_in_http_exceptions_raises_its_class() {
2676        let url = serve_once("401 Unauthorized", "{}");
2677        let mut core = BaseCore::new(Exchange::new(None));
2678        let error = fetch_error(&mut core, url).await;
2679        assert!(error.contains("AuthenticationError"), "{error}");
2680    }
2681
2682    #[tokio::test]
2683    async fn a_status_outside_http_exceptions_still_fails() {
2684        let url = serve_once("402 Payment Required", "{}");
2685        let mut core = BaseCore::new(Exchange::new(None));
2686        let error = fetch_error(&mut core, url).await;
2687        assert!(error.contains("ExchangeError"), "{error}");
2688    }
2689}