Skip to main content

ccxt_base/
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    // ── prediction-tier parsers (overridden by prediction venues) ────────
143    fn parse_prediction_trade(&self, _trade: Value, _market: Value) -> Value { Value::Null }
144    fn parse_prediction_order(&self, _order: Value, _market: Value) -> Value { Value::Null }
145    fn parse_prediction_position(&self, _position: Value, _market: Value) -> Value { Value::Null }
146    // ── signers / error handlers ─────────────────────────────────────────
147    /// `nonce()` — the request timestamp. The base default is `seconds()`, but
148    /// 47 venues override it (binance: `milliseconds() - timeDifference`), and
149    /// without a slot here the override is invisible to any caller that reaches
150    /// the base through a trait method — notably a pro Core, which finds
151    /// `ExchangeBase::nonce` at deref step 0 and never looks at the REST
152    /// parent's inherent one. Binance spot then signs its ws-api subscribe with
153    /// a seconds timestamp and the venue answers -1130.
154    fn nonce(&self) -> Value { Value::Null }
155    fn sign(&self, _path: Value, _api: Value, _method: Value, _params: Value, _headers: Value, _body: Value) -> Value { Value::Null }
156    fn handle_errors(&self, _code: Value, _reason: Value, _url: Value, _method: Value, _headers: Value, _body: Value, _response: Value, _request_headers: Value, _request_body: Value) -> Value { Value::Null }
157}
158
159// `Internals` no longer holds raw pointers, so `Send`/`Sync` are auto-derived
160// (its fields — `reqwest::Client`, `Arc<dyn Fn + Send + Sync>`,
161// `Arc<tokio::Mutex<_>>`, maps, `Vec<String>` — are all thread-safe). No manual
162// `unsafe impl` and no `PhantomPinned` are needed now that dispatch is static
163// (review #1: thread safety is compiler-proven, not asserted).
164
165// A cloned Exchange gets a fresh `Internals` — the http client and dispatch
166// state are per-instance and must not be shared.
167// Test-only callers (`clone_self`) only read `Value` fields off the copy.
168impl Clone for Internals {
169    fn clone(&self) -> Self { Internals::default() }
170}
171
172impl Default for Internals {
173    fn default() -> Self {
174        Self {
175            http_client:      None,
176            describe_cb:      None,
177            last_rest_ts:     0,
178            headers:          HashMap::new(),
179            throttle:         std::sync::Arc::new(tokio::sync::Mutex::new((0.0, 0))),
180            implicit_api:     HashMap::new(),
181            dispatch_stack:      Vec::new(),
182            dynamic_dispatch_miss: None,
183        }
184    }
185}
186
187// ── Exchange struct ─────────────────────────────────────────────────────────
188//
189// Every transpiler-visible field is `Value`. Both camelCase and snake_case
190// names appear because the TS source uses both interchangeably.
191
192#[derive(Clone)]
193pub struct Exchange {
194    // identity
195    pub id:          Value,
196    pub name:        Value,
197    pub countries:   Value,
198    pub version:     Value,
199    pub alias:       Value,
200    pub certified:   Value,
201    pub pro:         Value,
202    pub hostname:    Value,
203
204    // credentials
205    pub apiKey:        Value,
206    pub secret:        Value,
207    pub password:      Value,
208    pub uid:           Value,
209    pub walletAddress: Value,
210    pub privateKey:    Value,
211    pub twofa:         Value,
212    pub token:         Value,
213    pub login:         Value,
214    pub accountId:     Value,
215    pub requiredCredentials: Value,
216
217    // rate limiting / connection
218    pub timeout:                Value,
219    pub rateLimit:              Value,
220    pub enableRateLimit:        Value,
221    pub rateLimiterAlgorithm:   Value,
222    pub rollingWindowSize:      Value,
223    pub tokenBucket:            Value,
224    /// The raw constructor config, kept so `initialize_properties` can merge it
225    /// over `describe()` the way Go's `InitParent` does
226    /// (`deepExtend(describe, userConfig)`) instead of relying on per-field
227    /// precedence guards in each Core's generated `init()`.
228    pub userConfig:             Value,
229    pub verbose:                Value,
230    pub isSandboxModeEnabled:   Value,
231
232    // proxy
233    pub proxy:               Value,
234    pub proxyUrl:            Value,
235    pub proxy_url:           Value,
236    pub proxyUrlCallback:    Value,
237    pub proxy_url_callback:  Value,
238    pub httpProxy:           Value,
239    pub http_proxy:          Value,
240    pub httpProxyCallback:   Value,
241    pub http_proxy_callback: Value,
242    pub httpsProxy:          Value,
243    pub https_proxy:         Value,
244    pub httpsProxyCallback:  Value,
245    pub https_proxy_callback: Value,
246    pub socksProxy:          Value,
247    pub socks_proxy:         Value,
248    pub socksProxyCallback:  Value,
249    pub socks_proxy_callback: Value,
250    pub wsProxy:             Value,
251    pub ws_proxy:            Value,
252    pub wssProxy:            Value,
253    pub wss_proxy:           Value,
254    pub wsSocksProxy:        Value,
255    pub ws_socks_proxy:      Value,
256
257    // market data caches
258    pub markets:           Value,
259    pub markets_by_id:     Value,
260    pub currencies:        Value,
261    pub currencies_by_id:  Value,
262    pub commonCurrencies:  Value,
263    pub baseCurrencies:    Value,
264    pub quoteCurrencies:   Value,
265    pub symbols:           Value,
266    pub ids:               Value,
267    pub codes:             Value,
268    pub timeframes:        Value,
269    pub precision:         Value,
270    pub limits:            Value,
271    pub fees:              Value,
272    pub features:          Value,
273    pub has:               Value,
274    pub exceptions:        Value,
275    pub urls:              Value,
276    pub api:               Value,
277    pub options:           Value,
278    pub headers:           Value,
279    pub accounts:          Value,
280    pub accountsById:      Value,
281
282    // runtime state
283    pub orderbooks:        Value,
284    pub orders:            Value,
285    pub trades:            Value,
286    pub myTrades:          Value,
287    pub positions:         Value,
288    // WS state — mirrors `ts/src/base/Exchange.ts` `newUpdates: boolean = true`.
289    // Per-exchange WS code reads `self.newUpdates` to decide whether to call
290    // `cache.getLimit(...)` (return only what's new since the last call) or
291    // emit the whole rolling buffer.
292    pub newUpdates:        Value,
293    pub tickers:           Value,
294    pub bidsasks:          Value,
295    pub ohlcvs:            Value,
296    pub clients:           Value,
297    pub balance:           Value,
298    pub liquidations:      Value,
299    pub myLiquidations:    Value,
300    pub fundingRates:      Value,
301    pub triggerOrders:     Value,
302    pub transactions:      Value,
303    pub reloadingMarkets:  Value,
304    pub marketsLoading:    Value,
305
306    // last-* tracking
307    pub last_request_url:        Value,
308    pub last_request_headers:    Value,
309    pub last_request_body:       Value,
310    pub last_http_response:      Value,
311    pub last_response_headers:   Value,
312    /// Canned HTTP response for static *response* tests — when set,
313    /// `fetch_typed` returns it without hitting the network so the
314    /// exchange's parser runs against fixture data. Mirrors Go's
315    /// `MockResponse` field. Reused for all requests in a fixture; the test
316    /// dispatcher replaces or clears it before the next REST dispatch.
317    pub mock_response:           Value,
318    /// Response-test mock keyed by url fragment, for methods that call several
319    /// endpoints: one shared body cannot cover two endpoints of different
320    /// declared shapes. Consulted before `mock_response`.
321    pub mock_response_by_url:    Value,
322    pub last_json_response:      Value,
323    pub lastRestRequestTimestamp: Value,
324    /// Rolling cache of recent fetch results, capped at
325    /// `fetchHistoryCacheSize`. Mirrors `Exchange.ts` `fetchHistoryCache`
326    /// / `fetchHistoryCacheSize` (hand-written, above the transpile marker).
327    pub fetchHistoryCache:      Value,
328    pub fetchHistoryCacheSize:  Value,
329
330    // misc
331    pub paddingMode:               Value,
332    pub precisionMode:             Value,
333    pub substituteCommonCurrencyCodes: Value,
334    pub reduceFees:                Value,
335    pub minFundingAddressLength:   Value,
336    pub MAX_VALUE:                 Value,
337    pub returnResponseHeaders:     Value,
338    pub httpExceptions:            Value,
339    pub status:                    Value,
340
341    // user-agent / fetch behavior
342    pub userAgent:                 Value,
343    pub user_agent:                Value,
344    pub userAgents:                Value,
345
346    // describe() output (legacy)
347    pub describe_data:             Value,
348    pub derived_describe:          Option<DescribeCallback>,
349
350    // private runtime state (typed)
351    pub internals: Internals,
352}
353
354impl Default for Exchange {
355    fn default() -> Self { Self::new(None) }
356}
357
358// ── base-class describe() defaults (Exchange.ts) ────────────────────────────
359// Mirrors the constant sub-objects returned by the base `describe()` so a
360// plain `Exchange` carries the same shape as CCXT (verified by the
361// transpiled `test.afterConstructor` base test).
362
363fn vmap(pairs: &[(&str, Value)]) -> Value {
364    let mut m = HashMap::new();
365    for (k, v) in pairs { m.insert((*k).to_string(), v.clone()); }
366    Value::Map(m)
367}
368
369fn min_max() -> Value { vmap(&[("min", Value::Null), ("max", Value::Null)]) }
370
371fn base_limits() -> Value {
372    vmap(&[
373        ("leverage", min_max()),
374        ("amount",   min_max()),
375        ("price",    min_max()),
376        ("cost",     min_max()),
377    ])
378}
379
380fn base_fees() -> Value {
381    vmap(&[
382        ("trading", vmap(&[
383            ("tierBased",  Value::Null),
384            ("percentage", Value::Null),
385            ("taker",      Value::Null),
386            ("maker",      Value::Null),
387        ])),
388        ("funding", vmap(&[
389            ("tierBased",  Value::Null),
390            ("percentage", Value::Null),
391            ("withdraw",   Value::Map(HashMap::new())),
392            ("deposit",    Value::Map(HashMap::new())),
393        ])),
394    ])
395}
396
397fn base_urls() -> Value {
398    vmap(&[
399        ("logo", Value::Null), ("api", Value::Null), ("test", Value::Null),
400        ("www", Value::Null), ("doc", Value::Null), ("api_management", Value::Null),
401        ("fees", Value::Null), ("referral", Value::Null),
402    ])
403}
404
405fn base_status() -> Value {
406    vmap(&[
407        ("status",  Value::Str("ok".into())),
408        ("updated", Value::Null),
409        ("eta",     Value::Null),
410        ("url",     Value::Null),
411        ("info",    Value::Null),
412    ])
413}
414
415/// `deepExtend(a, b)` — recursive merge; `b` wins on scalar conflicts,
416/// nested maps merge key-by-key.
417fn deep_merge(a: &Value, b: &Value) -> Value {
418    match (a, b) {
419        (Value::Dict(am), Value::Dict(bm)) => {
420            let mut out = (**am).clone();
421            for (k, bv) in bm.iter() {
422                let merged = match out.get(k) {
423                    Some(av) => deep_merge(av, bv),
424                    None     => bv.clone(),
425                };
426                out.insert(k.clone(), merged);
427            }
428            Value::Map(out)
429        }
430        _ => b.clone(),
431    }
432}
433
434fn base_http_exceptions() -> Value {
435    let mut m = HashMap::new();
436    for (code, class) in [
437        ("422", "ExchangeError"),         ("418", "DDoSProtection"),
438        ("429", "RateLimitExceeded"),     ("404", "ExchangeNotAvailable"),
439        ("409", "ExchangeNotAvailable"),  ("410", "ExchangeNotAvailable"),
440        ("451", "ExchangeNotAvailable"),  ("500", "ExchangeNotAvailable"),
441        ("501", "ExchangeNotAvailable"),  ("502", "ExchangeNotAvailable"),
442        ("520", "ExchangeNotAvailable"),  ("521", "ExchangeNotAvailable"),
443        ("522", "ExchangeNotAvailable"),  ("525", "ExchangeNotAvailable"),
444        ("526", "ExchangeNotAvailable"),  ("400", "ExchangeNotAvailable"),
445        ("403", "ExchangeNotAvailable"),  ("405", "ExchangeNotAvailable"),
446        ("503", "ExchangeNotAvailable"),  ("530", "ExchangeNotAvailable"),
447        ("408", "RequestTimeout"),        ("504", "RequestTimeout"),
448        ("401", "AuthenticationError"),   ("407", "AuthenticationError"),
449        ("511", "AuthenticationError"),
450    ] {
451        m.insert(code.to_string(), Value::Str(class.to_string().into()));
452    }
453    Value::Map(m)
454}
455
456impl Exchange {
457    pub fn new(config: Option<Value>) -> Self {
458        let mut ex = Exchange {
459            // Base-class id (Exchange.ts describe()). A derived exchange's
460            // describe() overrides this with its own id.
461            id:        Value::Str("Exchange".into()),
462            name:      Value::Null,
463            countries: Value::Null,
464            version:   Value::Null,
465            alias:     Value::Bool(false),
466            certified: Value::Bool(false),
467            pro:       Value::Bool(false),
468            hostname:  Value::Null,
469
470            apiKey:        Value::Null,
471            secret:        Value::Null,
472            password:      Value::Null,
473            uid:           Value::Null,
474            walletAddress: Value::Null,
475            privateKey:    Value::Null,
476            twofa:         Value::Null,
477            token:         Value::Null,
478            login:         Value::Null,
479            accountId:     Value::Null,
480            // Base-class default (Exchange.ts). Kept when an exchange's
481            // describe() doesn't override it — so `checkRequiredCredentials`
482            // still works even though `super.describe()` is stubbed.
483            requiredCredentials: {
484                let mut m = HashMap::new();
485                m.insert("apiKey".to_string(),        Value::Bool(true));
486                m.insert("secret".to_string(),        Value::Bool(true));
487                m.insert("uid".to_string(),           Value::Bool(false));
488                m.insert("accountId".to_string(),     Value::Bool(false));
489                m.insert("login".to_string(),         Value::Bool(false));
490                m.insert("password".to_string(),      Value::Bool(false));
491                m.insert("twofa".to_string(),         Value::Bool(false));
492                m.insert("privateKey".to_string(),    Value::Bool(false));
493                m.insert("walletAddress".to_string(), Value::Bool(false));
494                m.insert("token".to_string(),         Value::Bool(false));
495                Value::Map(m)
496            },
497
498            timeout:              Value::Int(10_000),
499            rateLimit:            Value::Int(2_000),
500            enableRateLimit:      Value::Bool(true),
501            rateLimiterAlgorithm: Value::Str("leakyBucket".into()),
502            rollingWindowSize:    Value::Int(60_000),
503            tokenBucket:          Value::Map(HashMap::new()),
504            userConfig:           Value::Null,
505            verbose:              Value::Bool(false),
506            isSandboxModeEnabled: Value::Bool(false),
507
508            proxy:               Value::Null,
509            proxyUrl:            Value::Null,
510            proxy_url:           Value::Null,
511            proxyUrlCallback:    Value::Null,
512            proxy_url_callback:  Value::Null,
513            httpProxy:           Value::Null,
514            http_proxy:          Value::Null,
515            httpProxyCallback:   Value::Null,
516            http_proxy_callback: Value::Null,
517            httpsProxy:          Value::Null,
518            https_proxy:         Value::Null,
519            httpsProxyCallback:  Value::Null,
520            https_proxy_callback: Value::Null,
521            socksProxy:          Value::Null,
522            socks_proxy:         Value::Null,
523            socksProxyCallback:  Value::Null,
524            socks_proxy_callback: Value::Null,
525            wsProxy:             Value::Null,
526            ws_proxy:            Value::Null,
527            wssProxy:            Value::Null,
528            wss_proxy:           Value::Null,
529            wsSocksProxy:        Value::Null,
530            ws_socks_proxy:      Value::Null,
531
532            markets:           Value::Null,
533            markets_by_id:     Value::Null,
534            currencies:        Value::Map(HashMap::new()),
535            currencies_by_id:  Value::Null,
536            commonCurrencies:  {
537                let mut m = HashMap::new();
538                m.insert("XBT".to_string(),   Value::Str("BTC".into()));
539                m.insert("BCHSV".to_string(), Value::Str("BSV".into()));
540                Value::Map(m)
541            },
542            baseCurrencies:    Value::Null,
543            quoteCurrencies:   Value::Null,
544            symbols:           Value::Null,
545            ids:               Value::Null,
546            codes:             Value::Null,
547            timeframes:        Value::Null,
548            precision:         Value::Null,
549            limits:            base_limits(),
550            fees:              base_fees(),
551            features:          Value::Null,
552            has:               Value::Map(HashMap::new()),
553            exceptions:        Value::Null,
554            urls:              base_urls(),
555            api:               Value::Null,
556            // Base-class default `options` (Exchange.ts describe()). Kept
557            // when an exchange's describe() omits it — `super.describe()`
558            // is stubbed, so it wouldn't otherwise flow through.
559            options: {
560                let mk = |p: &str, s: &str, d: &str| {
561                    let mut e = HashMap::new();
562                    e.insert("primary".to_string(),   Value::Str(p.to_string().into()));
563                    e.insert("secondary".to_string(), Value::Str(s.to_string().into()));
564                    e.insert("default".to_string(),   Value::Str(d.to_string().into()));
565                    Value::Map(e)
566                };
567                let mut repl = HashMap::new();
568                repl.insert("ETH".to_string(), mk("ETH", "ERC20", "secondary"));
569                repl.insert("CRO".to_string(), mk("CRONOS", "CRC20", "secondary"));
570                repl.insert("TRX".to_string(), mk("TRX", "TRC20", "secondary"));
571                repl.insert("BTC".to_string(), mk("BTC", "BRC20", "primary"));
572                let mut o = HashMap::new();
573                o.insert("defaultNetworkCodeReplacements".to_string(), Value::Map(repl));
574                Value::Map(o)
575            },
576            headers:           Value::Map(HashMap::new()),
577            accounts:          Value::Null,
578            accountsById:      Value::Null,
579
580            orderbooks:    Value::Map(HashMap::new()),
581            orders:        Value::Null,
582            trades:        Value::Map(HashMap::new()),
583            myTrades:      Value::Null,
584            positions:     Value::Null,
585            newUpdates:    Value::Bool(true),
586            tickers:       Value::Map(HashMap::new()),
587            bidsasks:      Value::Map(HashMap::new()),
588            ohlcvs:        Value::Map(HashMap::new()),
589            clients:       Value::Map(HashMap::new()),
590            balance:       Value::Map(HashMap::new()),
591            liquidations:  Value::Null,
592            myLiquidations: Value::Null,
593            fundingRates:  Value::Null,
594            triggerOrders: Value::Null,
595            transactions:  Value::Map(HashMap::new()),
596            reloadingMarkets: Value::Null,
597            marketsLoading:   Value::Null,
598
599            last_request_url:           Value::Null,
600            last_request_headers:       Value::Null,
601            last_request_body:          Value::Null,
602            last_http_response:         Value::Null,
603            last_response_headers:      Value::Null,
604            mock_response:              Value::Null,
605            mock_response_by_url:       Value::Null,
606            last_json_response:         Value::Null,
607            lastRestRequestTimestamp:   Value::Int(0),
608            fetchHistoryCache:          Value::List(vec![]),
609            fetchHistoryCacheSize:      Value::Int(0),
610
611            paddingMode:                       Value::Null,
612            precisionMode:                     Value::Null,
613            substituteCommonCurrencyCodes:     Value::Bool(true),
614            reduceFees:                        Value::Bool(true),
615            minFundingAddressLength:           Value::Int(1),
616            MAX_VALUE:                         Value::Float(f64::MAX),
617            returnResponseHeaders:             Value::Bool(false),
618            httpExceptions:                    base_http_exceptions(),
619            status:                            base_status(),
620
621            userAgent:   Value::Null,
622            user_agent:  Value::Null,
623            userAgents:  {
624                let mut m = HashMap::new();
625                m.insert("chrome".to_string(), Value::Str("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36".into()));
626                m.insert("chrome39".to_string(), Value::Str("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36".into()));
627                m.insert("chrome100".to_string(), Value::Str("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36".into()));
628                Value::Map(m)
629            },
630
631            describe_data:     Value::Null,
632            derived_describe:  None,
633
634            internals: Internals::default(),
635        };
636        if let Some(cfg) = config {
637            ex.userConfig = cfg.clone();
638            ex.apply_config(&cfg);
639        }
640        // NOTE: `afterConstruct()` is deliberately NOT run here. In TS the
641        // constructor applies describe() and only then calls afterConstruct,
642        // so the bits it derives (networksById, the features table, the
643        // tokenBucket, the sandbox swap) see the venue's own values. Running
644        // it at this point — before the derived Core's describe() has been
645        // applied — is what made every venue throttle at the base 2000ms and
646        // forced a string of compensations in the generated `init()`. Each
647        // Core's `init()` now calls it last; a bare `Exchange` with no derived
648        // Core (base unit tests, `BaseCore`) calls `after_construct` itself.
649        ex
650    }
651
652    /// Apply a merged `describe()` + constructor-config map onto the typed
653    /// fields. The Rust counterpart of Go's `initializeProperties`
654    /// (`go/v4/exchange_options.go`) and of the TS constructor's
655    /// `deepExtend(this, describe(), userConfig)` — which Rust cannot do
656    /// directly because `Exchange` is a struct, not a dynamic object.
657    ///
658    /// Each Core's generated `init()` used to inline ~84 lines of this, which
659    /// is why every field carried its own precedence guard: config was applied
660    /// in `new()` BEFORE `describe()` ran, so `describe()` had to be stopped
661    /// from clobbering it. Here the config is merged over `describe()` first
662    /// (Go's `deepExtend(describe, userConfig)`), so last-write-wins is the
663    /// precedence rule and no guards are needed.
664    ///
665    /// Absent keys leave the base default in place — the equivalent of Go's
666    /// `SafeString(props, key, default)`.
667    pub fn initialize_properties(&mut self, described: Value) {
668        let props = if matches!(self.userConfig, Value::Null) {
669            described
670        } else {
671            crate::runtime::deep_merge_dict(&described, &self.userConfig.clone())
672        };
673        let get = |k: &str| crate::get_value(&props, &Value::Str(k.to_string().into()));
674        let assign = |field: &mut Value, v: Value| {
675            if !matches!(v, Value::Null) {
676                *field = v;
677            }
678        };
679        assign(&mut self.api, get("api"));
680        assign(&mut self.urls, get("urls"));
681        assign(&mut self.has, get("has"));
682        assign(&mut self.hostname, get("hostname"));
683        assign(&mut self.version, get("version"));
684        assign(&mut self.id, get("id"));
685        assign(&mut self.name, get("name"));
686        assign(&mut self.exceptions, get("exceptions"));
687        assign(&mut self.requiredCredentials, get("requiredCredentials"));
688        assign(&mut self.precisionMode, get("precisionMode"));
689        assign(&mut self.timeframes, get("timeframes"));
690        assign(&mut self.fees, get("fees"));
691        assign(&mut self.features, get("features"));
692        let rate_limit = get("rateLimit");
693        if matches!(rate_limit, Value::Int(_) | Value::Float(_)) {
694            self.rateLimit = rate_limit;
695        }
696        // `options` and `commonCurrencies` MERGE rather than replace: the base
697        // Exchange seeds defaults into both, and describe() only supplies the
698        // venue's additions.
699        if let Value::Dict(extra) = get("options") {
700            let mut merged = match &self.options {
701                Value::Dict(m) => (**m).clone(),
702                _ => HashMap::new(),
703            };
704            let extra = Arc::try_unwrap(extra).unwrap_or_else(|a| (*a).clone());
705            for (k, v) in extra { merged.insert(k, v); }
706            self.options = Value::Map(merged);
707        }
708        if let Value::Dict(extra) = get("commonCurrencies") {
709            let mut merged = match &self.commonCurrencies {
710                Value::Dict(m) => (**m).clone(),
711                _ => HashMap::new(),
712            };
713            let extra = Arc::try_unwrap(extra).unwrap_or_else(|a| (*a).clone());
714            for (k, v) in extra { merged.insert(k, v); }
715            self.commonCurrencies = Value::Map(merged);
716        }
717        // A venue whose describe() ships its own markets (the hard-coded ones)
718        // resolves load_markets without a network call. Guarded on markets not
719        // already being loaded, so config-injected markets win.
720        let described_markets = get("markets");
721        if matches!(&described_markets, Value::Dict(m) if !m.is_empty())
722            && matches!(self.markets, Value::Null)
723        {
724            self.set_markets_inline(described_markets);
725        }
726        self.build_implicit_api();
727    }
728
729    fn apply_config(&mut self, cfg: &Value) {
730        use crate::value::safe_string;
731        if let Some(v) = safe_string(cfg, "id",       None) { self.id       = Value::Str(v.into()); }
732        if let Some(v) = safe_string(cfg, "name",     None) { self.name     = Value::Str(v.into()); }
733        if let Some(v) = safe_string(cfg, "hostname", None) { self.hostname = Value::Str(v.into()); }
734        let rate_limit = crate::get_value(cfg, &Value::Str("rateLimit".into()));
735        if matches!(rate_limit, Value::Int(_) | Value::Float(_)) { self.rateLimit = rate_limit; }
736        let timeout = crate::get_value(cfg, &Value::Str("timeout".into()));
737        if matches!(timeout, Value::Int(_) | Value::Float(_)) { self.timeout = timeout; }
738        let fetch_history_cache_size = crate::get_value(cfg, &Value::Str("fetchHistoryCacheSize".into()));
739        if matches!(fetch_history_cache_size, Value::Int(_) | Value::Float(_)) { self.fetchHistoryCacheSize = fetch_history_cache_size; }
740        let urls = crate::get_value(cfg, &Value::Str("urls".into()));
741        if let Value::Dict(_) = urls { self.urls = deep_merge(&self.urls, &urls); }
742        if let Some(v) = safe_string(cfg, "apiKey",        None) { self.apiKey        = Value::Str(v.into()); }
743        if let Some(v) = safe_string(cfg, "secret",        None) { self.secret        = Value::Str(v.into()); }
744        if let Some(v) = safe_string(cfg, "password",      None) { self.password      = Value::Str(v.into()); }
745        if let Some(v) = safe_string(cfg, "uid",           None) { self.uid           = Value::Str(v.into()); }
746        if let Some(v) = safe_string(cfg, "walletAddress", None) { self.walletAddress = Value::Str(v.into()); }
747        if let Some(v) = safe_string(cfg, "privateKey",    None) { self.privateKey    = Value::Str(v.into()); }
748        if let Some(v) = safe_string(cfg, "token",         None) { self.token         = Value::Str(v.into()); }
749        if let Some(v) = safe_string(cfg, "login",         None) { self.login         = Value::Str(v.into()); }
750        if let Some(v) = safe_string(cfg, "accountId",     None) { self.accountId     = Value::Str(v.into()); }
751        if let Some(v) = safe_string(cfg, "httpProxy",     None) { self.httpProxy     = Value::Str(v.into()); }
752        if let Some(v) = safe_string(cfg, "httpsProxy",    None) { self.httpsProxy    = Value::Str(v.into()); }
753        if let Some(v) = safe_string(cfg, "socksProxy",    None) { self.socksProxy    = Value::Str(v.into()); }
754        // WS proxies: the `watch*` transport dials these through an HTTP
755        // CONNECT tunnel. Without them here a config-supplied `wsProxy` set
756        // the field on nothing and the socket quietly went direct.
757        if let Some(v) = safe_string(cfg, "wsProxy",       None) { self.wsProxy       = Value::Str(v.into()); }
758        if let Some(v) = safe_string(cfg, "wssProxy",      None) { self.wssProxy      = Value::Str(v.into()); }
759        if let Some(b) = crate::value::safe_bool(cfg, "verbose",         None) { self.verbose         = Value::Bool(b); }
760        if let Some(b) = crate::value::safe_bool(cfg, "enableRateLimit", None) { self.enableRateLimit = Value::Bool(b); }
761        // Pre-populated state (mirrors CCXT TS Exchange constructor):
762        // markets/currencies/options arrive ready to use from offline
763        // tests, the CLI, or library users seeding state. `setMarkets`
764        // also derives markets_by_id and symbols.
765        let markets    = crate::get_value(cfg, &Value::Str("markets".into()));
766        let currencies = crate::get_value(cfg, &Value::Str("currencies".into()));
767        if !matches!(markets,    Value::Null) { self.set_markets_inline(markets); }
768        if !matches!(currencies, Value::Null) { self.currencies = currencies; }
769        let opts = crate::get_value(cfg, &Value::Str("options".into()));
770        if let Value::Dict(extra) = opts {
771            let mut merged = match &self.options {
772                Value::Dict(m) => (**m).clone(),
773                _ => HashMap::new(),
774            };
775            let extra = Arc::try_unwrap(extra).unwrap_or_else(|a| (*a).clone());
776            for (k, v) in extra { merged.insert(k, v); }
777            self.options = Value::Map(merged);
778        }
779        let accounts = crate::get_value(cfg, &Value::Str("accounts".into()));
780        if !matches!(accounts, Value::Null) { self.accounts = accounts; }
781    }
782
783    /// `markets`-from-config → derives `markets_by_id` + `symbols`.
784    /// Accepts either Map<symbol, market> or Array<market>.
785    fn set_markets_inline(&mut self, markets: Value) {
786        let arr: Vec<Value> = match &markets {
787            Value::Dict(m)   => m.values().cloned().collect(),
788            Value::Arr(a) => (**a).clone(),
789            _ => return,
790        };
791        let mut by_symbol = HashMap::new();
792        // `markets_by_id` maps an exchange market id → the *list* of
793        // markets sharing that id (e.g. binance spot + swap both have
794        // id `BTCUSDT`); `safeMarket` disambiguates by market type.
795        let mut by_id: HashMap<String, Vec<Value>> = HashMap::new();
796        let mut symbols   = Vec::new();
797        for m in &arr {
798            if let Some(s) = crate::value::safe_string(m, "symbol", None) {
799                by_symbol.insert(s.clone(), m.clone());
800                symbols.push(Value::Str(s.into()));
801            }
802            if let Some(i) = crate::value::safe_string(m, "id", None) {
803                by_id.entry(i).or_default().push(m.clone());
804            }
805        }
806        self.markets       = if by_symbol.is_empty() { markets } else { Value::Map(by_symbol) };
807        self.markets_by_id = Value::Map(
808            by_id.into_iter().map(|(k, v)| (k, Value::Array(v))).collect()
809        );
810        self.symbols       = Value::Array(symbols);
811    }
812
813    // ── http client ─────────────────────────────────────────────────────────
814
815    fn http_client(&mut self) -> &reqwest::Client {
816        if self.internals.http_client.is_none() {
817            let mut b = reqwest::Client::builder()
818                .timeout(std::time::Duration::from_millis(self.timeout_ms()))
819                // Transparent gzip: many exchanges return large JSON payloads
820                // (binance spot exchangeInfo is ~17 MB raw vs ~0.3 MB gzipped).
821                // Other CCXT langs request gzip by default; without this rust
822                // downloads the full uncompressed body, dominating load time.
823                .gzip(true);
824            if let Some(ua) = self.user_agent_str() { b = b.user_agent(ua); }
825            // Apply scheme-specific proxies. Order matters for reqwest's
826            // proxy matcher: SOCKS catches everything when set, HTTP/HTTPS
827            // only match their own scheme. The legacy `proxy` (and its
828            // snake_case alias) plus tests' `httpsProxy` use the catch-all
829            // form via Proxy::all(...). The `socks` feature on `reqwest`
830            // is what makes `socks5://...` URIs actually route — without
831            // it `Proxy::all` would build but the connection silently
832            // never goes through SOCKS.
833            let mut proxies: Vec<reqwest::Proxy> = Vec::new();
834            for field in [&self.socksProxy, &self.socks_proxy] {
835                if let Value::Str(s) = field {
836                    if !s.is_empty() {
837                        if let Ok(p) = reqwest::Proxy::all(s.as_ref()) { proxies.push(p); }
838                    }
839                }
840            }
841            for field in [&self.httpsProxy, &self.https_proxy] {
842                if let Value::Str(s) = field {
843                    if !s.is_empty() {
844                        if let Ok(p) = reqwest::Proxy::https(s.as_ref()) { proxies.push(p); }
845                    }
846                }
847            }
848            for field in [&self.httpProxy, &self.http_proxy] {
849                if let Value::Str(s) = field {
850                    if !s.is_empty() {
851                        if let Ok(p) = reqwest::Proxy::http(s.as_ref()) { proxies.push(p); }
852                    }
853                }
854            }
855            // Legacy single `proxy` setter (catch-all). Only honoured if
856            // none of the scheme-specific fields fired.
857            if proxies.is_empty() {
858                if let Value::Str(s) = &self.proxy {
859                    if !s.is_empty() {
860                        if let Ok(p) = reqwest::Proxy::all(s.as_ref()) { proxies.push(p); }
861                    }
862                }
863            }
864            for p in proxies { b = b.proxy(p); }
865            self.internals.http_client = Some(b.build().expect("reqwest client"));
866        }
867        self.internals.http_client.as_ref().unwrap()
868    }
869
870    fn timeout_ms(&self) -> u64 {
871        match &self.timeout {
872            Value::Int(n)   => *n as u64,
873            Value::Float(f) => *f as u64,
874            _ => 10_000,
875        }
876    }
877
878    fn user_agent_str(&self) -> Option<&str> {
879        match &self.userAgent { Value::Str(s) => Some(s.as_ref()), _ => match &self.user_agent {
880            Value::Str(s) => Some(s.as_ref()), _ => None
881        }}
882    }
883
884
885    fn is_verbose(&self) -> bool {
886        matches!(self.verbose, Value::Bool(true))
887    }
888
889
890    // ── encoding / URL helpers ──────────────────────────────────────────────
891
892    pub fn urlencode_kv(&self, params: &Value) -> String {
893        let m = match params { Value::Dict(m) => m, _ => return String::new() };
894        m.iter().map(|(k, v)| format!(
895            "{}={}",
896            url_pct(k),
897            url_pct(&crate::runtime::stringify_param(v)),
898        )).collect::<Vec<_>>().join("&")
899    }
900
901    pub fn implode_params(&self, path: Value, params: Value) -> Value {
902        let path_str = match &path { Value::Str(s) => s.clone(), _ => return path };
903        let m = match &params { Value::Dict(m) => m, _ => return Value::Str(path_str) };
904        let mut out = path_str;
905        for (k, v) in m.iter() {
906            let needle = format!("{{{k}}}");
907            if out.contains(&needle) {
908                out = out.replace(&needle, &crate::runtime::stringify_param(v)).into();
909            }
910        }
911        Value::Str(out)
912    }
913
914    pub fn json_str(&self, v: &Value) -> String {
915        serde_json::to_string(&v.to_json()).unwrap_or_default()
916    }
917
918    // ── crypto ──────────────────────────────────────────────────────────────
919
920    pub fn hmac(&self, data: Value, secret: Value, hash: Value, optional_args: &[Value]) -> Value {
921        // `data`/`secret` may be a string OR the byte-array produced by
922        // `encode()` (CCXT's `hmac` takes the encoded request/secret).
923        let dbytes = value_to_bytes(&data);
924        let sbytes = value_to_bytes(&secret);
925        let h = match &hash { Value::Str(s) => s.clone(), _ => "sha256".to_string().into() };
926        let digest = match optional_args.get(0) {
927            Some(Value::Str(d)) => d.clone(),
928            _ => "hex".to_string().into(),
929        };
930        match self.hmac_typed(&dbytes, &sbytes, &h, &digest) {
931            Ok(v) => Value::Str(v.into()),
932            Err(_) => Value::Null,
933        }
934    }
935
936    pub fn hmac_typed(&self, data: &[u8], secret: &[u8], hash: &str, digest: &str) -> Result<String> {
937        let dbytes = data;
938        let sbytes = secret;
939        let raw: Vec<u8> = match hash.to_ascii_lowercase().as_str() {
940            "sha256" => { let mut m = HmacSha256::new_from_slice(sbytes).unwrap(); m.update(dbytes); m.finalize().into_bytes().to_vec() }
941            "sha512" => { let mut m = HmacSha512::new_from_slice(sbytes).unwrap(); m.update(dbytes); m.finalize().into_bytes().to_vec() }
942            "sha1"   => { let mut m = HmacSha1::new_from_slice(sbytes).unwrap();   m.update(dbytes); m.finalize().into_bytes().to_vec() }
943            "md5"    => { let mut m = HmacMd5::new_from_slice(sbytes).unwrap();    m.update(dbytes); m.finalize().into_bytes().to_vec() }
944            other    => return Err(ExchangeError::new("BadRequest", format!("unknown hmac: {other}"))),
945        };
946        Ok(match digest {
947            "base64" => B64.encode(&raw),
948            _        => hex::encode(&raw),
949        })
950    }
951
952    pub fn hash(&self, data: Value, algo: Value, optional_args: &[Value]) -> Value {
953        // `data` may be a string OR the byte-array produced by `encode()`.
954        let dbytes = value_to_bytes(&data);
955        let a = match &algo { Value::Str(s) => s.clone(), _ => "sha256".to_string().into() };
956        let digest = match optional_args.get(0) {
957            Some(Value::Str(d)) => d.clone(),
958            _ => "hex".to_string().into(),
959        };
960        let raw = hash_raw(&dbytes, &a);
961        match digest.as_ref() {
962            // `binary` → a byte-array Value (consumed by another crypto step).
963            "binary" => Value::Array(raw.iter().map(|b| Value::Int(*b as i64)).collect()),
964            "base64" => Value::Str(B64.encode(&raw).into()),
965            _        => Value::Str(hex::encode(&raw).into()),
966        }
967    }
968
969    pub fn hash_typed(&self, data: &[u8], algo: &str, digest: &str) -> String {
970        let raw = hash_raw(data, algo);
971        match digest {
972            "base64" => B64.encode(&raw),
973            _        => hex::encode(&raw),
974        }
975    }
976
977    pub fn binary_to_base64(&self, data: Value, _optional_args: &[Value]) -> Value {
978        let bytes = value_to_bytes(&data);
979        Value::Str(B64.encode(&bytes).into())
980    }
981    pub fn base64_to_binary(&self, s: Value, _optional_args: &[Value]) -> Value {
982        let str_val = match &s { Value::Str(s) => s.clone(), _ => return Value::Null };
983        match B64.decode(&*str_val) {
984            Ok(b) => Value::Array(b.into_iter().map(|n| Value::Int(n as i64)).collect()),
985            Err(_) => Value::Null,
986        }
987    }
988    pub fn binary_to_base16(&self, data: Value, _optional_args: &[Value]) -> Value {
989        let bytes = value_to_bytes(&data);
990        Value::Str(hex::encode(&bytes).into())
991    }
992    pub fn base16_to_binary(&self, s: Value, _optional_args: &[Value]) -> Value {
993        let str_val = match &s { Value::Str(s) => s.clone(), _ => return Value::Null };
994        match hex::decode(&*str_val) {
995            Ok(b) => Value::Array(b.into_iter().map(|n| Value::Int(n as i64)).collect()),
996            Err(_) => Value::Null,
997        }
998    }
999
1000    // ── time ────────────────────────────────────────────────────────────────
1001
1002    pub fn milliseconds(&self) -> Value {
1003        let n = std::time::SystemTime::now()
1004            .duration_since(std::time::UNIX_EPOCH)
1005            .map(|d| d.as_millis() as i64).unwrap_or(0);
1006        Value::Int(n)
1007    }
1008    pub fn seconds(&self) -> Value {
1009        match self.milliseconds() { Value::Int(n) => Value::Int(n / 1000), v => v }
1010    }
1011    pub fn microseconds(&self) -> Value {
1012        match self.milliseconds() { Value::Int(n) => Value::Int(n * 1000), v => v }
1013    }
1014
1015    pub fn iso8601(&self, ts: Value) -> Value {
1016        let n = match ts {
1017            Value::Int(n)   => n,
1018            Value::Float(f) => f as i64,
1019            Value::Str(ref s) => match s.parse::<i64>() { Ok(v) => v, Err(_) => return Value::Null },
1020            _ => return Value::Null,
1021        };
1022        if n < 0 {
1023            return Value::Null;
1024        }
1025        chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n)
1026            .map(|t| Value::Str(t.to_rfc3339_opts(chrono::SecondsFormat::Millis, true).into()))
1027            .unwrap_or(Value::Null)
1028    }
1029
1030    pub fn parse8601(&self, s: Value) -> Value {
1031        let str_val = match s { Value::Str(s) => s, _ => return Value::Null };
1032        if str_val.is_empty() {
1033            return Value::Null;
1034        }
1035        // rfc3339 (`T…Z` / `+00:00` offset forms).
1036        if let Ok(t) = chrono::DateTime::parse_from_rfc3339(&str_val) {
1037            return Value::Int(t.timestamp_millis());
1038        }
1039        // Numeric timezone offset WITHOUT a colon (`+0000`) — not valid
1040        // rfc3339 but common (e.g. bitso `2024-03-13T10:59:59+0000`). JS
1041        // `Date.parse` accepts it; chrono needs an explicit `%z` format.
1042        for fmt in [
1043            "%Y-%m-%dT%H:%M:%S%.f%z", "%Y-%m-%dT%H:%M:%S%z",
1044            "%Y-%m-%d %H:%M:%S%.f%z", "%Y-%m-%d %H:%M:%S%z",
1045        ] {
1046            if let Ok(t) = chrono::DateTime::parse_from_str(&str_val, fmt) {
1047                return Value::Int(t.timestamp_millis());
1048            }
1049        }
1050        // Lenient fallbacks — naive forms are interpreted as UTC.
1051        for fmt in [
1052            "%Y-%m-%d %H:%M:%S%.f", "%Y-%m-%d %H:%M:%S",
1053            "%Y-%m-%dT%H:%M:%S%.f", "%Y-%m-%dT%H:%M:%S",
1054            "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M",
1055        ] {
1056            if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(&str_val, fmt) {
1057                return Value::Int(ndt.and_utc().timestamp_millis());
1058            }
1059        }
1060        if let Ok(d) = chrono::NaiveDate::parse_from_str(&str_val, "%Y-%m-%d") {
1061            if let Some(ndt) = d.and_hms_opt(0, 0, 0) {
1062                return Value::Int(ndt.and_utc().timestamp_millis());
1063            }
1064        }
1065        Value::Null
1066    }
1067
1068    // safe_string/safe_number/safe_integer/safe_bool live on the transpiled
1069    // side (`exchange_generated.rs`) when the `transpiled-base` feature is
1070    // enabled. The free-functions in `crate::value` are the typed
1071    // equivalents — used internally by hand-written code below.
1072
1073
1074}
1075
1076// ── small helper used by url-encoding above ─────────────────────────────────
1077
1078// ── derived dispatch re-entry guard ─────────────────────────────────────────
1079//
1080// Virtual dispatch itself is now STATIC: `ExchangeBase`'s default methods call
1081// `DerivedExchange::X(self, ...)` and `self.call_dynamic(...)` directly on the
1082// concrete Core, with no stored self-pointer (review #1). All that remains here
1083// is the per-method re-entry guard the async `dispatch_to_derived` default (in
1084// `exchange_generated::ExchangeBase`) uses so a base method that dispatches its
1085// own name falls through to the base body instead of looping.
1086
1087impl Exchange {
1088    /// Enter the guard for `method`. Returns `false` if `method` is already on
1089    /// the dispatch stack (re-entry — caller should fall through to the base
1090    /// body); otherwise pushes it and returns `true`.
1091    pub fn dispatch_guard_enter(&mut self, method: &str) -> bool {
1092        if self.internals.dispatch_stack.iter().any(|m| m == method) { return false; }
1093        self.internals.dispatch_stack.push(method.to_string());
1094        true
1095    }
1096
1097    /// Leave the guard (pop the most-recently entered method).
1098    pub fn dispatch_guard_exit(&mut self) {
1099        self.internals.dispatch_stack.pop();
1100    }
1101}
1102
1103// ── ExchangeRuntime: base methods that reach derived overrides ───────────────
1104//
1105// A handful of hand-written base methods must call a derived override
1106// (`sign`, `handle_errors`) or dispatch async-by-name, so they need the
1107// concrete Core as `Self` to resolve statically (review #1). They live in this
1108// trait, blanket-impl'd for every `ExchangeBase`, so `self.fetch(...)`,
1109// `self.request_typed(...)`, … on a Core (or inside an `ExchangeBase` default)
1110// resolve here. Bodies reach `Exchange` fields via the `DerefMut` bound, other
1111// base methods via `ExchangeBase`, and pure `impl Exchange` helpers via `Deref`.
1112/// Coerce a `Value` (string, or list of strings) into a `Vec<String>` of
1113/// message/subscribe hashes for the WS drive loop.
1114fn ws_string_list(v: &Value) -> Vec<String> {
1115    match v {
1116        Value::Str(s) => vec![s.to_string()],
1117        Value::Arr(a) => a
1118            .iter()
1119            .filter_map(|x| match x {
1120                Value::Str(s) => Some(s.to_string()),
1121                _ => None,
1122            })
1123            .collect(),
1124        _ => Vec::new(),
1125    }
1126}
1127
1128pub trait ExchangeRuntime: crate::exchange_generated::ExchangeBase {
1129    fn fetch(&mut self, url: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1130        let url_str = match &url { Value::Str(s) => s.to_string(), _ => crate::runtime::stringify_param(&url).into() };
1131        let method = optional_args.get(0).cloned().unwrap_or(Value::Str("GET".into()));
1132        let headers = optional_args.get(1).cloned().unwrap_or(Value::Null);
1133        let body = optional_args.get(2).cloned().unwrap_or(Value::Null);
1134        let method_str = match &method { Value::Str(s) => s.to_string(), _ => "GET".to_string().into() };
1135        let body_str = match &body { Value::Str(s) => Some(s.to_string()), _ => None };
1136        let headers_map: HashMap<String, String> = match &headers {
1137            Value::Dict(m) => m.iter().filter_map(|(k, v)| match v {
1138                Value::Str(s) => Some((k.clone(), s.to_string())),
1139                _ => None,
1140            }).collect(),
1141            _ => HashMap::new(),
1142        };
1143        match self.fetch_typed(&url_str, &method_str, headers_map, body_str).await {
1144            Ok(v) => v,
1145            // Propagate, do NOT swallow. Returning `Value::Null` here hid every
1146            // transport-level failure — network errors, and `InvalidProxySettings`,
1147            // which the static request tests rely on: they set two conflicting
1148            // proxies so `fetch` aborts right after the request is built, then
1149            // assert on the captured URL/body. Swallowed, the method instead ran
1150            // on with a null response, so a venue that validates what it parsed
1151            // (bitstamp's fetchDepositAddress -> checkAddress) failed with a
1152            // misleading `InvalidAddress` instead of aborting. `panic!` is the
1153            // transpiled error convention — `ExchangeError`'s Display renders
1154            // `[Kind] message`, which `is_instance` matches on.
1155            Err(e) if e.kind == "InvalidProxySettings" => panic!("{}", e),
1156            // Everything else is still swallowed, which is also wrong — a real
1157            // network failure should reach the caller. It cannot be propagated
1158            // yet: the transpiler drops `catch` blocks (test.fetchHistory.ts's
1159            // `try { fetch2('sample1') } catch { ... }` lowers to a bare block),
1160            // so the panic escapes a test TS expects to swallow. Propagating
1161            // everything needs that lowering fixed first.
1162            Err(_) => Value::Null,
1163        }
1164    } }
1165
1166    // ── WebSocket (pro) drive loop ──────────────────────────────────────────
1167    //
1168    // Port of the runtime side of `Exchange.watch` / `watchMultiple`. These are
1169    // trait methods (not inherent on `Exchange`) so `self` is the concrete Core
1170    // and `dispatch_to_derived("handle_message", …)` reaches the venue override.
1171    //
1172    // Model: `watch` drives synchronously — it connects, sends the subscribe
1173    // frame once, then loops reading inbound frames and feeding each to the
1174    // venue's `handle_message` (which calls `client.resolve(value, hash)`),
1175    // returning as soon as one of the awaited hashes is settled. A repeated
1176    // `while true { watch_x().await }` consumer therefore gets one update per
1177    // call, exactly like the TS Future model. (Concurrently awaiting two streams
1178    // on the *same* socket via join is a known limitation — each drive loop
1179    // pulls from the shared frame queue.)
1180
1181    /// Shared drive loop for `watch` / `watch_multiple`.
1182    fn ws_run(
1183        &mut self,
1184        url: String,
1185        hashes: Vec<String>,
1186        message: Value,
1187        subscribe_hashes: Vec<String>,
1188        subscription: Value,
1189    ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1190        let __ws_proxy = [&self.wsProxy, &self.ws_proxy, &self.wssProxy]
1191            .iter()
1192            .find_map(|v| match v { Value::Str(s) if !s.is_empty() => Some(s.to_string()), _ => None });
1193        let client = match crate::pro::ws_client::ensure_client(&url, __ws_proxy).await {
1194            Ok(c) => c,
1195            Err(e) => panic!("{}", e),
1196        };
1197        if std::env::var("CCXT_WS_DEBUG").is_ok() {
1198            eprintln!("[wswait] {:?}", hashes);
1199        }
1200        client.note_futures(&hashes);
1201        // 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 text   = resp.text().await?;
1470        HTTP_NANOS.fetch_add(__http_t0.elapsed().as_nanos() as u64,
1471            std::sync::atomic::Ordering::Relaxed);
1472        if self.is_verbose() {
1473            eprintln!("[ccxt] ← {status} {} bytes", text.len());
1474            const CAP: usize = 16384;
1475            if text.len() > CAP {
1476                eprintln!("[ccxt]   response body: {}… ({} bytes total)",
1477                    &text[..text.char_indices().take_while(|(i, _)| *i < CAP).last().map(|(i, c)| i + c.len_utf8()).unwrap_or(0)],
1478                    text.len());
1479            } else {
1480                eprintln!("[ccxt]   response body: {text}");
1481            }
1482        }
1483        let __json_t0 = std::time::Instant::now();
1484        let json = match serde_json::from_str::<serde_json::Value>(&text) {
1485            Ok(j)  => Value::from_json(&j),
1486            Err(_) => Value::Null,
1487        };
1488        JSON_NANOS.fetch_add(__json_t0.elapsed().as_nanos() as u64,
1489            std::sync::atomic::Ordering::Relaxed);
1490        if status >= 400 {
1491            // Static dispatch to the derived exchange's handle_errors override.
1492            crate::exchange::DerivedExchange::handle_errors(
1493                self,
1494                Value::Int(status as i64),
1495                Value::Null,
1496                Value::Str(url.to_string().into()),
1497                Value::Str(method.to_string().into()),
1498                Value::Null,
1499                Value::Str(text.clone().into()),
1500                json.clone(),
1501                Value::Null,
1502                Value::Null,
1503            );
1504            return Err(ExchangeError::new(
1505                if status == 429 { "RateLimitExceeded" }
1506                else if status >= 500 { "ExchangeNotAvailable" }
1507                else { "ExchangeError" },
1508                format!("HTTP {status}: {text}"),
1509            ));
1510        }
1511        if matches!(json, Value::Null) {
1512            return Ok(Value::Str(text.into()));
1513        }
1514        Ok(json)
1515    } }
1516
1517    fn request_typed(&mut self, path: &str, scope_segments: &[String], verb: &str, params: Value, cost: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1518        // Mock transport responses only; preserve the signed request metadata.
1519        if matches!(self.mock_response, Value::Null) && matches!(self.mock_response_by_url, Value::Null) {
1520            self.throttle(&[cost]).await;
1521        }
1522        let api_arg = if scope_segments.len() == 1 {
1523            Value::Str(scope_segments[0].clone().into())
1524        } else {
1525            Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect())
1526        };
1527        let scope_lookup: String = scope_segments.first().cloned().unwrap_or_default();
1528        // Static dispatch to the derived exchange's sign override.
1529        let signed = crate::exchange::DerivedExchange::sign(
1530            self,
1531            Value::Str(path.to_string().into()),
1532            api_arg,
1533            Value::Str(verb.to_string().into()),
1534            params.clone(),
1535            Value::Null,
1536            Value::Null,
1537        );
1538        if let Value::Dict(m) = &signed {
1539            let url = match m.get("url") { Some(Value::Str(s)) => s.to_string(), _ => String::new().into() };
1540            let method = match m.get("method") { Some(Value::Str(s)) => s.to_string(), _ => verb.to_string().into() };
1541            let body = match m.get("body") { Some(Value::Str(s)) => Some(s.to_string()), _ => None };
1542            let headers = match m.get("headers") {
1543                Some(Value::Dict(h)) => h.iter()
1544                    .filter_map(|(k, v)| match v { Value::Str(s) => Some((k.clone(), s.to_string())), _ => None })
1545                    .collect::<HashMap<_, _>>(),
1546                _ => HashMap::new(),
1547            };
1548            if !url.is_empty() {
1549                return self.fetch_typed(&url, &method, headers, body).await;
1550            }
1551        }
1552        let base = self.url_for_scope(&scope_lookup).ok_or_else(|| ExchangeError::new(
1553            "BadRequest",
1554            format!("no URL configured for api scope `{scope_lookup}`"),
1555        ))?;
1556        let imploded = self.implode_params(Value::Str(path.to_string().into()), params.clone());
1557        let path_str = match &imploded { Value::Str(s) => s.clone(), _ => path.to_string().into() };
1558        let consumed_keys = self.extract_path_params(path);
1559        let remaining_params = match params {
1560            Value::Dict(m) => {
1561                let mut keep = HashMap::new();
1562                let m = Arc::try_unwrap(m).unwrap_or_else(|a| (*a).clone());
1563                for (k, v) in m {
1564                    if !consumed_keys.contains(&k) { keep.insert(k, v); }
1565                }
1566                Value::Map(keep)
1567            }
1568            other => other,
1569        };
1570        let mut url = format!("{}/{}", base.trim_end_matches('/'), path_str.trim_start_matches('/'));
1571        let mut body: Option<String> = None;
1572        let qs = match &remaining_params {
1573            Value::Dict(m) if !m.is_empty() => self.urlencode_kv(&remaining_params),
1574            _ => String::new(),
1575        };
1576        if verb == "GET" || verb == "DELETE" {
1577            if !qs.is_empty() {
1578                url = format!("{}?{}", url, qs);
1579            }
1580        } else if !qs.is_empty() {
1581            body = Some(qs);
1582        }
1583        let mut headers = HashMap::new();
1584        if scope_lookup != "public" {
1585            if let Value::Str(k) = &self.apiKey {
1586                headers.insert("X-MBX-APIKEY".to_string(), k.to_string());
1587            }
1588        }
1589        self.fetch_typed(&url, verb, headers, body).await
1590    } }
1591
1592    /// Route an implicit-API method name to `request_typed`.
1593    fn implicit_api_call(&mut self, name: &str, params: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1594        if self.internals.implicit_api.is_empty() {
1595            self.build_implicit_api();
1596        }
1597        let entry = self.internals.implicit_api.get(name).cloned();
1598        let (path, scope_segments, verb, config) = match entry {
1599            Some(t) => t,
1600            None => return Err(ExchangeError::new(
1601                "NotSupported",
1602                format!("implicit API method {name} not found in api block"),
1603            )),
1604        };
1605        let api = if scope_segments.len() == 1 {
1606            Value::Str(scope_segments[0].clone().into())
1607        } else {
1608            Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect())
1609        };
1610        let cost = if matches!(self.enableRateLimit, Value::Bool(true)) {
1611            self.call_dynamic(
1612                "calculate_rate_limiter_cost",
1613                vec![api, Value::Str(verb.clone().into()), Value::Str(path.clone().into()), params.clone(), config],
1614            ).await
1615        } else {
1616            Value::Null
1617        };
1618        self.request_typed(&path, &scope_segments, &verb, params, cost).await
1619    } }
1620
1621    #[cfg(test)]
1622    fn implicit_api_rate_limit_cost(&mut self, name: &str, params: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1623        if self.internals.implicit_api.is_empty() {
1624            self.build_implicit_api();
1625        }
1626        let (path, scope_segments, verb, config) = self.internals.implicit_api
1627            .get(name)
1628            .cloned()
1629            .ok_or_else(|| ExchangeError::new("NotSupported", format!("implicit API method {name} not found in api block")))?;
1630        let api = if scope_segments.len() == 1 {
1631            Value::Str(scope_segments[0].clone().into())
1632        } else {
1633            Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect())
1634        };
1635        Ok(self.call_dynamic(
1636            "calculate_rate_limiter_cost",
1637            vec![api, Value::Str(verb.into()), Value::Str(path.into()), params, config],
1638        ).await)
1639    } }
1640
1641    /// Dispatch an implicit-API method by name (from transpiled `_api.rs`).
1642    fn call_method(&mut self, name: Value, args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1643        let n = match name { Value::Str(s) => s, _ => return Value::Null };
1644        let params = args.get(0).cloned().unwrap_or(Value::Map(HashMap::new()));
1645        match self.implicit_api_call(&n, params).await {
1646            Ok(v) => v,
1647            Err(e) => {
1648                if matches!(self.verbose, Value::Bool(true)) {
1649                    eprintln!("[ccxt] {n} failed: {e}");
1650                }
1651                panic!("{e}");
1652            }
1653        }
1654    } }
1655
1656    /// Loads markets (and currencies), dispatching `fetch_markets` /
1657    /// `fetch_currencies` / `set_markets` to the derived overrides.
1658    fn load_markets(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1659        let reload = optional_args.get(0).cloned().unwrap_or(Value::Bool(false));
1660        let reload_b = matches!(reload, Value::Bool(true));
1661        if !reload_b && !self.markets.is_null() {
1662            return self.markets.clone();
1663        }
1664        let has_fetch_currencies = matches!(
1665            crate::get_value(&self.has, &Value::Str("fetchCurrencies".into())),
1666            Value::Bool(true),
1667        );
1668        let mut currencies = Value::Null;
1669        if has_fetch_currencies {
1670            if let Some(v) = self.dispatch_to_derived("fetch_currencies", Vec::new()).await {
1671                currencies = v;
1672            }
1673        }
1674        let fetched = match self.dispatch_to_derived("fetch_markets", Vec::new()).await {
1675            Some(v) => v,
1676            None => return Value::Null,
1677        };
1678        if matches!(fetched, Value::Null) {
1679            return self.markets.clone();
1680        }
1681        let preloaded_non_empty = matches!(&self.currencies, Value::Dict(m) if !m.is_empty());
1682        let currencies_arg = if matches!(&currencies, Value::Dict(m) if !m.is_empty()) {
1683            currencies
1684        } else if preloaded_non_empty {
1685            self.currencies.clone()
1686        } else {
1687            crate::exchange_stubs::synthesize_currencies_from_markets(&fetched, &self.precisionMode)
1688        };
1689        let is_prediction = matches!(
1690            crate::get_value(&self.has, &Value::Str("prediction".into())),
1691            Value::Bool(true),
1692        );
1693        if is_prediction {
1694            let _ = self.dispatch_to_derived("set_markets", vec![fetched, currencies_arg]).await;
1695        } else {
1696            <Self as crate::exchange_generated::ExchangeBase>::set_markets(self, fetched, &[currencies_arg]);
1697        }
1698        // Index markets_by_id by the secondary id (`id2`, e.g. apex's
1699        // crossSymbolName) too, so a WS handler that resolves a market from the
1700        // id2-based stream id (`safeMarket(data['s'])`) reaches the unified
1701        // symbol instead of a synthetic one.
1702        let markets_snapshot = self.markets.clone();
1703        if let Value::Dict(markets) = &markets_snapshot {
1704            if let Value::Dict(by_id_arc) = &self.markets_by_id {
1705                let mut by_id = (**by_id_arc).clone();
1706                for market in markets.values() {
1707                    let id  = crate::get_value(market, &Value::Str("id".into()));
1708                    let id2 = crate::get_value(market, &Value::Str("id2".into()));
1709                    if let (Value::Str(id2s), Value::Str(ids)) = (&id2, &id) {
1710                        if id2s != ids && !id2s.is_empty() && !by_id.contains_key(id2s.as_ref()) {
1711                            by_id.insert(id2s.to_string(), Value::List(vec![market.clone()]));
1712                        }
1713                    }
1714                }
1715                self.markets_by_id = Value::Map(by_id);
1716            }
1717        }
1718        self.markets.clone()
1719    } }
1720
1721    // ── super.X() shims — call the BASE (ExchangeBase) method, fully-qualified
1722    // so a derived override is bypassed (that is what `super.X()` means).
1723    fn super_describe(&self) -> Value {
1724        <Self as crate::exchange_generated::ExchangeBase>::describe(self)
1725    }
1726    fn super_set_sandbox_mode(&mut self, enabled: Value) {
1727        <Self as crate::exchange_generated::ExchangeBase>::set_sandbox_mode(self, enabled);
1728    }
1729    fn super_safe_market(&self, id: Value, market: Value, delim: Value, market_type: Value) -> Value {
1730        <Self as crate::exchange_generated::ExchangeBase>::safe_market(self, &[id, market, delim, market_type])
1731    }
1732    fn super_handle_market_type_and_params(&self, method_name: Value, market: Value, params: Value, default_value: Value) -> Value {
1733        <Self as crate::exchange_generated::ExchangeBase>::handle_market_type_and_params(self, method_name, &[market, params, default_value])
1734    }
1735    fn super_market(&self, symbol: Value) -> Value {
1736        <Self as crate::exchange_generated::ExchangeBase>::market(self, symbol)
1737    }
1738    fn super_amount_to_precision(&self, symbol: Value, amount: Value) -> Value {
1739        <Self as crate::exchange_generated::ExchangeBase>::amount_to_precision(self, symbol, amount)
1740    }
1741    fn super_handle_margin_mode_and_params(&self, method_name: Value, params: Value, default_value: Value) -> Value {
1742        <Self as crate::exchange_generated::ExchangeBase>::handle_margin_mode_and_params(self, method_name, &[params, default_value])
1743    }
1744    fn super_safe_currency_code(&self, currency_id: Value, currency: Value) -> Value {
1745        <Self as crate::exchange_generated::ExchangeBase>::safe_currency_code(self, currency_id, &[currency])
1746    }
1747    fn super_set_markets(&mut self, markets: Value, currencies: Value) -> Value {
1748        <Self as crate::exchange_generated::ExchangeBase>::set_markets(self, markets, &[currencies])
1749    }
1750    fn super_network_id_to_code(&self, optional_args: &[Value]) -> Value {
1751        <Self as crate::exchange_generated::ExchangeBase>::network_id_to_code(self, optional_args)
1752    }
1753    fn super_network_code_to_id(&self, network_code: Value, optional_args: &[Value]) -> Value {
1754        <Self as crate::exchange_generated::ExchangeBase>::network_code_to_id(self, network_code, optional_args)
1755    }
1756    fn super_fetch_deposit_address(&mut self, code: Value, params: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
1757        self.fetch_deposit_address(code, &[params]).await
1758    } }
1759    fn super_load_markets(&mut self, reload: Value, params: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
1760        self.load_markets(&[reload, params]).await
1761    } }
1762}
1763
1764impl<T: crate::exchange_generated::ExchangeBase> ExchangeRuntime for T {}
1765
1766/// Normalize a TS dynamic method name for the generated Rust dispatch table.
1767///
1768/// Must stay byte-identical to the transpiler's `toSnakeCase`
1769/// (`build/rustTranspiler.ts`) and to `Exchange::to_snake_case` (which names
1770/// the implicit-API entries `call_dynamic`'s fall-through looks up) — it is the
1771/// only thing deciding whether a paginated `this[method](...)` re-entry lands
1772/// on a dispatch arm. `method_name_snake_case_tests` pins all three.
1773///
1774/// A name that is not a `Value::Str` (or is empty) is a hard bug: TS
1775/// `this[name](...)` always indexes with a string. Returning `""` here would
1776/// resolve to no dispatch arm and no implicit endpoint, so `call_dynamic`
1777/// would hand back `Value::Null` and the caller would silently see an empty
1778/// page instead of an error — exactly the failure this PR set out to remove.
1779/// Panic instead, mirroring the TS `TypeError: this[method] is not a function`
1780/// (the transpiled try/catch turns it back into a catchable error).
1781pub fn method_name_to_snake_case(name: &Value) -> String {
1782    let name = match name {
1783        Value::Str(name) if !name.is_empty() => name,
1784        _ => panic!(
1785            "{}",
1786            crate::exchange_errors::not_supported(format!(
1787                "dynamic method dispatch requires a non-empty string method name, got {name:?}"
1788            )),
1789        ),
1790    };
1791    let chars: Vec<char> = name.chars().collect();
1792    let mut out = String::with_capacity(name.len() + 4);
1793    for (i, &c) in chars.iter().enumerate() {
1794        if c.is_ascii_uppercase() {
1795            let lower_before = i > 0
1796                && (chars[i - 1].is_ascii_lowercase() || chars[i - 1].is_ascii_digit());
1797            let acronym_end = i > 0 && chars[i - 1].is_ascii_uppercase()
1798                && chars.get(i + 1).map(|next| next.is_ascii_lowercase()).unwrap_or(false);
1799            if lower_before || acronym_end {
1800                out.push('_');
1801            }
1802            out.push(c.to_ascii_lowercase());
1803        } else {
1804            out.push(c);
1805        }
1806    }
1807    out
1808}
1809
1810/// Wraps a `call_dynamic` re-entry that MUST resolve. `call_dynamic_base`'s
1811/// `_` arm returns `Value::Null` for a name that is neither a dispatch arm nor
1812/// an implicit-API endpoint — fine for an optional probe, but a dynamic
1813/// re-entry from `fetchPaginatedCall*` / `fetchWebEndpoint` would then hand the
1814/// caller an empty page instead of an error. That arm records the miss on
1815/// `internals.dynamic_dispatch_miss`; this raises it as a loud `NotSupported`,
1816/// the way `call_method` used to fail, so a dispatch regression surfaces as an
1817/// error rather than as null data (review on #30385).
1818pub trait CallDynamicChecked: crate::exchange_generated::ExchangeBase {
1819    fn call_dynamic_checked(&mut self, name: Value, args: Vec<Value>) -> impl ::std::future::Future<Output = Value> + Send { async move {
1820        let snake = method_name_to_snake_case(&name);
1821        // Clear first: a miss recorded by an unrelated earlier probe must not
1822        // be attributed to this call.
1823        self.internals.dynamic_dispatch_miss = None;
1824        let out = self.call_dynamic(&snake, args).await;
1825        // Only OUR name counts — a nested optional probe inside the dispatched
1826        // method legitimately misses and must stay silent.
1827        if self.internals.dynamic_dispatch_miss.as_deref() == Some(snake.as_str()) {
1828            self.internals.dynamic_dispatch_miss = None;
1829            panic!(
1830                "{}",
1831                crate::exchange_errors::not_supported(format!(
1832                    "{} dynamic method {snake}() resolved to no dispatch arm and no implicit API endpoint",
1833                    crate::runtime::stringify_param(&self.id),
1834                )),
1835            );
1836        }
1837        out
1838    } }
1839}
1840
1841impl<T: crate::exchange_generated::ExchangeBase> CallDynamicChecked for T {}
1842
1843/// A minimal Core wrapping a bare `Exchange` with NO overrides. Lets code that
1844/// only has an `Exchange` value — `Value` snapshots (value.rs), the constructor
1845/// (`after_construct`), and base unit tests — call `ExchangeBase`/`ExchangeRuntime`
1846/// trait methods, which all resolve to the base defaults (review #1: base
1847/// methods are trait methods now, so a bare `Exchange` can't call them directly).
1848pub struct BaseCore {
1849    pub exchange: Exchange,
1850}
1851impl BaseCore {
1852    pub fn new(exchange: Exchange) -> Self { Self { exchange } }
1853    pub fn into_inner(self) -> Exchange { self.exchange }
1854}
1855impl std::ops::Deref for BaseCore {
1856    type Target = Exchange;
1857    fn deref(&self) -> &Exchange { &self.exchange }
1858}
1859impl std::ops::DerefMut for BaseCore {
1860    fn deref_mut(&mut self) -> &mut Exchange { &mut self.exchange }
1861}
1862impl DerivedExchange for BaseCore {}
1863impl crate::exchange_generated::ExchangeBase for BaseCore {
1864    fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<Value>)
1865        -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>>
1866    {
1867        Box::pin(async move { self.call_dynamic_base(method, args).await })
1868    }
1869}
1870
1871// ── implicit API dispatch ───────────────────────────────────────────────────
1872
1873impl Exchange {
1874    /// Builds the `name → (path, scope, verb)` dispatch table by walking
1875    /// the `self.api` Value::Map. Called lazily on first dynamic call.
1876    ///
1877    /// The `api` block layout is:
1878    ///   { <scope>: { <verb>: [path, path, ...] } }
1879    ///   { <scope>: { <subscope>: { <verb>: [path, ...] } } }
1880    /// — arbitrary nesting before the verb level. The verb is one of
1881    /// `get`/`post`/`put`/`delete`/`patch` (any case). All path components
1882    /// before the verb concatenate into the scope (joined by `_`).
1883    pub fn build_implicit_api(&mut self) {
1884        let mut map: HashMap<String, (String, Vec<String>, String, Value)> = HashMap::new();
1885        Self::walk_api_node(&self.api, &[], &mut map);
1886        self.internals.implicit_api = map;
1887    }
1888
1889    fn walk_api_node(
1890        node: &Value,
1891        crumbs: &[String],
1892        out: &mut HashMap<String, (String, Vec<String>, String, Value)>,
1893    ) {
1894        let known_verbs = ["get", "post", "put", "delete", "patch"];
1895        let last_is_verb = crumbs.last()
1896            .map(|c| known_verbs.iter().any(|v| *v == c.to_lowercase().as_str()))
1897            .unwrap_or(false);
1898        match node {
1899            // If the current level is a verb (`get`/`post`/…) and its child
1900            // is a Map, the keys ARE the paths (and values are rate-limit
1901            // costs — exchange-specific).
1902            Value::Dict(m) if last_is_verb => {
1903                let verb = crumbs.last().unwrap().to_lowercase();
1904                // Method name uses snake-cased scope (`fapi_public_get_X`).
1905                let scope_snake = Self::api_scope_from_crumbs(&crumbs[..crumbs.len() - 1]);
1906                // But sign()/urls.api lookup uses the original segments
1907                // (camelCase, e.g. `["fapiPublic"]` for binance,
1908                //  `["public","common"]` for bitget, `["public","spot"]`
1909                //  for gate). Preserve as Vec<String> so the dispatcher
1910                //  can choose Value::Str (single) vs Value::Array (multi).
1911                let scope_segments: Vec<String> = crumbs[..crumbs.len() - 1].to_vec();
1912                for (path_key, endpoint_config) in m.iter() {
1913                    let config = match endpoint_config {
1914                        Value::Dict(_) => endpoint_config.clone(),
1915                        Value::Int(_) | Value::Float(_) => Value::Map({
1916                            let mut config = crate::value::HashMap::new();
1917                            config.insert("cost".to_string(), endpoint_config.clone());
1918                            config
1919                        }),
1920                        _ => Value::Map(crate::value::HashMap::new()),
1921                    };
1922                    Self::register_implicit(&verb, &scope_snake, &scope_segments, path_key, config, out);
1923                }
1924            }
1925            Value::Dict(m) => {
1926                for (key, child) in m.iter() {
1927                    let mut next = crumbs.to_vec();
1928                    next.push(key.clone());
1929                    Self::walk_api_node(child, &next, out);
1930                }
1931            }
1932            // Some exchanges use `Array<path-string>` at the verb level.
1933            Value::Arr(a) if last_is_verb => {
1934                let verb = crumbs.last().unwrap().to_lowercase();
1935                let scope_snake = Self::api_scope_from_crumbs(&crumbs[..crumbs.len() - 1]);
1936                let scope_segments: Vec<String> = crumbs[..crumbs.len() - 1].to_vec();
1937                for path in a.iter() {
1938                    let (path_str, config) = match path {
1939                        Value::Str(s) => (s.clone(), Value::Map(crate::value::HashMap::new())),
1940                        Value::Dict(pm) => match pm.get("method").or_else(|| pm.get("path")) {
1941                            Some(Value::Str(s)) => (s.clone(), path.clone()),
1942                            _ => continue,
1943                        },
1944                        _ => continue,
1945                    };
1946                    Self::register_implicit(&verb, &scope_snake, &scope_segments, &path_str, config, out);
1947                }
1948            }
1949            _ => {}
1950        }
1951    }
1952
1953    fn api_scope_from_crumbs(crumbs: &[String]) -> String {
1954        // The scope identifier in TS is camelCase (e.g. `fapiPrivate`),
1955        // but transpiled call sites are snake_case (`fapi_private_get_X`).
1956        // Convert each crumb camelCase → snake_case and join with `_`.
1957        crumbs.iter()
1958            .map(|s| s
1959                .chars()
1960                .enumerate()
1961                .flat_map(|(i, c)| {
1962                    if c.is_ascii_uppercase() && i > 0 {
1963                        vec!['_', c.to_ascii_lowercase()]
1964                    } else {
1965                        vec![c.to_ascii_lowercase()]
1966                    }
1967                })
1968                .collect::<String>())
1969            .collect::<Vec<_>>()
1970            .join("_")
1971    }
1972
1973    fn register_implicit(
1974        verb: &str,
1975        scope_snake: &str,
1976        scope_segments: &[String],
1977        path: &str,
1978        config: Value,
1979        out: &mut HashMap<String, (String, Vec<String>, String, Value)>,
1980    ) {
1981        // CCXT's TS `defineRestApiEndpoint` builds the method name by
1982        // splitting the path on EVERY non-alphanumeric character:
1983        //   `path.split(/[^a-zA-Z0-9]/)` → capitalize each part → join.
1984        // So `:`, `{`, `}`, `/`, `.`, `-` are all separators. Examples:
1985        //   `ticker/24hr`                      → `Ticker24hr` → `ticker24hr`
1986        //   `lending/auto-invest`              → `LendingAutoInvest` → `lending_auto_invest`
1987        //   `candles/trade:{tf}:{sym}/hist`    → `CandlesTradeTfSymHist`
1988        //                                      → `candles_trade_tf_sym_hist`
1989        let camel: String = path
1990            .split(|c: char| !c.is_ascii_alphanumeric())
1991            .filter(|s| !s.is_empty())
1992            .map(|seg| {
1993                let mut chars = seg.chars();
1994                match chars.next() {
1995                    None => String::new(),
1996                    Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
1997                }
1998            })
1999            .collect();
2000        // snake_case from camel: insert `_` between [a-z\d] and [A-Z],
2001        // and between [A-Z]+ and [A-Z][a-z]. Mirrors the transpiler's
2002        // toSnakeCase exactly.
2003        let snake = Self::to_snake_case(&camel);
2004        // An empty path (e.g. nado's `archive: { post: { '': 1 } }`, method
2005        // name `archivePost`) must NOT append a trailing `_` — the transpiled
2006        // call site looks up `archive_post`, not `archive_post_`.
2007        let snake_name = if snake.is_empty() {
2008            format!("{scope_snake}_{verb}")
2009        } else {
2010            format!("{scope_snake}_{verb}_{snake}")
2011        };
2012        // CamelCase variant: `<scope_camel><Verb><PathCamel>` — TS often
2013        // constructs method names dynamically as camelCase (e.g. bit2c's
2014        // `"privatePostOrderAddOrder"`). `self.call_method(name, ...)`
2015        // looks up by exact string, so register both keys.
2016        let scope_camel: String = scope_segments.iter()
2017            .enumerate()
2018            .map(|(i, s)| {
2019                if i == 0 {
2020                    s.to_string()
2021                } else {
2022                    let mut chars = s.chars();
2023                    match chars.next() {
2024                        None => String::new(),
2025                        Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
2026                    }
2027                }
2028            })
2029            .collect();
2030        let verb_camel = {
2031            let mut chars = verb.chars();
2032            match chars.next() {
2033                None => String::new(),
2034                Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str().to_lowercase().as_str(),
2035            }
2036        };
2037        let camel_name = format!("{scope_camel}{verb_camel}{camel}");
2038        // Snake-cased from the WHOLE camel name, which is what the transpiler
2039        // does to produce the call site. It usually equals `snake_name` above,
2040        // but the two diverge when a path segment starts with a digit: joining
2041        // pre-snaked parts forces a separator the transpiler never inserts, so
2042        // revolutx's `1.0/public/tickers` registers as
2043        // `public_get_10_public_tickers` while the generated code calls
2044        // `public_get10_public_tickers` (toSnakeCase puts no `_` between a
2045        // digit and the preceding letter). Register both spellings so either
2046        // resolves.
2047        let camel_snake_name = Self::to_snake_case(&camel_name);
2048        let entry = (path.to_string(), scope_segments.to_vec(), verb.to_uppercase(), config);
2049        out.insert(snake_name, entry.clone());
2050        if !out.contains_key(&camel_snake_name) {
2051            out.insert(camel_snake_name, entry.clone());
2052        }
2053        if !out.contains_key(&camel_name) {
2054            out.insert(camel_name, entry);
2055        }
2056    }
2057
2058    fn to_snake_case(s: &str) -> String {
2059        // 1st pass: `[A-Z]+([A-Z][a-z])` → `$1_$2`
2060        let bytes: Vec<char> = s.chars().collect();
2061        let mut out = String::with_capacity(s.len() + 4);
2062        for i in 0..bytes.len() {
2063            let c = bytes[i];
2064            let prev = if i > 0 { Some(bytes[i - 1]) } else { None };
2065            let next = if i + 1 < bytes.len() { Some(bytes[i + 1]) } else { None };
2066            if c.is_ascii_uppercase() {
2067                let prev_lower_or_digit = prev
2068                    .map(|p| p.is_ascii_lowercase() || p.is_ascii_digit())
2069                    .unwrap_or(false);
2070                let prev_upper = prev.map(|p| p.is_ascii_uppercase()).unwrap_or(false);
2071                let next_lower = next.map(|n| n.is_ascii_lowercase()).unwrap_or(false);
2072                if prev_lower_or_digit {
2073                    out.push('_');
2074                } else if prev_upper && next_lower {
2075                    out.push('_');
2076                }
2077            }
2078            out.push(c.to_ascii_lowercase());
2079        }
2080        // Collapse any `__` runs introduced by underscores already in input.
2081        while out.contains("__") {
2082            out = out.replace("__", "_");
2083        }
2084        out.trim_matches('_').to_string()
2085    }
2086
2087    /// Resolves the base URL for a given api scope. Looks up
2088    /// `urls.api.<scope>`; if that's itself a map, prefers `rest`.
2089    fn url_for_scope(&self, scope: &str) -> Option<String> {
2090        let api = crate::get_value(&self.urls, &Value::Str("api".into()));
2091        // Try scoped first (binance-style: urls.api.public, urls.api.private).
2092        let scoped = crate::get_value(&api, &Value::Str(scope.to_string().into()));
2093        let raw = match scoped {
2094            Value::Str(s) => s,
2095            Value::Dict(m) => match m.get("rest").or_else(|| m.get("current")) {
2096                Some(Value::Str(s)) => s.clone(),
2097                _ => return self.fallback_rest_url(&api),
2098            },
2099            _ => return self.fallback_rest_url(&api),
2100        };
2101        Some(self.implode_hostname_typed(&raw))
2102    }
2103
2104    /// Many exchanges (okx, kucoin, bitget, gate, hyperliquid, …) use
2105    /// a single `urls.api.rest` URL for all scopes. Fall back to it
2106    /// when the per-scope lookup misses.
2107    fn fallback_rest_url(&self, api: &Value) -> Option<String> {
2108        let rest = crate::get_value(api, &Value::Str("rest".into()));
2109        if let Value::Str(s) = rest {
2110            return Some(self.implode_hostname_typed(&s));
2111        }
2112        // Last resort: if urls.api itself is a string, use it.
2113        if let Value::Str(s) = api {
2114            return Some(self.implode_hostname_typed(s));
2115        }
2116        None
2117    }
2118
2119    /// Internal typed `{hostname}` substitution.
2120    fn implode_hostname_typed(&self, url: &str) -> String {
2121        let host = match &self.hostname {
2122            Value::Str(s) => s.clone(),
2123            _ => return url.to_string(),
2124        };
2125        url.replace("{hostname}", &host)
2126    }
2127
2128    // Dispatches an implicit API call. Looks the method up in the dispatch
2129    // table (building it on first use) and routes through `request`.
2130    // Public-endpoint request: imploding params into the path/query and
2131    // hitting `fetch`. Private endpoints need per-exchange signing — for
2132    // now we treat anything outside `public` as a stub that returns Null.
2133    fn extract_path_params(&self, path: &str) -> Vec<String> {
2134        let mut out: Vec<String> = vec![];
2135        let mut chars = path.chars().peekable();
2136        while let Some(c) = chars.next() {
2137            if c == '{' {
2138                let mut name = String::new();
2139                while let Some(&nc) = chars.peek() {
2140                    if nc == '}' { chars.next(); break; }
2141                    name.push(nc); chars.next();
2142                }
2143                if !name.is_empty() { out.push(name); }
2144            }
2145        }
2146        out
2147    }
2148}
2149
2150/// Raw digest bytes for a named hash algorithm — includes Keccak-256
2151/// (`keccak`), used by ETH-style signing (hyperliquid, etc.).
2152pub(crate) fn hash_raw(data: &[u8], algo: &str) -> Vec<u8> {
2153    match algo.to_ascii_lowercase().as_str() {
2154        "sha256" => { let mut h = Sha256::new(); h.update(data); h.finalize().to_vec() }
2155        "sha512" => { let mut h = Sha512::new(); h.update(data); h.finalize().to_vec() }
2156        "sha1"   => { let mut h = Sha1::new();   h.update(data); h.finalize().to_vec() }
2157        "md5"    => { let mut h = Md5::new();    h.update(data); h.finalize().to_vec() }
2158        "keccak" | "keccak256" => {
2159            use sha3::{Keccak256, Digest as _};
2160            let mut h = Keccak256::new();
2161            h.update(data);
2162            h.finalize().to_vec()
2163        }
2164        _ => Vec::new(),
2165    }
2166}
2167
2168/// EIP-712 `encode` — produces the `\x19\x01 || domainSeparator ||
2169/// hashStruct(message)` preimage. The caller keccak-hashes this into the
2170/// 32-byte digest that gets ECDSA-signed (hyperliquid, etc.).
2171type Eip712Types = std::collections::BTreeMap<String, Vec<(String, String)>>;
2172
2173/// Strip a trailing `[...]` array suffix from an EIP-712 field type, so
2174/// `Order[]` and `Order` both resolve to the struct name `Order`.
2175fn eip712_base_type(ty: &str) -> &str {
2176    match ty.find('[') { Some(i) => &ty[..i], None => ty }
2177}
2178
2179/// EIP-712 `encodeType`: the primary type's signature followed by every
2180/// referenced struct type, sorted alphabetically (per the spec), so a nested
2181/// `TypedDataSign(Order contents,…)` correctly appends `Order(uint256 salt,…)`.
2182fn eip712_encode_type(primary: &str, types: &Eip712Types) -> String {
2183    fn collect(name: &str, types: &Eip712Types, deps: &mut std::collections::BTreeSet<String>) {
2184        if let Some(fields) = types.get(name) {
2185            for (_, ty) in fields {
2186                let base = eip712_base_type(ty).to_string();
2187                if types.contains_key(&base) && deps.insert(base.clone()) {
2188                    collect(&base, types, deps);
2189                }
2190            }
2191        }
2192    }
2193    let fmt = |name: &str| -> String {
2194        let fields = types.get(name).cloned().unwrap_or_default();
2195        let inner: Vec<String> = fields.iter().map(|(n, t)| format!("{t} {n}")).collect();
2196        format!("{}({})", name, inner.join(","))
2197    };
2198    let mut deps = std::collections::BTreeSet::new();
2199    collect(primary, types, &mut deps);
2200    deps.remove(primary);
2201    let mut out = fmt(primary);
2202    for dep in &deps { out.push_str(&fmt(dep)); } // BTreeSet iterates sorted
2203    out
2204}
2205
2206pub(crate) fn eip712_encode(domain: &Value, types: &Value, message: &Value) -> Vec<u8> {
2207    let dm = match domain { Value::Dict(m) => m, _ => return Vec::new() };
2208    // EIP712Domain field set — canonical order, only the keys present.
2209    let mut domain_fields: Vec<(String, String)> = Vec::new();
2210    for (n, t) in [("name", "string"), ("version", "string"), ("chainId", "uint256"),
2211                   ("verifyingContract", "address"), ("salt", "bytes32")] {
2212        if dm.contains_key(n) { domain_fields.push((n.to_string(), t.to_string())); }
2213    }
2214    // Domain has no nested structs — a flat (empty type-map) hash.
2215    let mut domain_types: Eip712Types = Eip712Types::new();
2216    domain_types.insert("EIP712Domain".to_string(), domain_fields);
2217    let domain_sep = eip712_hash_struct("EIP712Domain", domain, &domain_types);
2218
2219    // Collect all user-defined types (name → fields), excluding EIP712Domain.
2220    let mut type_map: Eip712Types = Eip712Types::new();
2221    if let Value::Dict(m) = types {
2222        for (name, def) in m.iter() {
2223            if name == "EIP712Domain" { continue; }
2224            if let Value::Arr(arr) = def {
2225                let fields: Vec<(String, String)> = arr.iter().filter_map(|it| match it {
2226                    Value::Dict(fm) => Some((
2227                        fm.get("name")?.as_str()?.to_string(),
2228                        fm.get("type")?.as_str()?.to_string(),
2229                    )),
2230                    _ => None,
2231                }).collect();
2232                type_map.insert(name.clone(), fields);
2233            }
2234        }
2235    }
2236    if type_map.is_empty() { return Vec::new(); }
2237    // Primary type = the one not referenced as a field type by any other type
2238    // (the top-level struct). Falls back to the first key.
2239    let referenced: std::collections::HashSet<String> = type_map.values()
2240        .flat_map(|fs| fs.iter().map(|(_, t)| eip712_base_type(t).to_string()))
2241        .collect();
2242    let primary = type_map.keys().find(|k| !referenced.contains(*k)).cloned()
2243        .unwrap_or_else(|| type_map.keys().next().cloned().unwrap_or_default());
2244    let struct_hash = eip712_hash_struct(&primary, message, &type_map);
2245    let mut out = vec![0x19u8, 0x01u8];
2246    out.extend_from_slice(&domain_sep);
2247    out.extend_from_slice(&struct_hash);
2248    out
2249}
2250
2251/// EIP-712 `hashStruct(typeName, data)`: keccak(typeHash ‖ encoded-fields),
2252/// where a field whose type is itself a struct in `types` is hashed recursively.
2253fn eip712_hash_struct(type_name: &str, data: &Value, types: &Eip712Types) -> Vec<u8> {
2254    let type_str = eip712_encode_type(type_name, types);
2255    let mut enc = hash_raw(type_str.as_bytes(), "keccak"); // typeHash (32 bytes)
2256    let dm = match data { Value::Dict(m) => Some(m), _ => None };
2257    let fields = types.get(type_name).cloned().unwrap_or_default();
2258    for (name, ty) in &fields {
2259        let v = dm.and_then(|m| m.get(name)).cloned().unwrap_or(Value::Null);
2260        let base = eip712_base_type(ty);
2261        if types.contains_key(base) {
2262            // Nested struct field — recurse.
2263            enc.extend_from_slice(&eip712_hash_struct(base, &v, types));
2264        } else {
2265            enc.extend_from_slice(&eip712_encode_value(ty, &v));
2266        }
2267    }
2268    hash_raw(&enc, "keccak")
2269}
2270
2271/// Encodes an integer into a 32-byte EIP-712 / ABI word for a `uintN`/`intN`
2272/// type, validating the declared bit width. Fails closed (panics) on a negative
2273/// value in an unsigned type, or any value that overflows the declared width,
2274/// instead of silently truncating to 32 bytes or routing a negative through the
2275/// unsigned branch (review #15). Valid, in-range values encode exactly as
2276/// before (big-endian right-aligned for uint; two's-complement sign-extended
2277/// for int), so signing of well-formed payloads is unchanged.
2278pub(crate) fn eip712_int_word(ty: &str, n: &num_bigint::BigInt) -> [u8; 32] {
2279    use num_bigint::{BigInt, Sign};
2280    let signed = ty.starts_with("int");
2281    let digits = ty.trim_start_matches(if signed { "int" } else { "uint" });
2282    let mut width: usize = if digits.is_empty() { 256 } else { digits.parse().unwrap_or(256) };
2283    if !((8..=256).contains(&width) && width % 8 == 0) { width = 256; }
2284    let mut out = [0u8; 32];
2285    if !signed {
2286        if n.sign() == Sign::Minus {
2287            panic!("eip712/abi: negative value {n} supplied for unsigned type {ty}");
2288        }
2289        let max = (BigInt::from(1) << width) - 1;
2290        if n > &max {
2291            panic!("eip712/abi: value {n} overflows {ty} (max {max})");
2292        }
2293        let (_, be) = n.to_bytes_be();
2294        let take = be.len().min(32);
2295        out[32 - take..].copy_from_slice(&be[be.len() - take..]);
2296    } else {
2297        let min = -(BigInt::from(1) << (width - 1));
2298        let max = (BigInt::from(1) << (width - 1)) - 1;
2299        if n < &min || n > &max {
2300            panic!("eip712/abi: value {n} out of range for {ty} ([{min}, {max}])");
2301        }
2302        if n.sign() == Sign::Minus { out = [0xff; 32]; }
2303        let be = n.to_signed_bytes_be();
2304        let take = be.len().min(32);
2305        out[32 - take..].copy_from_slice(&be[be.len() - take..]);
2306    }
2307    out
2308}
2309
2310fn eip712_encode_value(ty: &str, v: &Value) -> [u8; 32] {
2311    let mut out = [0u8; 32];
2312    if ty == "string" || ty == "bytes" {
2313        out.copy_from_slice(&hash_raw(&value_to_bytes(v), "keccak"));
2314    } else if ty.starts_with("bytes") {
2315        // bytesN — left-aligned.
2316        let b = eip712_bytes(v);
2317        let n = b.len().min(32);
2318        out[..n].copy_from_slice(&b[..n]);
2319    } else if ty == "address" {
2320        // 20-byte address, right-aligned (left-padded with zeros).
2321        let b = eip712_bytes(v);
2322        let take = b.len().min(20);
2323        out[32 - take..].copy_from_slice(&b[b.len() - take..]);
2324    } else if ty == "bool" {
2325        if matches!(v, Value::Bool(true)) { out[31] = 1; }
2326    } else if ty.starts_with("uint") || ty.starts_with("int") {
2327        // uint256 (e.g. polymarket tokenId) exceeds u128 — use BigInt. Signed
2328        // intN uses two's-complement, sign-extended to 32 bytes.
2329        use num_bigint::BigInt;
2330        let n: BigInt = match v {
2331            Value::Int(i)   => BigInt::from(*i),
2332            Value::Float(f) => BigInt::from(*f as i64),
2333            Value::Str(s)   => {
2334                let t = s.trim();
2335                if let Some(h) = t.strip_prefix("0x") {
2336                    BigInt::parse_bytes(h.as_bytes(), 16).unwrap_or_default()
2337                } else {
2338                    BigInt::parse_bytes(t.as_bytes(), 10).unwrap_or_default()
2339                }
2340            }
2341            _ => BigInt::from(0),
2342        };
2343        out = eip712_int_word(ty, &n);
2344    }
2345    out
2346}
2347
2348/// Decode an EIP-712 byte value: a `0x`-hex string or a byte-array Value.
2349fn eip712_bytes(v: &Value) -> Vec<u8> {
2350    match v {
2351        Value::Str(s) => {
2352            let h = s.strip_prefix("0x").unwrap_or(s);
2353            hex::decode(h).unwrap_or_else(|_| s.as_bytes().to_vec())
2354        }
2355        _ => value_to_bytes(v),
2356    }
2357}
2358
2359pub(crate) fn value_to_bytes(v: &Value) -> Vec<u8> {
2360    match v {
2361        Value::Str(s) => s.as_bytes().to_vec(),
2362        Value::Arr(a) => a.iter().filter_map(|x| match x {
2363            Value::Int(n) => Some(*n as u8),
2364            _ => None,
2365        }).collect(),
2366        _ => Vec::new(),
2367    }
2368}
2369
2370pub(crate) fn url_pct(s: &str) -> String {
2371    s.bytes().map(|b| match b {
2372        b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
2373        _ => format!("%{b:02X}"),
2374    }).collect()
2375}
2376
2377/// Pins the `mock_response` contract that `request_typed` implements: the canned
2378/// payload is returned by `fetch_typed` only AFTER the request has been built and
2379/// signed, so `last_request_url` / `_headers` / `_body` still describe the real
2380/// request a static *response* fixture would have sent; and the payload stays set
2381/// until the caller replaces or clears it, so one fixture can serve the several
2382/// `fetch_typed` calls a single paginating `fetchX` issues.
2383#[cfg(all(test, feature = "transpiled-base"))]
2384mod response_mock_tests {
2385    use super::ExchangeRuntime;
2386    use crate::{get_value, Value};
2387
2388    #[tokio::test]
2389    async fn response_mock_serves_multiple_requests_until_reset() {
2390        // Conflicting proxies reject any unmocked request before network I/O.
2391        let config = Value::from_json(&serde_json::json!({
2392            "httpProxy": "http://fake:8080", "httpsProxy": "http://fake:8080",
2393            "enableRateLimit": false,
2394        }));
2395        let mut exchange = crate::exchanges::binance::BinanceCore::new(Some(config));
2396        let response = Value::from_json(&serde_json::json!({ "price": "100" }));
2397        exchange.exchange.mock_response = response.clone();
2398        for symbol in ["BTCUSDT", "ETHUSDT"] {
2399            let params = Value::from_json(&serde_json::json!({ "symbol": symbol }));
2400            let result = exchange.request_typed(
2401                "ticker/price", &["public".to_string()], "GET", params, Value::Int(1),
2402            ).await.expect("each request must use the same mock without network access");
2403            assert_eq!(result, response);
2404            assert_eq!(exchange.exchange.last_request_url, Value::Str(format!(
2405                "https://api.binance.com/api/v3/ticker/price?symbol={symbol}",
2406            ).into()));
2407        }
2408        exchange.exchange.mock_response = Value::Null;
2409        let error = exchange.request_typed(
2410            "ticker/price", &["public".to_string()], "GET", Value::Null, Value::Int(1),
2411        ).await.expect_err("reset must restore the normal transport path");
2412        assert!(error.to_string().contains("InvalidProxySettings"));
2413    }
2414
2415    #[tokio::test]
2416    async fn response_mock_preserves_public_request_url() {
2417        let mut exchange = crate::exchanges::binance::BinanceCore::new(None);
2418        let response = Value::from_json(&serde_json::json!({ "price": "100" }));
2419        exchange.exchange.mock_response = response.clone();
2420        let params = Value::from_json(&serde_json::json!({ "symbol": "BTCUSDT" }));
2421        let result = exchange.request_typed(
2422            "ticker/price", &["public".to_string()], "GET", params, Value::Int(1),
2423        ).await.expect("mock response must not require network access");
2424        assert_eq!(result, response);
2425        assert_eq!(exchange.exchange.last_request_url, Value::Str(
2426            "https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT".into(),
2427        ));
2428        assert_eq!(exchange.exchange.last_request_body, Value::Null);
2429    }
2430
2431    #[tokio::test]
2432    async fn response_mock_preserves_private_request_headers_and_body() {
2433        let config = Value::from_json(&serde_json::json!({
2434            "apiKey": "fixture-key", "secret": "fixture-secret",
2435        }));
2436        let mut exchange = crate::exchanges::binance::BinanceCore::new(Some(config));
2437        let response = Value::from_json(&serde_json::json!({ "orderId": 123 }));
2438        exchange.exchange.mock_response = response.clone();
2439        let params = Value::from_json(&serde_json::json!({
2440            "symbol": "BTCUSDT", "side": "BUY", "type": "MARKET", "quantity": "1",
2441        }));
2442        let result = exchange.request_typed(
2443            "order", &["private".to_string()], "POST", params, Value::Int(1),
2444        ).await.expect("signed mock response must not require network access");
2445        assert_eq!(result, response);
2446        assert_eq!(exchange.exchange.last_request_url, Value::Str(
2447            "https://api.binance.com/api/v3/order".into(),
2448        ));
2449        assert_eq!(get_value(&exchange.exchange.last_request_headers,
2450            &Value::Str("X-MBX-APIKEY".into())), Value::Str("fixture-key".into()));
2451        let Value::Str(body) = &exchange.exchange.last_request_body else {
2452            panic!("signed POST must retain its encoded body");
2453        };
2454        assert!(body.contains("symbol=BTCUSDT"));
2455        assert!(body.contains("signature="));
2456    }
2457}
2458
2459/// Pins `method_name_to_snake_case` — the transform that decides whether a
2460/// paginated `this[method](...)` re-entry lands on a `call_dynamic` arm — against
2461/// the two implementations it must agree with: the transpiler's `toSnakeCase`
2462/// (`build/rustTranspiler.ts`, which names the arms) and `Exchange::to_snake_case`
2463/// (which names the implicit-API entries the `_` arm falls through to).
2464/// Requested in review on #30385.
2465#[cfg(test)]
2466mod method_name_snake_case_tests {
2467    use super::{method_name_to_snake_case, Exchange};
2468    use crate::Value;
2469
2470    fn snake(name: &str) -> String {
2471        method_name_to_snake_case(&Value::Str(name.to_string().into()))
2472    }
2473
2474    // The four names the review called out, plus the digit/acronym shapes that
2475    // are the only places the three transforms could plausibly diverge.
2476    #[test]
2477    fn matches_the_transpiler_dispatch_arm_names() {
2478        // unified methods re-entered by fetchPaginatedCall* — these must hit an arm
2479        assert_eq!(snake("fetchTransfers"), "fetch_transfers");
2480        assert_eq!(snake("fetchOHLCV"), "fetch_ohlcv");                 // trailing acronym
2481        assert_eq!(snake("fetchOpenOrdersWs"), "fetch_open_orders_ws");
2482        assert_eq!(snake("fetchL2OrderBook"), "fetch_l2_order_book");   // letter+digit token
2483        assert_eq!(snake("getLeverageTiersPaginated"), "get_leverage_tiers_paginated");
2484        // implicit endpoints re-entered by fetchWebEndpoint — these must hit the
2485        // `_` arm's implicit_api lookup, which is keyed by to_snake_case
2486        assert_eq!(snake("publicGetTicker24hr"), "public_get_ticker24hr"); // NO `_` before a digit
2487        assert_eq!(snake("webExchangeGetV3Assets"), "web_exchange_get_v3_assets");
2488        assert_eq!(snake("webApiGetAjaxCoinCoinInfo"), "web_api_get_ajax_coin_coin_info");
2489        // acronym runs: `[A-Z]+[A-Z][a-z]` splits before the last capital only
2490        assert_eq!(snake("parseHTTPResponse"), "parse_http_response");
2491        assert_eq!(snake("fetchOHLCVWs"), "fetch_ohlcv_ws");
2492        // already-snake and single-token names are pass-through
2493        assert_eq!(snake("fetch"), "fetch");
2494        assert_eq!(snake("fetch_transfers"), "fetch_transfers");
2495    }
2496
2497    // `method_name_to_snake_case` and `Exchange::to_snake_case` must produce the
2498    // SAME key, or a dynamic name would snake to something the implicit-api map
2499    // does not hold. Differential over the shapes above; the full 11k-name sweep
2500    // over every ts/src method + abstract endpoint also reports zero divergence.
2501    #[test]
2502    fn agrees_with_exchange_to_snake_case() {
2503        for name in [
2504            "fetchTransfers", "fetchOHLCV", "fetchOpenOrdersWs", "publicGetTicker24hr",
2505            "fetchL2OrderBook", "webExchangeGetV3Assets", "webApiGetAjaxCoinCoinInfo",
2506            "parseHTTPResponse", "fetchOHLCVWs", "privatePostSPEIWithdrawal",
2507            "sapiV3GetAsset", "fapiPublicGetTicker24hr", "publicGet10PublicTickers",
2508            "fetch", "fetchPositionsRisk", "createOrderWs", "fetchMyLiquidations",
2509        ] {
2510            assert_eq!(
2511                snake(name),
2512                Exchange::to_snake_case(name),
2513                "method_name_to_snake_case and Exchange::to_snake_case diverge on {name}",
2514            );
2515        }
2516    }
2517
2518    // A non-string / empty dynamic name used to snake to "" and then resolve to
2519    // Value::Null — a silent empty page. It must be loud instead.
2520    #[test]
2521    #[should_panic(expected = "NotSupported")]
2522    fn non_string_method_name_is_loud() {
2523        let _ = method_name_to_snake_case(&Value::Int(7));
2524    }
2525
2526    #[test]
2527    #[should_panic(expected = "NotSupported")]
2528    fn empty_method_name_is_loud() {
2529        let _ = method_name_to_snake_case(&Value::Str(String::new().into()));
2530    }
2531}
2532
2533#[cfg(test)]
2534mod eip712_int_tests {
2535    use super::eip712_int_word;
2536    use num_bigint::BigInt;
2537
2538    #[test]
2539    fn uint8_max_ok_and_int8_bounds_ok() {
2540        assert_eq!(eip712_int_word("uint8", &BigInt::from(255))[31], 255);
2541        let _ = eip712_int_word("int8", &BigInt::from(127));
2542        let _ = eip712_int_word("int8", &BigInt::from(-128));
2543    }
2544
2545    #[test]
2546    fn i64_u64_boundaries_ok() {
2547        let _ = eip712_int_word("int64", &BigInt::from(i64::MAX));
2548        let _ = eip712_int_word("int64", &BigInt::from(i64::MIN));
2549        let _ = eip712_int_word("uint64", &BigInt::from(u64::MAX));
2550    }
2551
2552    // u64::MAX + 1 (2^64) must fit a uint256 exactly: 0x01 followed by 8 zero
2553    // bytes, right-aligned → byte index 23.
2554    #[test]
2555    fn u64_plus_one_preserved_in_uint256() {
2556        let n = BigInt::from(u64::MAX) + 1;
2557        assert_eq!(eip712_int_word("uint256", &n)[23], 1);
2558    }
2559
2560    #[test]
2561    fn negative_int_is_twos_complement() {
2562        assert_eq!(eip712_int_word("int256", &BigInt::from(-1)), [0xff; 32]);
2563    }
2564
2565    #[test]
2566    #[should_panic(expected = "overflows")]
2567    fn uint8_overflow_rejected() { let _ = eip712_int_word("uint8", &BigInt::from(256)); }
2568
2569    #[test]
2570    #[should_panic(expected = "negative")]
2571    fn uint_negative_rejected() { let _ = eip712_int_word("uint256", &BigInt::from(-1)); }
2572
2573    #[test]
2574    #[should_panic(expected = "out of range")]
2575    fn int8_overflow_rejected() { let _ = eip712_int_word("int8", &BigInt::from(128)); }
2576
2577    #[test]
2578    #[should_panic(expected = "overflows")]
2579    fn uint64_plus_one_rejected() {
2580        let _ = eip712_int_word("uint64", &(BigInt::from(u64::MAX) + 1));
2581    }
2582}
2583
2584#[cfg(test)]
2585mod throttle_tests {
2586    use super::Exchange;
2587    use crate::Value;
2588
2589    #[test]
2590    fn implicit_api_retains_endpoint_cost_config() {
2591        let mut by_limit = crate::value::HashMap::new();
2592        by_limit.insert("cost".to_string(), Value::Int(2));
2593        by_limit.insert("byLimit".to_string(), Value::List(vec![
2594            Value::List(vec![Value::Int(100), Value::Int(5)]),
2595        ]));
2596        let mut endpoints = crate::value::HashMap::new();
2597        endpoints.insert("ticker".to_string(), Value::Float(0.1));
2598        endpoints.insert("depth".to_string(), Value::Map(by_limit.clone()));
2599        let mut verbs = crate::value::HashMap::new();
2600        verbs.insert("get".to_string(), Value::Map(endpoints));
2601        let mut api = crate::value::HashMap::new();
2602        api.insert("public".to_string(), Value::Map(verbs));
2603        let mut exchange = Exchange::new(None);
2604        exchange.api = Value::Map(api);
2605        exchange.build_implicit_api();
2606        let ticker_config = &exchange.internals.implicit_api["public_get_ticker"].3;
2607        assert_eq!(
2608            crate::get_value(ticker_config, &Value::Str("cost".into())),
2609            Value::Float(0.1),
2610            "numeric endpoint costs must be normalized to a config object"
2611        );
2612        let depth_config = &exchange.internals.implicit_api["public_get_depth"].3;
2613        assert_eq!(depth_config, &Value::Map(by_limit), "object endpoint config must be retained");
2614    }
2615
2616    // The leaky-bucket limiter must space requests by ~rateLimit ms (real time).
2617    #[tokio::test]
2618    async fn spaces_requests_by_rate_limit() {
2619        let mut ex = Exchange::new(None);
2620        ex.enableRateLimit = Value::Bool(true);
2621        ex.rateLimit = Value::Int(15); // 15 ms per token
2622        let start = std::time::Instant::now();
2623        for _ in 0..5 { ex.throttle(&[]).await; }
2624        let elapsed = start.elapsed().as_millis();
2625        // 1st immediate, next 4 each wait ~15ms → ≥ ~45ms (generous lower bound).
2626        assert!(elapsed >= 45, "throttle did not space requests: {elapsed}ms");
2627    }
2628
2629    // Disabled rate limiting must not sleep at all.
2630    #[tokio::test]
2631    async fn disabled_is_noop() {
2632        let mut ex = Exchange::new(None);
2633        ex.enableRateLimit = Value::Bool(false);
2634        ex.rateLimit = Value::Int(1000);
2635        let start = std::time::Instant::now();
2636        for _ in 0..5 { ex.throttle(&[]).await; }
2637        assert!(start.elapsed().as_millis() < 50, "disabled throttle slept");
2638    }
2639}
2640
2641#[cfg(all(test, feature = "transpiled-base"))]
2642mod rate_limit_config_tests {
2643    use crate::exchange::ExchangeRuntime;
2644    use crate::exchange_generated::ExchangeBase;
2645    use crate::Value;
2646
2647    // init() must apply describe().rateLimit so the limiter spaces requests at
2648    // the venue rate instead of the base 2000ms default (review #8). binance
2649    // declares rateLimit: 50.
2650    #[test]
2651    fn binance_init_applies_describe_rate_limit() {
2652        let b = crate::exchanges::binance::BinanceCore::new(None);
2653        assert_eq!(
2654            b.exchange.rateLimit,
2655            Value::Int(50),
2656            "init() dropped describe().rateLimit; got {:?}",
2657            b.exchange.rateLimit
2658        );
2659    }
2660
2661    // A caller-supplied rateLimit must win over describe()'s value.
2662    #[test]
2663    fn config_rate_limit_overrides_describe() {
2664        let mut cfg = crate::value::HashMap::new();
2665        cfg.insert("rateLimit".to_string(), Value::Int(123));
2666        let b = crate::exchanges::binance::BinanceCore::new(Some(Value::Map(cfg)));
2667        assert_eq!(b.exchange.rateLimit, Value::Int(123), "config rateLimit was clobbered by describe()");
2668    }
2669
2670    #[tokio::test]
2671    async fn implicit_api_preserves_and_calculates_endpoint_cost() {
2672        let mut binance = crate::exchanges::binance::BinanceCore::new(None);
2673        binance.build_implicit_api();
2674        let config = binance
2675            .exchange
2676            .internals
2677            .implicit_api
2678            .get("fapi_public_get_depth")
2679            .expect("Binance futures depth endpoint must be registered")
2680            .3
2681            .clone();
2682        assert_eq!(
2683            crate::get_value(&config, &Value::Str("cost".into())),
2684            Value::Int(2),
2685            "the implicit API table dropped the endpoint's base cost"
2686        );
2687        let params = Value::Map({
2688            let mut map = crate::value::HashMap::new();
2689            map.insert("limit".to_string(), Value::Int(100));
2690            map
2691        });
2692        let cost = binance
2693            .implicit_api_rate_limit_cost("fapi_public_get_depth", params)
2694            .await
2695            .expect("registered endpoint must have a calculable cost");
2696        assert_eq!(cost, Value::Int(5), "Binance byLimit cost was not applied");
2697    }
2698}
2699
2700#[cfg(all(test, feature = "transpiled-base"))]
2701mod sandbox_mode_tests {
2702    use crate::Value;
2703
2704    // super_set_sandbox_mode was a no-op, so venues that override setSandboxMode
2705    // (binance, okx, gate, …) never actually switched to their sandbox URL
2706    // (review #9). After delegating to the base, set_sandbox_mode(true) must
2707    // swap urls['api'] -> urls['test'] and toggle isSandboxModeEnabled.
2708    #[test]
2709    fn binance_sandbox_swaps_api_url() {
2710        let mut b = crate::exchanges::binance::BinanceCore::new(None);
2711        let test_url = crate::get_value(&b.exchange.urls, &Value::Str("test".into()));
2712        assert!(!matches!(test_url, Value::Null), "binance describe() has no test url");
2713        b.set_sandbox_mode(Value::Bool(true));
2714        assert_eq!(b.exchange.isSandboxModeEnabled, Value::Bool(true));
2715        let api_url = crate::get_value(&b.exchange.urls, &Value::Str("api".into()));
2716        assert_eq!(api_url, test_url, "sandbox mode did not switch urls['api'] to urls['test']");
2717    }
2718}
2719
2720#[cfg(all(test, feature = "transpiled-base"))]
2721mod dynamic_dispatch_tests {
2722    use crate::exchange::CallDynamicChecked;
2723    use crate::exchange_generated::ExchangeBase;
2724    use crate::Value;
2725
2726    // The three behaviours the review on #30385 asked for, on the real dispatch
2727    // table (binance's Core) rather than on the name transform alone.
2728
2729    // 1. A unified method re-entered dynamically — the case the PR fixes — must
2730    //    reach a dispatch arm and NOT the `_ => Null` fall-through.
2731    //    `call_method` could never resolve `fetchOHLCV` (it only knows implicit
2732    //    endpoints), so pagination hard-failed with NotSupported. Probe the
2733    //    fall-through directly: dispatch the name and require that the `_` arm
2734    //    did not record a miss for it, which is only true when a real arm
2735    //    matched. `fetch_ohlcv` with no args returns without any network I/O
2736    //    (binance's override throws ArgumentsRequired on a null symbol), so
2737    //    catch the unwind and inspect the miss flag rather than the result.
2738    #[tokio::test]
2739    async fn unified_method_reaches_a_dispatch_arm_not_the_null_fallthrough() {
2740        let mut b = crate::exchanges::binance::BinanceCore::new(None);
2741        let snake = crate::exchange::method_name_to_snake_case(
2742            &Value::Str("fetchOHLCV".into()));
2743        assert_eq!(snake, "fetch_ohlcv");
2744        b.exchange.internals.dynamic_dispatch_miss = None;
2745        let _ = futures::FutureExt::catch_unwind(
2746            std::panic::AssertUnwindSafe(b.call_dynamic(&snake, vec![])),
2747        ).await;
2748        assert_eq!(
2749            b.exchange.internals.dynamic_dispatch_miss, None,
2750            "`{snake}` fell through to the `_ => Null` arm — a paginated \
2751             re-entry would have silently returned an empty page",
2752        );
2753        // Negative control for the probe itself: a name with no arm DOES record.
2754        let _ = b.call_dynamic("fetch_definitely_not_an_arm", vec![]).await;
2755        assert_eq!(
2756            b.exchange.internals.dynamic_dispatch_miss.as_deref(),
2757            Some("fetch_definitely_not_an_arm"),
2758            "the miss probe is inert — the assertion above proves nothing",
2759        );
2760    }
2761
2762    // 2. An implicit endpoint re-entered dynamically (fetchWebEndpoint's
2763    //    endpointMethod) still routes through the `_` arm's implicit_api
2764    //    lookup — the PR must not have broken direct implicit calls.
2765    #[tokio::test]
2766    async fn implicit_endpoint_is_still_reachable_and_is_not_a_miss() {
2767        let mut b = crate::exchanges::binance::BinanceCore::new(None);
2768        b.exchange.build_implicit_api();
2769        let snake = crate::exchange::method_name_to_snake_case(
2770            &Value::Str("publicGetTicker24hr".into()));
2771        assert!(
2772            b.exchange.internals.implicit_api.contains_key(&snake),
2773            "implicit api has no `{snake}` entry — the `_` arm would treat a real \
2774             endpoint as an unknown name",
2775        );
2776    }
2777
2778    // 3. THE REGRESSION GUARD. A name that is neither a dispatch arm nor an
2779    //    implicit endpoint used to yield `Value::Null` — a silent empty page.
2780    //    `call_dynamic_checked` must turn it back into a loud NotSupported,
2781    //    the way `call_method` used to fail.
2782    #[tokio::test]
2783    #[should_panic(expected = "NotSupported")]
2784    async fn unknown_dynamic_name_is_loud_not_null() {
2785        let mut b = crate::exchanges::binance::BinanceCore::new(None);
2786        let _ = b.call_dynamic_checked(
2787            Value::Str("fetchNoSuchThingAtAll".into()),
2788            vec![],
2789        ).await;
2790    }
2791
2792    // …and the bare `call_dynamic` it wraps still returns Null for that name,
2793    // so the loudness comes from the wrapper and optional probes stay cheap.
2794    #[tokio::test]
2795    async fn bare_call_dynamic_still_returns_null_for_optional_probes() {
2796        let mut b = crate::exchanges::binance::BinanceCore::new(None);
2797        let out = b.call_dynamic("fetch_no_such_thing_at_all", vec![]).await;
2798        assert_eq!(out, Value::Null);
2799        assert_eq!(
2800            b.exchange.internals.dynamic_dispatch_miss.as_deref(),
2801            Some("fetch_no_such_thing_at_all"),
2802            "the `_` arm did not record the miss, so call_dynamic_checked \
2803             could never raise on it",
2804        );
2805    }
2806}
2807
2808#[cfg(all(test, feature = "transpiled-base"))]
2809mod cow_alias_tests {
2810    use super::Exchange;
2811    use crate::Value;
2812    use crate::runtime::get_array_length;
2813
2814    // convertOHLCVToTradingView does `result[key].push(...)` on an extracted
2815    // local — a COW clone in Rust. Without the write-back the result columns
2816    // stay empty. Assert the data survives (review P0-C).
2817    #[test]
2818    fn convert_ohlcv_to_trading_view_preserves_pushes() {
2819        use crate::exchange_generated::ExchangeBase;
2820        let ex = super::BaseCore::new(Exchange::new(None));
2821        let row = Value::List(vec![
2822            Value::Int(1_700_000_000_000), Value::Int(1), Value::Int(2),
2823            Value::Int(0), Value::Int(1), Value::Int(10),
2824        ]);
2825        let ohlcvs = Value::List(vec![row.clone(), row]);
2826        let r = ex.convert_ohlcv_to_trading_view(ohlcvs, &[]);
2827        for key in ["t", "o", "h", "l", "c", "v"] {
2828            let col = crate::get_value(&r, &Value::Str(key.to_string().into()));
2829            assert_eq!(get_array_length(&col), Value::Int(2),
2830                "result['{key}'] lost its pushes — COW write-back failed");
2831        }
2832    }
2833}