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            // `panic!` is the transpiled error convention — `ExchangeError`'s Display
1146            // renders `[Kind] message`, which `is_instance` matches on.
1147            Err(e) => panic!("{}", e),
1148        }
1149    } }
1150
1151    // ── WebSocket (pro) drive loop ──────────────────────────────────────────
1152    //
1153    // Port of the runtime side of `Exchange.watch` / `watchMultiple`. These are
1154    // trait methods (not inherent on `Exchange`) so `self` is the concrete Core
1155    // and `dispatch_to_derived("handle_message", …)` reaches the venue override.
1156    //
1157    // Model: `watch` drives synchronously — it connects, sends the subscribe
1158    // frame once, then loops reading inbound frames and feeding each to the
1159    // venue's `handle_message` (which calls `client.resolve(value, hash)`),
1160    // returning as soon as one of the awaited hashes is settled. A repeated
1161    // `while true { watch_x().await }` consumer therefore gets one update per
1162    // call, exactly like the TS Future model. (Concurrently awaiting two streams
1163    // on the *same* socket via join is a known limitation — each drive loop
1164    // pulls from the shared frame queue.)
1165
1166    /// Shared drive loop for `watch` / `watch_multiple`.
1167    fn ws_run(
1168        &mut self,
1169        url: String,
1170        hashes: Vec<String>,
1171        message: Value,
1172        subscribe_hashes: Vec<String>,
1173        subscription: Value,
1174    ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1175        let __ws_proxy = [&self.wsProxy, &self.ws_proxy, &self.wssProxy]
1176            .iter()
1177            .find_map(|v| match v { Value::Str(s) if !s.is_empty() => Some(s.to_string()), _ => None });
1178        let client = match crate::pro::ws_client::ensure_client(&url, __ws_proxy).await {
1179            Ok(c) => c,
1180            Err(e) => panic!("{}", e),
1181        };
1182        if std::env::var("CCXT_WS_DEBUG").is_ok() {
1183            eprintln!("[wswait] {:?}", hashes);
1184        }
1185        client.note_futures(&hashes);
1186        // Subscribe once per hash. Send the message if any subscribe hash was
1187        // newly added, or if none were provided (mirrors TS's
1188        // `subscribeHashes === undefined || missingSubscriptions.length`).
1189        let mut send_subscribe = subscribe_hashes.is_empty();
1190        for sh in &subscribe_hashes {
1191            if client.subscribe_once(sh, subscription.clone()) {
1192                send_subscribe = true;
1193            }
1194        }
1195        if send_subscribe && !matches!(message, Value::Null) {
1196            let payload = match &message {
1197                Value::Str(s) => s.to_string(),
1198                v => v.to_json().to_string(),
1199            };
1200            client.send_text(payload);
1201        }
1202        // Mirror the connection into `self.clients`, the map TS venues iterate
1203        // to decide whether a stream is still worth keeping alive (binance's
1204        // `keepAliveListenKey` re-arms only while some client still holds a
1205        // subscription for the type). The handle serves `subscriptions` /
1206        // `futures` live from the registry, so this stays coherent as
1207        // subscriptions come and go.
1208        crate::runtime::add_element_to_object(
1209            &mut self.clients,
1210            &Value::Str(url.clone().into()),
1211            crate::pro::ws_client::client_value(&url),
1212        );
1213        // If an ancestor ws_run on this task is already driving `url`, don't
1214        // start a nested loop — the subscribe frame was sent above; report the
1215        // current settled state and let the outer loop resolve `hashes`.
1216        let nested_same = WS_DRIVEN_URLS
1217            .try_with(|s| s.lock().unwrap().contains(&url))
1218            .unwrap_or(false);
1219        if nested_same {
1220            return match client.take_settled(&hashes) {
1221                Some(Ok(v)) => v,
1222                _ => Value::Null,
1223            };
1224        }
1225        // Drive the loop, marking `url` for the duration so a nested watch on
1226        // the same url takes the branch above. Establish the task-local set on
1227        // the first (top-level) drive; nested-different-url calls extend it.
1228        if WS_DRIVEN_URLS.try_with(|_| ()).is_ok() {
1229            WS_DRIVEN_URLS.with(|s| { s.lock().unwrap().insert(url.clone()); });
1230            let r = self.ws_drive_loop(client, hashes, url.clone()).await;
1231            WS_DRIVEN_URLS.with(|s| { s.lock().unwrap().remove(&url); });
1232            r
1233        } else {
1234            let mut set = std::collections::HashSet::new();
1235            set.insert(url.clone());
1236            WS_DRIVEN_URLS
1237                .scope(std::sync::Mutex::new(set), self.ws_drive_loop(client, hashes, url.clone()))
1238                .await
1239        }
1240    } }
1241
1242    /// Read → dispatch → drain loop, split out so `ws_run` can wrap it in the
1243    /// `WS_DRIVEN_URLS` task-local scope.
1244    fn ws_drive_loop(
1245        &mut self,
1246        client: std::sync::Arc<crate::pro::ws_client::ClientState>,
1247        hashes: Vec<String>,
1248        url: String,
1249    ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1250        loop {
1251            // Run coroutines scheduled via spawn/delay, inline (they need
1252            // &mut self). Drain repeatedly: a coroutine may schedule another
1253            // (handle_order_book → delay(watch_order_book_snapshot)). Runs at
1254            // the top of the iteration rather than after the dispatch below so
1255            // the `continue` on a fired deadline reaches it too.
1256            loop {
1257                let batch = crate::exchange_stubs::drain_spawn_queue();
1258                if batch.is_empty() { break; }
1259                for (method, args) in batch {
1260                    if std::env::var("CCXT_WS_DEBUG").is_ok() {
1261                        eprintln!("[wsdrain] {}", method);
1262                    }
1263                    if method == "load_order_book" {
1264                        self.ws_load_order_book(args).await;
1265                    } else {
1266                        let _ = self.dispatch_to_derived(&method, args).await;
1267                    }
1268                }
1269            }
1270            if let Some(settled) = client.take_settled(&hashes) {
1271                match settled {
1272                    Ok(v) => return v,
1273                    Err(e) => panic!(
1274                        "{}",
1275                        match &e {
1276                            Value::Str(s) => s.clone(),
1277                            v => crate::runtime::stringify_param(v).into(),
1278                        }
1279                    ),
1280                }
1281            }
1282            // Bound the read by the earliest pending `delay` deadline, so a
1283            // periodic coroutine (binance's `keepAliveListenKey`) still fires
1284            // on a stream that has gone quiet. `next_message` keeps its frames
1285            // in the client's queue, so timing out drops nothing.
1286            let next_due = crate::exchange_stubs::next_spawn_due();
1287            let received = match next_due {
1288                Some(d) => match tokio::time::timeout(d, client.next_message()).await {
1289                    Ok(m) => m,
1290                    // Deadline reached: loop back round to the drain above.
1291                    Err(_) => continue,
1292                },
1293                None => client.next_message().await,
1294            };
1295            let msg = match received {
1296                Some(m) => m,
1297                None => panic!("[NetworkError] {} websocket connection closed", url),
1298            };
1299            if std::env::var("CCXT_WS_DEBUG").is_ok() {
1300                let n: usize = std::env::var("CCXT_WS_DEBUG").ok()
1301                    .and_then(|v| v.parse().ok()).filter(|v| *v > 1).unwrap_or(220);
1302                let s = msg.to_json().to_string();
1303                eprintln!("[wsmsg] {}", s.chars().take(n).collect::<String>());
1304            }
1305            let client_value = crate::pro::ws_client::client_value(&url);
1306            let _ = self
1307                .dispatch_to_derived("handle_message", vec![client_value, msg])
1308                .await;
1309        }
1310    } }
1311
1312    /// Base `loadOrderBook`: fetch the REST depth snapshot, splice the buffered
1313    /// WS cache onto it, and resolve the watcher. Venues spawn this after
1314    /// buffering enough deltas (bitstamp, …). Runs in the drive loop so it can
1315    /// reach the venue's `get_cache_index` / `handle_deltas` overrides.
1316    fn ws_load_order_book(
1317        &mut self,
1318        args: Vec<Value>,
1319    ) -> impl ::std::future::Future<Output = ()> + Send { async move {
1320        let client = args.get(0).cloned().unwrap_or(Value::Null);
1321        let message_hash = args.get(1).cloned().unwrap_or(Value::Null);
1322        let symbol = args.get(2).cloned().unwrap_or(Value::Null);
1323        let limit = args.get(3).cloned().unwrap_or(Value::Null);
1324        let params = args.get(4).cloned().unwrap_or(Value::Map(indexmap::IndexMap::new()));
1325        let err = |id: &Value| Value::Str(format!(
1326            "[ExchangeError] {} loadOrderBook() failed to synchronize",
1327            match id { Value::Str(s) => s.as_ref(), _ => "" }).into());
1328        if !crate::runtime::in_op(&self.orderbooks, &symbol) {
1329            crate::pro::ws_client::value_reject(&client, &[err(&self.id), message_hash]);
1330            return;
1331        }
1332        let max_retries: i64 = 3;
1333        let mut tries = 0;
1334        while tries < max_retries {
1335            let mut stored = crate::get_value(&self.orderbooks, &symbol);
1336            let cache = crate::get_value(&stored, &Value::Str("cache".into()));
1337            let snapshot = self
1338                .dispatch_to_derived("fetch_rest_order_book_safe",
1339                    vec![symbol.clone(), limit.clone(), params.clone()])
1340                .await
1341                .unwrap_or(Value::Null);
1342            let index = self
1343                .dispatch_to_derived("get_cache_index", vec![snapshot.clone(), cache.clone()])
1344                .await;
1345            let idx = match index { Some(Value::Int(n)) => n, _ => -1 };
1346            if idx >= 0 {
1347                stored.reset(snapshot);
1348                let clen = match crate::runtime::get_array_length(&cache) { Value::Int(n) => n, _ => 0 };
1349                let deltas: Vec<Value> = (idx..clen)
1350                    .map(|i| crate::get_value(&cache, &Value::Int(i)))
1351                    .collect();
1352                self.dispatch_to_derived("handle_deltas", vec![stored.clone(), Value::List(deltas)]).await;
1353                crate::set_value(&mut stored, &Value::Str("cache".into()), Value::List(Vec::new()));
1354                crate::pro::ws_client::value_resolve(&client, &[stored.clone(), message_hash.clone()]);
1355                return;
1356            }
1357            tries += 1;
1358        }
1359        crate::pro::ws_client::value_reject(&client, &[err(&self.id), message_hash]);
1360    } }
1361
1362    fn watch(
1363        &mut self,
1364        url: Value,
1365        message_hash: Value,
1366        optional_args: &[Value],
1367    ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1368        let url_s = match &url { Value::Str(s) => s.to_string(), v => crate::runtime::stringify_param(v) };
1369        let hash_s = match &message_hash { Value::Str(s) => s.to_string(), v => crate::runtime::stringify_param(v) };
1370        let message = optional_args.get(0).cloned().unwrap_or(Value::Null);
1371        let subscribe_hash = optional_args.get(1).cloned().unwrap_or(message_hash.clone());
1372        let sub_hash_s = match &subscribe_hash { Value::Str(s) => s.to_string(), v => crate::runtime::stringify_param(v) };
1373        let subscription = optional_args.get(2).cloned().unwrap_or(Value::Null);
1374        self.ws_run(url_s, vec![hash_s], message, vec![sub_hash_s], subscription).await
1375    } }
1376
1377    fn watch_multiple(
1378        &mut self,
1379        url: Value,
1380        message_hashes: 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 hashes = ws_string_list(&message_hashes);
1385        let message = optional_args.get(0).cloned().unwrap_or(Value::Null);
1386        let subscribe_hashes = ws_string_list(&optional_args.get(1).cloned().unwrap_or(Value::Null));
1387        let subscription = optional_args.get(2).cloned().unwrap_or(Value::Null);
1388        self.ws_run(url_s, hashes, message, subscribe_hashes, subscription).await
1389    } }
1390
1391    fn fetch_typed(
1392        &mut self,
1393        url:     &str,
1394        method:  &str,
1395        headers: HashMap<String, String>,
1396        body:    Option<String>,
1397    ) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1398        let _fetch_call_count = HTTP_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1399        self.last_request_url     = Value::Str(url.to_string().into());
1400        self.last_request_headers = Value::Map(headers.iter()
1401            .map(|(k, v)| (k.clone(), Value::Str(v.clone().into())))
1402            .collect());
1403        self.last_request_body    = match &body {
1404            Some(b) => Value::Str(b.clone().into()),
1405            None    => Value::Null,
1406        };
1407        // map iteration is unordered, so sort the fragments for a deterministic pick
1408        if let Value::Dict(byUrl) = &self.mock_response_by_url {
1409            let mut fragments: Vec<&String> = byUrl.keys().collect();
1410            fragments.sort();
1411            for fragment in &fragments {
1412                if url.contains(fragment.as_str()) {
1413                    return Ok(byUrl.get(*fragment).cloned().unwrap_or(Value::Null));
1414                }
1415            }
1416            if let Some(first) = fragments.first() {
1417                return Ok(byUrl.get(*first).cloned().unwrap_or(Value::Null));
1418            }
1419        }
1420        if !matches!(self.mock_response, Value::Null) {
1421            return Ok(self.mock_response.clone());
1422        }
1423        let proxy_defined = |v: &Value| matches!(v, Value::Str(s) if !s.is_empty());
1424        let used_proxies = [
1425            proxy_defined(&self.httpProxy)  || proxy_defined(&self.http_proxy),
1426            proxy_defined(&self.httpsProxy) || proxy_defined(&self.https_proxy),
1427            proxy_defined(&self.socksProxy) || proxy_defined(&self.socks_proxy),
1428        ].iter().filter(|x| **x).count();
1429        if used_proxies > 1 {
1430            return Err(ExchangeError::new(
1431                "InvalidProxySettings",
1432                format!("{} you have multiple conflicting proxy settings, please use only one from: httpProxy, httpsProxy, socksProxy",
1433                    match &self.id { Value::Str(s) => s.as_ref(), _ => "" }),
1434            ));
1435        }
1436        let client = self.http_client().clone();
1437        let method_parsed = reqwest::Method::from_bytes(method.as_bytes())
1438            .map_err(|_| ExchangeError::new("BadRequest", format!("invalid HTTP method: {method}")))?;
1439        let mut req = client.request(method_parsed, url);
1440        for (k, v) in &self.internals.headers { req = req.header(k, v); }
1441        for (k, v) in &headers                { req = req.header(k, v); }
1442        if self.is_verbose() {
1443            eprintln!("[ccxt] {method} {url}");
1444            for (k, v) in &self.internals.headers { eprintln!("[ccxt]   {k}: {v}"); }
1445            for (k, v) in &headers                { eprintln!("[ccxt]   {k}: {v}"); }
1446            if let Some(b) = &body {
1447                eprintln!("[ccxt]   request body: {b}");
1448            }
1449        }
1450        if let Some(b) = body                 { req = req.body(b); }
1451        let __http_t0 = std::time::Instant::now();
1452        let resp = req.send().await?;
1453        let status = resp.status().as_u16();
1454        let reason = resp.status().canonical_reason().unwrap_or("");
1455        let text   = resp.text().await?;
1456        HTTP_NANOS.fetch_add(__http_t0.elapsed().as_nanos() as u64,
1457            std::sync::atomic::Ordering::Relaxed);
1458        if self.is_verbose() {
1459            eprintln!("[ccxt] ← {status} {} bytes", text.len());
1460            const CAP: usize = 16384;
1461            if text.len() > CAP {
1462                eprintln!("[ccxt]   response body: {}… ({} bytes total)",
1463                    &text[..text.char_indices().take_while(|(i, _)| *i < CAP).last().map(|(i, c)| i + c.len_utf8()).unwrap_or(0)],
1464                    text.len());
1465            } else {
1466                eprintln!("[ccxt]   response body: {text}");
1467            }
1468        }
1469        let __json_t0 = std::time::Instant::now();
1470        let json = match serde_json::from_str::<serde_json::Value>(&text) {
1471            Ok(j)  => Value::from_json(&j),
1472            Err(_) => Value::Null,
1473        };
1474        JSON_NANOS.fetch_add(__json_t0.elapsed().as_nanos() as u64,
1475            std::sync::atomic::Ordering::Relaxed);
1476        // Venues also report failures in a 2xx body, so every response goes through
1477        // the derived handle_errors; a Null result falls back to httpExceptions.
1478        let handled = crate::exchange::DerivedExchange::handle_errors(
1479            self,
1480            Value::Int(status as i64),
1481            Value::Str(reason.into()),
1482            Value::Str(url.to_string().into()),
1483            Value::Str(method.to_string().into()),
1484            Value::Null,
1485            Value::Str(text.clone().into()),
1486            json.clone(),
1487            Value::Null,
1488            Value::Null,
1489        );
1490        if matches!(handled, Value::Null) {
1491            self.handle_http_status_code(
1492                Value::Int(status as i64),
1493                Value::Str(reason.into()),
1494                Value::Str(url.to_string().into()),
1495                Value::Str(method.to_string().into()),
1496                Value::Str(text.clone().into()),
1497            );
1498        }
1499        if status >= 400 {
1500            return Err(ExchangeError::new(
1501                if status == 429 { "RateLimitExceeded" }
1502                else if status >= 500 { "ExchangeNotAvailable" }
1503                else { "ExchangeError" },
1504                format!("HTTP {status}: {text}"),
1505            ));
1506        }
1507        if matches!(json, Value::Null) {
1508            return Ok(Value::Str(text.into()));
1509        }
1510        Ok(json)
1511    } }
1512
1513    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 {
1514        // Mock transport responses only; preserve the signed request metadata.
1515        if matches!(self.mock_response, Value::Null) && matches!(self.mock_response_by_url, Value::Null) {
1516            self.throttle(&[cost]).await;
1517        }
1518        let api_arg = if scope_segments.len() == 1 {
1519            Value::Str(scope_segments[0].clone().into())
1520        } else {
1521            Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect())
1522        };
1523        let scope_lookup: String = scope_segments.first().cloned().unwrap_or_default();
1524        // Static dispatch to the derived exchange's sign override.
1525        let signed = crate::exchange::DerivedExchange::sign(
1526            self,
1527            Value::Str(path.to_string().into()),
1528            api_arg,
1529            Value::Str(verb.to_string().into()),
1530            params.clone(),
1531            Value::Null,
1532            Value::Null,
1533        );
1534        if let Value::Dict(m) = &signed {
1535            let url = match m.get("url") { Some(Value::Str(s)) => s.to_string(), _ => String::new().into() };
1536            let method = match m.get("method") { Some(Value::Str(s)) => s.to_string(), _ => verb.to_string().into() };
1537            let body = match m.get("body") { Some(Value::Str(s)) => Some(s.to_string()), _ => None };
1538            let headers = match m.get("headers") {
1539                Some(Value::Dict(h)) => h.iter()
1540                    .filter_map(|(k, v)| match v { Value::Str(s) => Some((k.clone(), s.to_string())), _ => None })
1541                    .collect::<HashMap<_, _>>(),
1542                _ => HashMap::new(),
1543            };
1544            if !url.is_empty() {
1545                return self.fetch_typed(&url, &method, headers, body).await;
1546            }
1547        }
1548        let base = self.url_for_scope(&scope_lookup).ok_or_else(|| ExchangeError::new(
1549            "BadRequest",
1550            format!("no URL configured for api scope `{scope_lookup}`"),
1551        ))?;
1552        let imploded = self.implode_params(Value::Str(path.to_string().into()), params.clone());
1553        let path_str = match &imploded { Value::Str(s) => s.clone(), _ => path.to_string().into() };
1554        let consumed_keys = self.extract_path_params(path);
1555        let remaining_params = match params {
1556            Value::Dict(m) => {
1557                let mut keep = HashMap::new();
1558                let m = Arc::try_unwrap(m).unwrap_or_else(|a| (*a).clone());
1559                for (k, v) in m {
1560                    if !consumed_keys.contains(&k) { keep.insert(k, v); }
1561                }
1562                Value::Map(keep)
1563            }
1564            other => other,
1565        };
1566        let mut url = format!("{}/{}", base.trim_end_matches('/'), path_str.trim_start_matches('/'));
1567        let mut body: Option<String> = None;
1568        let qs = match &remaining_params {
1569            Value::Dict(m) if !m.is_empty() => self.urlencode_kv(&remaining_params),
1570            _ => String::new(),
1571        };
1572        if verb == "GET" || verb == "DELETE" {
1573            if !qs.is_empty() {
1574                url = format!("{}?{}", url, qs);
1575            }
1576        } else if !qs.is_empty() {
1577            body = Some(qs);
1578        }
1579        let mut headers = HashMap::new();
1580        if scope_lookup != "public" {
1581            if let Value::Str(k) = &self.apiKey {
1582                headers.insert("X-MBX-APIKEY".to_string(), k.to_string());
1583            }
1584        }
1585        self.fetch_typed(&url, verb, headers, body).await
1586    } }
1587
1588    /// Route an implicit-API method name to `request_typed`.
1589    fn implicit_api_call(&mut self, name: &str, params: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1590        if self.internals.implicit_api.is_empty() {
1591            self.build_implicit_api();
1592        }
1593        let entry = self.internals.implicit_api.get(name).cloned();
1594        let (path, scope_segments, verb, config) = match entry {
1595            Some(t) => t,
1596            None => return Err(ExchangeError::new(
1597                "NotSupported",
1598                format!("implicit API method {name} not found in api block"),
1599            )),
1600        };
1601        let api = if scope_segments.len() == 1 {
1602            Value::Str(scope_segments[0].clone().into())
1603        } else {
1604            Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect())
1605        };
1606        let cost = if matches!(self.enableRateLimit, Value::Bool(true)) {
1607            self.call_dynamic(
1608                "calculate_rate_limiter_cost",
1609                vec![api, Value::Str(verb.clone().into()), Value::Str(path.clone().into()), params.clone(), config],
1610            ).await
1611        } else {
1612            Value::Null
1613        };
1614        self.request_typed(&path, &scope_segments, &verb, params, cost).await
1615    } }
1616
1617    #[cfg(test)]
1618    fn implicit_api_rate_limit_cost(&mut self, name: &str, params: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1619        if self.internals.implicit_api.is_empty() {
1620            self.build_implicit_api();
1621        }
1622        let (path, scope_segments, verb, config) = self.internals.implicit_api
1623            .get(name)
1624            .cloned()
1625            .ok_or_else(|| ExchangeError::new("NotSupported", format!("implicit API method {name} not found in api block")))?;
1626        let api = if scope_segments.len() == 1 {
1627            Value::Str(scope_segments[0].clone().into())
1628        } else {
1629            Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect())
1630        };
1631        Ok(self.call_dynamic(
1632            "calculate_rate_limiter_cost",
1633            vec![api, Value::Str(verb.into()), Value::Str(path.into()), params, config],
1634        ).await)
1635    } }
1636
1637    /// Dispatch an implicit-API method by name (from transpiled `_api.rs`).
1638    fn call_method(&mut self, name: Value, args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1639        let n = match name { Value::Str(s) => s, _ => return Value::Null };
1640        let params = args.get(0).cloned().unwrap_or(Value::Map(HashMap::new()));
1641        match self.implicit_api_call(&n, params).await {
1642            Ok(v) => v,
1643            Err(e) => {
1644                if matches!(self.verbose, Value::Bool(true)) {
1645                    eprintln!("[ccxt] {n} failed: {e}");
1646                }
1647                panic!("{e}");
1648            }
1649        }
1650    } }
1651
1652    /// Loads markets (and currencies), dispatching `fetch_markets` /
1653    /// `fetch_currencies` / `set_markets` to the derived overrides.
1654    fn load_markets(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1655        let reload = optional_args.get(0).cloned().unwrap_or(Value::Bool(false));
1656        let reload_b = matches!(reload, Value::Bool(true));
1657        if !reload_b && !self.markets.is_null() {
1658            return self.markets.clone();
1659        }
1660        let has_fetch_currencies = matches!(
1661            crate::get_value(&self.has, &Value::Str("fetchCurrencies".into())),
1662            Value::Bool(true),
1663        );
1664        let mut currencies = Value::Null;
1665        if has_fetch_currencies {
1666            if let Some(v) = self.dispatch_to_derived("fetch_currencies", Vec::new()).await {
1667                currencies = v;
1668            }
1669        }
1670        let fetched = match self.dispatch_to_derived("fetch_markets", Vec::new()).await {
1671            Some(v) => v,
1672            None => return Value::Null,
1673        };
1674        if matches!(fetched, Value::Null) {
1675            return self.markets.clone();
1676        }
1677        let preloaded_non_empty = matches!(&self.currencies, Value::Dict(m) if !m.is_empty());
1678        let currencies_arg = if matches!(&currencies, Value::Dict(m) if !m.is_empty()) {
1679            currencies
1680        } else if preloaded_non_empty {
1681            self.currencies.clone()
1682        } else {
1683            crate::exchange_stubs::synthesize_currencies_from_markets(&fetched, &self.precisionMode)
1684        };
1685        let is_prediction = matches!(
1686            crate::get_value(&self.has, &Value::Str("prediction".into())),
1687            Value::Bool(true),
1688        );
1689        if is_prediction {
1690            let _ = self.dispatch_to_derived("set_markets", vec![fetched, currencies_arg]).await;
1691        } else {
1692            <Self as crate::exchange_generated::ExchangeBase>::set_markets(self, fetched, &[currencies_arg]);
1693        }
1694        // Index markets_by_id by the secondary id (`id2`, e.g. apex's
1695        // crossSymbolName) too, so a WS handler that resolves a market from the
1696        // id2-based stream id (`safeMarket(data['s'])`) reaches the unified
1697        // symbol instead of a synthetic one.
1698        let markets_snapshot = self.markets.clone();
1699        if let Value::Dict(markets) = &markets_snapshot {
1700            if let Value::Dict(by_id_arc) = &self.markets_by_id {
1701                let mut by_id = (**by_id_arc).clone();
1702                for market in markets.values() {
1703                    let id  = crate::get_value(market, &Value::Str("id".into()));
1704                    let id2 = crate::get_value(market, &Value::Str("id2".into()));
1705                    if let (Value::Str(id2s), Value::Str(ids)) = (&id2, &id) {
1706                        if id2s != ids && !id2s.is_empty() && !by_id.contains_key(id2s.as_ref()) {
1707                            by_id.insert(id2s.to_string(), Value::List(vec![market.clone()]));
1708                        }
1709                    }
1710                }
1711                self.markets_by_id = Value::Map(by_id);
1712            }
1713        }
1714        self.markets.clone()
1715    } }
1716
1717    // ── super.X() shims — call the BASE (ExchangeBase) method, fully-qualified
1718    // so a derived override is bypassed (that is what `super.X()` means).
1719    fn super_describe(&self) -> Value {
1720        <Self as crate::exchange_generated::ExchangeBase>::describe(self)
1721    }
1722    fn super_set_sandbox_mode(&mut self, enabled: Value) {
1723        <Self as crate::exchange_generated::ExchangeBase>::set_sandbox_mode(self, enabled);
1724    }
1725    fn super_safe_market(&self, id: Value, market: Value, delim: Value, market_type: Value) -> Value {
1726        <Self as crate::exchange_generated::ExchangeBase>::safe_market(self, &[id, market, delim, market_type])
1727    }
1728    fn super_handle_market_type_and_params(&self, method_name: Value, market: Value, params: Value, default_value: Value) -> Value {
1729        <Self as crate::exchange_generated::ExchangeBase>::handle_market_type_and_params(self, method_name, &[market, params, default_value])
1730    }
1731    fn super_market(&self, symbol: Value) -> Value {
1732        <Self as crate::exchange_generated::ExchangeBase>::market(self, symbol)
1733    }
1734    fn super_amount_to_precision(&self, symbol: Value, amount: Value) -> Value {
1735        <Self as crate::exchange_generated::ExchangeBase>::amount_to_precision(self, symbol, amount)
1736    }
1737    fn super_handle_margin_mode_and_params(&self, method_name: Value, params: Value, default_value: Value) -> Value {
1738        <Self as crate::exchange_generated::ExchangeBase>::handle_margin_mode_and_params(self, method_name, &[params, default_value])
1739    }
1740    fn super_safe_currency_code(&self, currency_id: Value, currency: Value) -> Value {
1741        <Self as crate::exchange_generated::ExchangeBase>::safe_currency_code(self, currency_id, &[currency])
1742    }
1743    fn super_set_markets(&mut self, markets: Value, currencies: Value) -> Value {
1744        <Self as crate::exchange_generated::ExchangeBase>::set_markets(self, markets, &[currencies])
1745    }
1746    fn super_network_id_to_code(&self, optional_args: &[Value]) -> Value {
1747        <Self as crate::exchange_generated::ExchangeBase>::network_id_to_code(self, optional_args)
1748    }
1749    fn super_network_code_to_id(&self, network_code: Value, optional_args: &[Value]) -> Value {
1750        <Self as crate::exchange_generated::ExchangeBase>::network_code_to_id(self, network_code, optional_args)
1751    }
1752    fn super_fetch_deposit_address(&mut self, code: Value, params: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
1753        self.fetch_deposit_address(code, &[params]).await
1754    } }
1755    fn super_load_markets(&mut self, reload: Value, params: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
1756        self.load_markets(&[reload, params]).await
1757    } }
1758}
1759
1760impl<T: crate::exchange_generated::ExchangeBase> ExchangeRuntime for T {}
1761
1762/// Normalize a TS dynamic method name for the generated Rust dispatch table.
1763///
1764/// Must stay byte-identical to the transpiler's `toSnakeCase`
1765/// (`build/rustTranspiler.ts`) and to `Exchange::to_snake_case` (which names
1766/// the implicit-API entries `call_dynamic`'s fall-through looks up) — it is the
1767/// only thing deciding whether a paginated `this[method](...)` re-entry lands
1768/// on a dispatch arm. `method_name_snake_case_tests` pins all three.
1769///
1770/// A name that is not a `Value::Str` (or is empty) is a hard bug: TS
1771/// `this[name](...)` always indexes with a string. Returning `""` here would
1772/// resolve to no dispatch arm and no implicit endpoint, so `call_dynamic`
1773/// would hand back `Value::Null` and the caller would silently see an empty
1774/// page instead of an error — exactly the failure this PR set out to remove.
1775/// Panic instead, mirroring the TS `TypeError: this[method] is not a function`
1776/// (the transpiled try/catch turns it back into a catchable error).
1777pub fn method_name_to_snake_case(name: &Value) -> String {
1778    let name = match name {
1779        Value::Str(name) if !name.is_empty() => name,
1780        _ => panic!(
1781            "{}",
1782            crate::exchange_errors::not_supported(format!(
1783                "dynamic method dispatch requires a non-empty string method name, got {name:?}"
1784            )),
1785        ),
1786    };
1787    let chars: Vec<char> = name.chars().collect();
1788    let mut out = String::with_capacity(name.len() + 4);
1789    for (i, &c) in chars.iter().enumerate() {
1790        if c.is_ascii_uppercase() {
1791            let lower_before = i > 0
1792                && (chars[i - 1].is_ascii_lowercase() || chars[i - 1].is_ascii_digit());
1793            let acronym_end = i > 0 && chars[i - 1].is_ascii_uppercase()
1794                && chars.get(i + 1).map(|next| next.is_ascii_lowercase()).unwrap_or(false);
1795            if lower_before || acronym_end {
1796                out.push('_');
1797            }
1798            out.push(c.to_ascii_lowercase());
1799        } else {
1800            out.push(c);
1801        }
1802    }
1803    out
1804}
1805
1806/// Wraps a `call_dynamic` re-entry that MUST resolve. `call_dynamic_base`'s
1807/// `_` arm returns `Value::Null` for a name that is neither a dispatch arm nor
1808/// an implicit-API endpoint — fine for an optional probe, but a dynamic
1809/// re-entry from `fetchPaginatedCall*` / `fetchWebEndpoint` would then hand the
1810/// caller an empty page instead of an error. That arm records the miss on
1811/// `internals.dynamic_dispatch_miss`; this raises it as a loud `NotSupported`,
1812/// the way `call_method` used to fail, so a dispatch regression surfaces as an
1813/// error rather than as null data (review on #30385).
1814pub trait CallDynamicChecked: crate::exchange_generated::ExchangeBase {
1815    fn call_dynamic_checked(&mut self, name: Value, args: Vec<Value>) -> impl ::std::future::Future<Output = Value> + Send { async move {
1816        let snake = method_name_to_snake_case(&name);
1817        // Clear first: a miss recorded by an unrelated earlier probe must not
1818        // be attributed to this call.
1819        self.internals.dynamic_dispatch_miss = None;
1820        let out = self.call_dynamic(&snake, args).await;
1821        // Only OUR name counts — a nested optional probe inside the dispatched
1822        // method legitimately misses and must stay silent.
1823        if self.internals.dynamic_dispatch_miss.as_deref() == Some(snake.as_str()) {
1824            self.internals.dynamic_dispatch_miss = None;
1825            panic!(
1826                "{}",
1827                crate::exchange_errors::not_supported(format!(
1828                    "{} dynamic method {snake}() resolved to no dispatch arm and no implicit API endpoint",
1829                    crate::runtime::stringify_param(&self.id),
1830                )),
1831            );
1832        }
1833        out
1834    } }
1835}
1836
1837impl<T: crate::exchange_generated::ExchangeBase> CallDynamicChecked for T {}
1838
1839/// A minimal Core wrapping a bare `Exchange` with NO overrides. Lets code that
1840/// only has an `Exchange` value — `Value` snapshots (value.rs), the constructor
1841/// (`after_construct`), and base unit tests — call `ExchangeBase`/`ExchangeRuntime`
1842/// trait methods, which all resolve to the base defaults (review #1: base
1843/// methods are trait methods now, so a bare `Exchange` can't call them directly).
1844pub struct BaseCore {
1845    pub exchange: Exchange,
1846}
1847impl BaseCore {
1848    pub fn new(exchange: Exchange) -> Self { Self { exchange } }
1849    pub fn into_inner(self) -> Exchange { self.exchange }
1850}
1851impl std::ops::Deref for BaseCore {
1852    type Target = Exchange;
1853    fn deref(&self) -> &Exchange { &self.exchange }
1854}
1855impl std::ops::DerefMut for BaseCore {
1856    fn deref_mut(&mut self) -> &mut Exchange { &mut self.exchange }
1857}
1858impl DerivedExchange for BaseCore {}
1859impl crate::exchange_generated::ExchangeBase for BaseCore {
1860    fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<Value>)
1861        -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>>
1862    {
1863        Box::pin(async move { self.call_dynamic_base(method, args).await })
1864    }
1865}
1866
1867// ── implicit API dispatch ───────────────────────────────────────────────────
1868
1869impl Exchange {
1870    /// Builds the `name → (path, scope, verb)` dispatch table by walking
1871    /// the `self.api` Value::Map. Called lazily on first dynamic call.
1872    ///
1873    /// The `api` block layout is:
1874    ///   { <scope>: { <verb>: [path, path, ...] } }
1875    ///   { <scope>: { <subscope>: { <verb>: [path, ...] } } }
1876    /// — arbitrary nesting before the verb level. The verb is one of
1877    /// `get`/`post`/`put`/`delete`/`patch` (any case). All path components
1878    /// before the verb concatenate into the scope (joined by `_`).
1879    pub fn build_implicit_api(&mut self) {
1880        let mut map: HashMap<String, (String, Vec<String>, String, Value)> = HashMap::new();
1881        Self::walk_api_node(&self.api, &[], &mut map);
1882        self.internals.implicit_api = map;
1883    }
1884
1885    fn walk_api_node(
1886        node: &Value,
1887        crumbs: &[String],
1888        out: &mut HashMap<String, (String, Vec<String>, String, Value)>,
1889    ) {
1890        let known_verbs = ["get", "post", "put", "delete", "patch"];
1891        let last_is_verb = crumbs.last()
1892            .map(|c| known_verbs.iter().any(|v| *v == c.to_lowercase().as_str()))
1893            .unwrap_or(false);
1894        match node {
1895            // If the current level is a verb (`get`/`post`/…) and its child
1896            // is a Map, the keys ARE the paths (and values are rate-limit
1897            // costs — exchange-specific).
1898            Value::Dict(m) if last_is_verb => {
1899                let verb = crumbs.last().unwrap().to_lowercase();
1900                // Method name uses snake-cased scope (`fapi_public_get_X`).
1901                let scope_snake = Self::api_scope_from_crumbs(&crumbs[..crumbs.len() - 1]);
1902                // But sign()/urls.api lookup uses the original segments
1903                // (camelCase, e.g. `["fapiPublic"]` for binance,
1904                //  `["public","common"]` for bitget, `["public","spot"]`
1905                //  for gate). Preserve as Vec<String> so the dispatcher
1906                //  can choose Value::Str (single) vs Value::Array (multi).
1907                let scope_segments: Vec<String> = crumbs[..crumbs.len() - 1].to_vec();
1908                for (path_key, endpoint_config) in m.iter() {
1909                    let config = match endpoint_config {
1910                        Value::Dict(_) => endpoint_config.clone(),
1911                        Value::Int(_) | Value::Float(_) => Value::Map({
1912                            let mut config = crate::value::HashMap::new();
1913                            config.insert("cost".to_string(), endpoint_config.clone());
1914                            config
1915                        }),
1916                        _ => Value::Map(crate::value::HashMap::new()),
1917                    };
1918                    Self::register_implicit(&verb, &scope_snake, &scope_segments, path_key, config, out);
1919                }
1920            }
1921            Value::Dict(m) => {
1922                for (key, child) in m.iter() {
1923                    let mut next = crumbs.to_vec();
1924                    next.push(key.clone());
1925                    Self::walk_api_node(child, &next, out);
1926                }
1927            }
1928            // Some exchanges use `Array<path-string>` at the verb level.
1929            Value::Arr(a) if last_is_verb => {
1930                let verb = crumbs.last().unwrap().to_lowercase();
1931                let scope_snake = Self::api_scope_from_crumbs(&crumbs[..crumbs.len() - 1]);
1932                let scope_segments: Vec<String> = crumbs[..crumbs.len() - 1].to_vec();
1933                for path in a.iter() {
1934                    let (path_str, config) = match path {
1935                        Value::Str(s) => (s.clone(), Value::Map(crate::value::HashMap::new())),
1936                        Value::Dict(pm) => match pm.get("method").or_else(|| pm.get("path")) {
1937                            Some(Value::Str(s)) => (s.clone(), path.clone()),
1938                            _ => continue,
1939                        },
1940                        _ => continue,
1941                    };
1942                    Self::register_implicit(&verb, &scope_snake, &scope_segments, &path_str, config, out);
1943                }
1944            }
1945            _ => {}
1946        }
1947    }
1948
1949    fn api_scope_from_crumbs(crumbs: &[String]) -> String {
1950        // The scope identifier in TS is camelCase (e.g. `fapiPrivate`),
1951        // but transpiled call sites are snake_case (`fapi_private_get_X`).
1952        // Convert each crumb camelCase → snake_case and join with `_`.
1953        crumbs.iter()
1954            .map(|s| s
1955                .chars()
1956                .enumerate()
1957                .flat_map(|(i, c)| {
1958                    if c.is_ascii_uppercase() && i > 0 {
1959                        vec!['_', c.to_ascii_lowercase()]
1960                    } else {
1961                        vec![c.to_ascii_lowercase()]
1962                    }
1963                })
1964                .collect::<String>())
1965            .collect::<Vec<_>>()
1966            .join("_")
1967    }
1968
1969    fn register_implicit(
1970        verb: &str,
1971        scope_snake: &str,
1972        scope_segments: &[String],
1973        path: &str,
1974        config: Value,
1975        out: &mut HashMap<String, (String, Vec<String>, String, Value)>,
1976    ) {
1977        // CCXT's TS `defineRestApiEndpoint` builds the method name by
1978        // splitting the path on EVERY non-alphanumeric character:
1979        //   `path.split(/[^a-zA-Z0-9]/)` → capitalize each part → join.
1980        // So `:`, `{`, `}`, `/`, `.`, `-` are all separators. Examples:
1981        //   `ticker/24hr`                      → `Ticker24hr` → `ticker24hr`
1982        //   `lending/auto-invest`              → `LendingAutoInvest` → `lending_auto_invest`
1983        //   `candles/trade:{tf}:{sym}/hist`    → `CandlesTradeTfSymHist`
1984        //                                      → `candles_trade_tf_sym_hist`
1985        let camel: String = path
1986            .split(|c: char| !c.is_ascii_alphanumeric())
1987            .filter(|s| !s.is_empty())
1988            .map(|seg| {
1989                let mut chars = seg.chars();
1990                match chars.next() {
1991                    None => String::new(),
1992                    Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
1993                }
1994            })
1995            .collect();
1996        // snake_case from camel: insert `_` between [a-z\d] and [A-Z],
1997        // and between [A-Z]+ and [A-Z][a-z]. Mirrors the transpiler's
1998        // toSnakeCase exactly.
1999        let snake = Self::to_snake_case(&camel);
2000        // An empty path (e.g. nado's `archive: { post: { '': 1 } }`, method
2001        // name `archivePost`) must NOT append a trailing `_` — the transpiled
2002        // call site looks up `archive_post`, not `archive_post_`.
2003        let snake_name = if snake.is_empty() {
2004            format!("{scope_snake}_{verb}")
2005        } else {
2006            format!("{scope_snake}_{verb}_{snake}")
2007        };
2008        // CamelCase variant: `<scope_camel><Verb><PathCamel>` — TS often
2009        // constructs method names dynamically as camelCase (e.g. bit2c's
2010        // `"privatePostOrderAddOrder"`). `self.call_method(name, ...)`
2011        // looks up by exact string, so register both keys.
2012        let scope_camel: String = scope_segments.iter()
2013            .enumerate()
2014            .map(|(i, s)| {
2015                if i == 0 {
2016                    s.to_string()
2017                } else {
2018                    let mut chars = s.chars();
2019                    match chars.next() {
2020                        None => String::new(),
2021                        Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
2022                    }
2023                }
2024            })
2025            .collect();
2026        let verb_camel = {
2027            let mut chars = verb.chars();
2028            match chars.next() {
2029                None => String::new(),
2030                Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str().to_lowercase().as_str(),
2031            }
2032        };
2033        let camel_name = format!("{scope_camel}{verb_camel}{camel}");
2034        // Snake-cased from the WHOLE camel name, which is what the transpiler
2035        // does to produce the call site. It usually equals `snake_name` above,
2036        // but the two diverge when a path segment starts with a digit: joining
2037        // pre-snaked parts forces a separator the transpiler never inserts, so
2038        // revolutx's `1.0/public/tickers` registers as
2039        // `public_get_10_public_tickers` while the generated code calls
2040        // `public_get10_public_tickers` (toSnakeCase puts no `_` between a
2041        // digit and the preceding letter). Register both spellings so either
2042        // resolves.
2043        let camel_snake_name = Self::to_snake_case(&camel_name);
2044        let entry = (path.to_string(), scope_segments.to_vec(), verb.to_uppercase(), config);
2045        out.insert(snake_name, entry.clone());
2046        if !out.contains_key(&camel_snake_name) {
2047            out.insert(camel_snake_name, entry.clone());
2048        }
2049        if !out.contains_key(&camel_name) {
2050            out.insert(camel_name, entry);
2051        }
2052    }
2053
2054    fn to_snake_case(s: &str) -> String {
2055        // 1st pass: `[A-Z]+([A-Z][a-z])` → `$1_$2`
2056        let bytes: Vec<char> = s.chars().collect();
2057        let mut out = String::with_capacity(s.len() + 4);
2058        for i in 0..bytes.len() {
2059            let c = bytes[i];
2060            let prev = if i > 0 { Some(bytes[i - 1]) } else { None };
2061            let next = if i + 1 < bytes.len() { Some(bytes[i + 1]) } else { None };
2062            if c.is_ascii_uppercase() {
2063                let prev_lower_or_digit = prev
2064                    .map(|p| p.is_ascii_lowercase() || p.is_ascii_digit())
2065                    .unwrap_or(false);
2066                let prev_upper = prev.map(|p| p.is_ascii_uppercase()).unwrap_or(false);
2067                let next_lower = next.map(|n| n.is_ascii_lowercase()).unwrap_or(false);
2068                if prev_lower_or_digit {
2069                    out.push('_');
2070                } else if prev_upper && next_lower {
2071                    out.push('_');
2072                }
2073            }
2074            out.push(c.to_ascii_lowercase());
2075        }
2076        // Collapse any `__` runs introduced by underscores already in input.
2077        while out.contains("__") {
2078            out = out.replace("__", "_");
2079        }
2080        out.trim_matches('_').to_string()
2081    }
2082
2083    /// Resolves the base URL for a given api scope. Looks up
2084    /// `urls.api.<scope>`; if that's itself a map, prefers `rest`.
2085    fn url_for_scope(&self, scope: &str) -> Option<String> {
2086        let api = crate::get_value(&self.urls, &Value::Str("api".into()));
2087        // Try scoped first (binance-style: urls.api.public, urls.api.private).
2088        let scoped = crate::get_value(&api, &Value::Str(scope.to_string().into()));
2089        let raw = match scoped {
2090            Value::Str(s) => s,
2091            Value::Dict(m) => match m.get("rest").or_else(|| m.get("current")) {
2092                Some(Value::Str(s)) => s.clone(),
2093                _ => return self.fallback_rest_url(&api),
2094            },
2095            _ => return self.fallback_rest_url(&api),
2096        };
2097        Some(self.implode_hostname_typed(&raw))
2098    }
2099
2100    /// Many exchanges (okx, kucoin, bitget, gate, hyperliquid, …) use
2101    /// a single `urls.api.rest` URL for all scopes. Fall back to it
2102    /// when the per-scope lookup misses.
2103    fn fallback_rest_url(&self, api: &Value) -> Option<String> {
2104        let rest = crate::get_value(api, &Value::Str("rest".into()));
2105        if let Value::Str(s) = rest {
2106            return Some(self.implode_hostname_typed(&s));
2107        }
2108        // Last resort: if urls.api itself is a string, use it.
2109        if let Value::Str(s) = api {
2110            return Some(self.implode_hostname_typed(s));
2111        }
2112        None
2113    }
2114
2115    /// Internal typed `{hostname}` substitution.
2116    fn implode_hostname_typed(&self, url: &str) -> String {
2117        let host = match &self.hostname {
2118            Value::Str(s) => s.clone(),
2119            _ => return url.to_string(),
2120        };
2121        url.replace("{hostname}", &host)
2122    }
2123
2124    // Dispatches an implicit API call. Looks the method up in the dispatch
2125    // table (building it on first use) and routes through `request`.
2126    // Public-endpoint request: imploding params into the path/query and
2127    // hitting `fetch`. Private endpoints need per-exchange signing — for
2128    // now we treat anything outside `public` as a stub that returns Null.
2129    fn extract_path_params(&self, path: &str) -> Vec<String> {
2130        let mut out: Vec<String> = vec![];
2131        let mut chars = path.chars().peekable();
2132        while let Some(c) = chars.next() {
2133            if c == '{' {
2134                let mut name = String::new();
2135                while let Some(&nc) = chars.peek() {
2136                    if nc == '}' { chars.next(); break; }
2137                    name.push(nc); chars.next();
2138                }
2139                if !name.is_empty() { out.push(name); }
2140            }
2141        }
2142        out
2143    }
2144}
2145
2146/// Raw digest bytes for a named hash algorithm — includes Keccak-256
2147/// (`keccak`), used by ETH-style signing (hyperliquid, etc.).
2148pub(crate) fn hash_raw(data: &[u8], algo: &str) -> Vec<u8> {
2149    match algo.to_ascii_lowercase().as_str() {
2150        "sha256" => { let mut h = Sha256::new(); h.update(data); h.finalize().to_vec() }
2151        "sha512" => { let mut h = Sha512::new(); h.update(data); h.finalize().to_vec() }
2152        "sha1"   => { let mut h = Sha1::new();   h.update(data); h.finalize().to_vec() }
2153        "md5"    => { let mut h = Md5::new();    h.update(data); h.finalize().to_vec() }
2154        "keccak" | "keccak256" => {
2155            use sha3::{Keccak256, Digest as _};
2156            let mut h = Keccak256::new();
2157            h.update(data);
2158            h.finalize().to_vec()
2159        }
2160        _ => Vec::new(),
2161    }
2162}
2163
2164/// EIP-712 `encode` — produces the `\x19\x01 || domainSeparator ||
2165/// hashStruct(message)` preimage. The caller keccak-hashes this into the
2166/// 32-byte digest that gets ECDSA-signed (hyperliquid, etc.).
2167type Eip712Types = std::collections::BTreeMap<String, Vec<(String, String)>>;
2168
2169/// Strip a trailing `[...]` array suffix from an EIP-712 field type, so
2170/// `Order[]` and `Order` both resolve to the struct name `Order`.
2171fn eip712_base_type(ty: &str) -> &str {
2172    match ty.find('[') { Some(i) => &ty[..i], None => ty }
2173}
2174
2175/// EIP-712 `encodeType`: the primary type's signature followed by every
2176/// referenced struct type, sorted alphabetically (per the spec), so a nested
2177/// `TypedDataSign(Order contents,…)` correctly appends `Order(uint256 salt,…)`.
2178fn eip712_encode_type(primary: &str, types: &Eip712Types) -> String {
2179    fn collect(name: &str, types: &Eip712Types, deps: &mut std::collections::BTreeSet<String>) {
2180        if let Some(fields) = types.get(name) {
2181            for (_, ty) in fields {
2182                let base = eip712_base_type(ty).to_string();
2183                if types.contains_key(&base) && deps.insert(base.clone()) {
2184                    collect(&base, types, deps);
2185                }
2186            }
2187        }
2188    }
2189    let fmt = |name: &str| -> String {
2190        let fields = types.get(name).cloned().unwrap_or_default();
2191        let inner: Vec<String> = fields.iter().map(|(n, t)| format!("{t} {n}")).collect();
2192        format!("{}({})", name, inner.join(","))
2193    };
2194    let mut deps = std::collections::BTreeSet::new();
2195    collect(primary, types, &mut deps);
2196    deps.remove(primary);
2197    let mut out = fmt(primary);
2198    for dep in &deps { out.push_str(&fmt(dep)); } // BTreeSet iterates sorted
2199    out
2200}
2201
2202pub(crate) fn eip712_encode(domain: &Value, types: &Value, message: &Value) -> Vec<u8> {
2203    let dm = match domain { Value::Dict(m) => m, _ => return Vec::new() };
2204    // EIP712Domain field set — canonical order, only the keys present.
2205    let mut domain_fields: Vec<(String, String)> = Vec::new();
2206    for (n, t) in [("name", "string"), ("version", "string"), ("chainId", "uint256"),
2207                   ("verifyingContract", "address"), ("salt", "bytes32")] {
2208        if dm.contains_key(n) { domain_fields.push((n.to_string(), t.to_string())); }
2209    }
2210    // Domain has no nested structs — a flat (empty type-map) hash.
2211    let mut domain_types: Eip712Types = Eip712Types::new();
2212    domain_types.insert("EIP712Domain".to_string(), domain_fields);
2213    let domain_sep = eip712_hash_struct("EIP712Domain", domain, &domain_types);
2214
2215    // Collect all user-defined types (name → fields), excluding EIP712Domain.
2216    let mut type_map: Eip712Types = Eip712Types::new();
2217    if let Value::Dict(m) = types {
2218        for (name, def) in m.iter() {
2219            if name == "EIP712Domain" { continue; }
2220            if let Value::Arr(arr) = def {
2221                let fields: Vec<(String, String)> = arr.iter().filter_map(|it| match it {
2222                    Value::Dict(fm) => Some((
2223                        fm.get("name")?.as_str()?.to_string(),
2224                        fm.get("type")?.as_str()?.to_string(),
2225                    )),
2226                    _ => None,
2227                }).collect();
2228                type_map.insert(name.clone(), fields);
2229            }
2230        }
2231    }
2232    if type_map.is_empty() { return Vec::new(); }
2233    // Primary type = the one not referenced as a field type by any other type
2234    // (the top-level struct). Falls back to the first key.
2235    let referenced: std::collections::HashSet<String> = type_map.values()
2236        .flat_map(|fs| fs.iter().map(|(_, t)| eip712_base_type(t).to_string()))
2237        .collect();
2238    let primary = type_map.keys().find(|k| !referenced.contains(*k)).cloned()
2239        .unwrap_or_else(|| type_map.keys().next().cloned().unwrap_or_default());
2240    let struct_hash = eip712_hash_struct(&primary, message, &type_map);
2241    let mut out = vec![0x19u8, 0x01u8];
2242    out.extend_from_slice(&domain_sep);
2243    out.extend_from_slice(&struct_hash);
2244    out
2245}
2246
2247/// EIP-712 `hashStruct(typeName, data)`: keccak(typeHash ‖ encoded-fields),
2248/// where a field whose type is itself a struct in `types` is hashed recursively.
2249fn eip712_hash_struct(type_name: &str, data: &Value, types: &Eip712Types) -> Vec<u8> {
2250    let type_str = eip712_encode_type(type_name, types);
2251    let mut enc = hash_raw(type_str.as_bytes(), "keccak"); // typeHash (32 bytes)
2252    let dm = match data { Value::Dict(m) => Some(m), _ => None };
2253    let fields = types.get(type_name).cloned().unwrap_or_default();
2254    for (name, ty) in &fields {
2255        let v = dm.and_then(|m| m.get(name)).cloned().unwrap_or(Value::Null);
2256        let base = eip712_base_type(ty);
2257        if types.contains_key(base) {
2258            // Nested struct field — recurse.
2259            enc.extend_from_slice(&eip712_hash_struct(base, &v, types));
2260        } else {
2261            enc.extend_from_slice(&eip712_encode_value(ty, &v));
2262        }
2263    }
2264    hash_raw(&enc, "keccak")
2265}
2266
2267/// Encodes an integer into a 32-byte EIP-712 / ABI word for a `uintN`/`intN`
2268/// type, validating the declared bit width. Fails closed (panics) on a negative
2269/// value in an unsigned type, or any value that overflows the declared width,
2270/// instead of silently truncating to 32 bytes or routing a negative through the
2271/// unsigned branch (review #15). Valid, in-range values encode exactly as
2272/// before (big-endian right-aligned for uint; two's-complement sign-extended
2273/// for int), so signing of well-formed payloads is unchanged.
2274pub(crate) fn eip712_int_word(ty: &str, n: &num_bigint::BigInt) -> [u8; 32] {
2275    use num_bigint::{BigInt, Sign};
2276    let signed = ty.starts_with("int");
2277    let digits = ty.trim_start_matches(if signed { "int" } else { "uint" });
2278    let mut width: usize = if digits.is_empty() { 256 } else { digits.parse().unwrap_or(256) };
2279    if !((8..=256).contains(&width) && width % 8 == 0) { width = 256; }
2280    let mut out = [0u8; 32];
2281    if !signed {
2282        if n.sign() == Sign::Minus {
2283            panic!("eip712/abi: negative value {n} supplied for unsigned type {ty}");
2284        }
2285        let max = (BigInt::from(1) << width) - 1;
2286        if n > &max {
2287            panic!("eip712/abi: value {n} overflows {ty} (max {max})");
2288        }
2289        let (_, be) = n.to_bytes_be();
2290        let take = be.len().min(32);
2291        out[32 - take..].copy_from_slice(&be[be.len() - take..]);
2292    } else {
2293        let min = -(BigInt::from(1) << (width - 1));
2294        let max = (BigInt::from(1) << (width - 1)) - 1;
2295        if n < &min || n > &max {
2296            panic!("eip712/abi: value {n} out of range for {ty} ([{min}, {max}])");
2297        }
2298        if n.sign() == Sign::Minus { out = [0xff; 32]; }
2299        let be = n.to_signed_bytes_be();
2300        let take = be.len().min(32);
2301        out[32 - take..].copy_from_slice(&be[be.len() - take..]);
2302    }
2303    out
2304}
2305
2306fn eip712_encode_value(ty: &str, v: &Value) -> [u8; 32] {
2307    let mut out = [0u8; 32];
2308    if ty == "string" || ty == "bytes" {
2309        out.copy_from_slice(&hash_raw(&value_to_bytes(v), "keccak"));
2310    } else if ty.starts_with("bytes") {
2311        // bytesN — left-aligned.
2312        let b = eip712_bytes(v);
2313        let n = b.len().min(32);
2314        out[..n].copy_from_slice(&b[..n]);
2315    } else if ty == "address" {
2316        // 20-byte address, right-aligned (left-padded with zeros).
2317        let b = eip712_bytes(v);
2318        let take = b.len().min(20);
2319        out[32 - take..].copy_from_slice(&b[b.len() - take..]);
2320    } else if ty == "bool" {
2321        if matches!(v, Value::Bool(true)) { out[31] = 1; }
2322    } else if ty.starts_with("uint") || ty.starts_with("int") {
2323        // uint256 (e.g. polymarket tokenId) exceeds u128 — use BigInt. Signed
2324        // intN uses two's-complement, sign-extended to 32 bytes.
2325        use num_bigint::BigInt;
2326        let n: BigInt = match v {
2327            Value::Int(i)   => BigInt::from(*i),
2328            Value::Float(f) => BigInt::from(*f as i64),
2329            Value::Str(s)   => {
2330                let t = s.trim();
2331                if let Some(h) = t.strip_prefix("0x") {
2332                    BigInt::parse_bytes(h.as_bytes(), 16).unwrap_or_default()
2333                } else {
2334                    BigInt::parse_bytes(t.as_bytes(), 10).unwrap_or_default()
2335                }
2336            }
2337            _ => BigInt::from(0),
2338        };
2339        out = eip712_int_word(ty, &n);
2340    }
2341    out
2342}
2343
2344/// Decode an EIP-712 byte value: a `0x`-hex string or a byte-array Value.
2345fn eip712_bytes(v: &Value) -> Vec<u8> {
2346    match v {
2347        Value::Str(s) => {
2348            let h = s.strip_prefix("0x").unwrap_or(s);
2349            hex::decode(h).unwrap_or_else(|_| s.as_bytes().to_vec())
2350        }
2351        _ => value_to_bytes(v),
2352    }
2353}
2354
2355pub(crate) fn value_to_bytes(v: &Value) -> Vec<u8> {
2356    match v {
2357        Value::Str(s) => s.as_bytes().to_vec(),
2358        Value::Arr(a) => a.iter().filter_map(|x| match x {
2359            Value::Int(n) => Some(*n as u8),
2360            _ => None,
2361        }).collect(),
2362        _ => Vec::new(),
2363    }
2364}
2365
2366pub(crate) fn url_pct(s: &str) -> String {
2367    s.bytes().map(|b| match b {
2368        b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
2369        _ => format!("%{b:02X}"),
2370    }).collect()
2371}
2372
2373/// Pins the `mock_response` contract that `request_typed` implements: the canned
2374/// payload is returned by `fetch_typed` only AFTER the request has been built and
2375/// signed, so `last_request_url` / `_headers` / `_body` still describe the real
2376/// request a static *response* fixture would have sent; and the payload stays set
2377/// until the caller replaces or clears it, so one fixture can serve the several
2378/// `fetch_typed` calls a single paginating `fetchX` issues.
2379#[cfg(all(test, feature = "engine", feature = "binance"))]
2380mod response_mock_tests {
2381    use super::ExchangeRuntime;
2382    use crate::{get_value, Value};
2383
2384    #[tokio::test]
2385    async fn response_mock_serves_multiple_requests_until_reset() {
2386        // Conflicting proxies reject any unmocked request before network I/O.
2387        let config = Value::from_json(&serde_json::json!({
2388            "httpProxy": "http://fake:8080", "httpsProxy": "http://fake:8080",
2389            "enableRateLimit": false,
2390        }));
2391        let mut exchange = crate::exchanges::binance::BinanceCore::new(Some(config));
2392        let response = Value::from_json(&serde_json::json!({ "price": "100" }));
2393        exchange.exchange.mock_response = response.clone();
2394        for symbol in ["BTCUSDT", "ETHUSDT"] {
2395            let params = Value::from_json(&serde_json::json!({ "symbol": symbol }));
2396            let result = exchange.request_typed(
2397                "ticker/price", &["public".to_string()], "GET", params, Value::Int(1),
2398            ).await.expect("each request must use the same mock without network access");
2399            assert_eq!(result, response);
2400            assert_eq!(exchange.exchange.last_request_url, Value::Str(format!(
2401                "https://api.binance.com/api/v3/ticker/price?symbol={symbol}",
2402            ).into()));
2403        }
2404        exchange.exchange.mock_response = Value::Null;
2405        let error = exchange.request_typed(
2406            "ticker/price", &["public".to_string()], "GET", Value::Null, Value::Int(1),
2407        ).await.expect_err("reset must restore the normal transport path");
2408        assert!(error.to_string().contains("InvalidProxySettings"));
2409    }
2410
2411    #[tokio::test]
2412    async fn response_mock_preserves_public_request_url() {
2413        let mut exchange = crate::exchanges::binance::BinanceCore::new(None);
2414        let response = Value::from_json(&serde_json::json!({ "price": "100" }));
2415        exchange.exchange.mock_response = response.clone();
2416        let params = Value::from_json(&serde_json::json!({ "symbol": "BTCUSDT" }));
2417        let result = exchange.request_typed(
2418            "ticker/price", &["public".to_string()], "GET", params, Value::Int(1),
2419        ).await.expect("mock response must not require network access");
2420        assert_eq!(result, response);
2421        assert_eq!(exchange.exchange.last_request_url, Value::Str(
2422            "https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT".into(),
2423        ));
2424        assert_eq!(exchange.exchange.last_request_body, Value::Null);
2425    }
2426
2427    #[tokio::test]
2428    async fn response_mock_preserves_private_request_headers_and_body() {
2429        let config = Value::from_json(&serde_json::json!({
2430            "apiKey": "fixture-key", "secret": "fixture-secret",
2431        }));
2432        let mut exchange = crate::exchanges::binance::BinanceCore::new(Some(config));
2433        let response = Value::from_json(&serde_json::json!({ "orderId": 123 }));
2434        exchange.exchange.mock_response = response.clone();
2435        let params = Value::from_json(&serde_json::json!({
2436            "symbol": "BTCUSDT", "side": "BUY", "type": "MARKET", "quantity": "1",
2437        }));
2438        let result = exchange.request_typed(
2439            "order", &["private".to_string()], "POST", params, Value::Int(1),
2440        ).await.expect("signed mock response must not require network access");
2441        assert_eq!(result, response);
2442        assert_eq!(exchange.exchange.last_request_url, Value::Str(
2443            "https://api.binance.com/api/v3/order".into(),
2444        ));
2445        assert_eq!(get_value(&exchange.exchange.last_request_headers,
2446            &Value::Str("X-MBX-APIKEY".into())), Value::Str("fixture-key".into()));
2447        let Value::Str(body) = &exchange.exchange.last_request_body else {
2448            panic!("signed POST must retain its encoded body");
2449        };
2450        assert!(body.contains("symbol=BTCUSDT"));
2451        assert!(body.contains("signature="));
2452    }
2453}
2454
2455/// Pins `method_name_to_snake_case` — the transform that decides whether a
2456/// paginated `this[method](...)` re-entry lands on a `call_dynamic` arm — against
2457/// the two implementations it must agree with: the transpiler's `toSnakeCase`
2458/// (`build/rustTranspiler.ts`, which names the arms) and `Exchange::to_snake_case`
2459/// (which names the implicit-API entries the `_` arm falls through to).
2460/// Requested in review on #30385.
2461#[cfg(test)]
2462mod method_name_snake_case_tests {
2463    use super::{method_name_to_snake_case, Exchange};
2464    use crate::Value;
2465
2466    fn snake(name: &str) -> String {
2467        method_name_to_snake_case(&Value::Str(name.to_string().into()))
2468    }
2469
2470    // The four names the review called out, plus the digit/acronym shapes that
2471    // are the only places the three transforms could plausibly diverge.
2472    #[test]
2473    fn matches_the_transpiler_dispatch_arm_names() {
2474        // unified methods re-entered by fetchPaginatedCall* — these must hit an arm
2475        assert_eq!(snake("fetchTransfers"), "fetch_transfers");
2476        assert_eq!(snake("fetchOHLCV"), "fetch_ohlcv");                 // trailing acronym
2477        assert_eq!(snake("fetchOpenOrdersWs"), "fetch_open_orders_ws");
2478        assert_eq!(snake("fetchL2OrderBook"), "fetch_l2_order_book");   // letter+digit token
2479        assert_eq!(snake("getLeverageTiersPaginated"), "get_leverage_tiers_paginated");
2480        // implicit endpoints re-entered by fetchWebEndpoint — these must hit the
2481        // `_` arm's implicit_api lookup, which is keyed by to_snake_case
2482        assert_eq!(snake("publicGetTicker24hr"), "public_get_ticker24hr"); // NO `_` before a digit
2483        assert_eq!(snake("webExchangeGetV3Assets"), "web_exchange_get_v3_assets");
2484        assert_eq!(snake("webApiGetAjaxCoinCoinInfo"), "web_api_get_ajax_coin_coin_info");
2485        // acronym runs: `[A-Z]+[A-Z][a-z]` splits before the last capital only
2486        assert_eq!(snake("parseHTTPResponse"), "parse_http_response");
2487        assert_eq!(snake("fetchOHLCVWs"), "fetch_ohlcv_ws");
2488        // already-snake and single-token names are pass-through
2489        assert_eq!(snake("fetch"), "fetch");
2490        assert_eq!(snake("fetch_transfers"), "fetch_transfers");
2491    }
2492
2493    // `method_name_to_snake_case` and `Exchange::to_snake_case` must produce the
2494    // SAME key, or a dynamic name would snake to something the implicit-api map
2495    // does not hold. Differential over the shapes above; the full 11k-name sweep
2496    // over every ts/src method + abstract endpoint also reports zero divergence.
2497    #[test]
2498    fn agrees_with_exchange_to_snake_case() {
2499        for name in [
2500            "fetchTransfers", "fetchOHLCV", "fetchOpenOrdersWs", "publicGetTicker24hr",
2501            "fetchL2OrderBook", "webExchangeGetV3Assets", "webApiGetAjaxCoinCoinInfo",
2502            "parseHTTPResponse", "fetchOHLCVWs", "privatePostSPEIWithdrawal",
2503            "sapiV3GetAsset", "fapiPublicGetTicker24hr", "publicGet10PublicTickers",
2504            "fetch", "fetchPositionsRisk", "createOrderWs", "fetchMyLiquidations",
2505        ] {
2506            assert_eq!(
2507                snake(name),
2508                Exchange::to_snake_case(name),
2509                "method_name_to_snake_case and Exchange::to_snake_case diverge on {name}",
2510            );
2511        }
2512    }
2513
2514    // A non-string / empty dynamic name used to snake to "" and then resolve to
2515    // Value::Null — a silent empty page. It must be loud instead.
2516    #[test]
2517    #[should_panic(expected = "NotSupported")]
2518    fn non_string_method_name_is_loud() {
2519        let _ = method_name_to_snake_case(&Value::Int(7));
2520    }
2521
2522    #[test]
2523    #[should_panic(expected = "NotSupported")]
2524    fn empty_method_name_is_loud() {
2525        let _ = method_name_to_snake_case(&Value::Str(String::new().into()));
2526    }
2527}
2528
2529#[cfg(test)]
2530mod eip712_int_tests {
2531    use super::eip712_int_word;
2532    use num_bigint::BigInt;
2533
2534    #[test]
2535    fn uint8_max_ok_and_int8_bounds_ok() {
2536        assert_eq!(eip712_int_word("uint8", &BigInt::from(255))[31], 255);
2537        let _ = eip712_int_word("int8", &BigInt::from(127));
2538        let _ = eip712_int_word("int8", &BigInt::from(-128));
2539    }
2540
2541    #[test]
2542    fn i64_u64_boundaries_ok() {
2543        let _ = eip712_int_word("int64", &BigInt::from(i64::MAX));
2544        let _ = eip712_int_word("int64", &BigInt::from(i64::MIN));
2545        let _ = eip712_int_word("uint64", &BigInt::from(u64::MAX));
2546    }
2547
2548    // u64::MAX + 1 (2^64) must fit a uint256 exactly: 0x01 followed by 8 zero
2549    // bytes, right-aligned → byte index 23.
2550    #[test]
2551    fn u64_plus_one_preserved_in_uint256() {
2552        let n = BigInt::from(u64::MAX) + 1;
2553        assert_eq!(eip712_int_word("uint256", &n)[23], 1);
2554    }
2555
2556    #[test]
2557    fn negative_int_is_twos_complement() {
2558        assert_eq!(eip712_int_word("int256", &BigInt::from(-1)), [0xff; 32]);
2559    }
2560
2561    #[test]
2562    #[should_panic(expected = "overflows")]
2563    fn uint8_overflow_rejected() { let _ = eip712_int_word("uint8", &BigInt::from(256)); }
2564
2565    #[test]
2566    #[should_panic(expected = "negative")]
2567    fn uint_negative_rejected() { let _ = eip712_int_word("uint256", &BigInt::from(-1)); }
2568
2569    #[test]
2570    #[should_panic(expected = "out of range")]
2571    fn int8_overflow_rejected() { let _ = eip712_int_word("int8", &BigInt::from(128)); }
2572
2573    #[test]
2574    #[should_panic(expected = "overflows")]
2575    fn uint64_plus_one_rejected() {
2576        let _ = eip712_int_word("uint64", &(BigInt::from(u64::MAX) + 1));
2577    }
2578}
2579
2580#[cfg(test)]
2581mod throttle_tests {
2582    use super::Exchange;
2583    use crate::Value;
2584
2585    #[test]
2586    fn implicit_api_retains_endpoint_cost_config() {
2587        let mut by_limit = crate::value::HashMap::new();
2588        by_limit.insert("cost".to_string(), Value::Int(2));
2589        by_limit.insert("byLimit".to_string(), Value::List(vec![
2590            Value::List(vec![Value::Int(100), Value::Int(5)]),
2591        ]));
2592        let mut endpoints = crate::value::HashMap::new();
2593        endpoints.insert("ticker".to_string(), Value::Float(0.1));
2594        endpoints.insert("depth".to_string(), Value::Map(by_limit.clone()));
2595        let mut verbs = crate::value::HashMap::new();
2596        verbs.insert("get".to_string(), Value::Map(endpoints));
2597        let mut api = crate::value::HashMap::new();
2598        api.insert("public".to_string(), Value::Map(verbs));
2599        let mut exchange = Exchange::new(None);
2600        exchange.api = Value::Map(api);
2601        exchange.build_implicit_api();
2602        let ticker_config = &exchange.internals.implicit_api["public_get_ticker"].3;
2603        assert_eq!(
2604            crate::get_value(ticker_config, &Value::Str("cost".into())),
2605            Value::Float(0.1),
2606            "numeric endpoint costs must be normalized to a config object"
2607        );
2608        let depth_config = &exchange.internals.implicit_api["public_get_depth"].3;
2609        assert_eq!(depth_config, &Value::Map(by_limit), "object endpoint config must be retained");
2610    }
2611
2612    // The leaky-bucket limiter must space requests by ~rateLimit ms (real time).
2613    #[tokio::test]
2614    async fn spaces_requests_by_rate_limit() {
2615        let mut ex = Exchange::new(None);
2616        ex.enableRateLimit = Value::Bool(true);
2617        ex.rateLimit = Value::Int(15); // 15 ms per token
2618        let start = std::time::Instant::now();
2619        for _ in 0..5 { ex.throttle(&[]).await; }
2620        let elapsed = start.elapsed().as_millis();
2621        // 1st immediate, next 4 each wait ~15ms → ≥ ~45ms (generous lower bound).
2622        assert!(elapsed >= 45, "throttle did not space requests: {elapsed}ms");
2623    }
2624
2625    // Disabled rate limiting must not sleep at all.
2626    #[tokio::test]
2627    async fn disabled_is_noop() {
2628        let mut ex = Exchange::new(None);
2629        ex.enableRateLimit = Value::Bool(false);
2630        ex.rateLimit = Value::Int(1000);
2631        let start = std::time::Instant::now();
2632        for _ in 0..5 { ex.throttle(&[]).await; }
2633        assert!(start.elapsed().as_millis() < 50, "disabled throttle slept");
2634    }
2635}
2636
2637#[cfg(all(test, feature = "engine", feature = "binance"))]
2638mod rate_limit_config_tests {
2639    use crate::exchange::ExchangeRuntime;
2640    use crate::exchange_generated::ExchangeBase;
2641    use crate::Value;
2642
2643    // init() must apply describe().rateLimit so the limiter spaces requests at
2644    // the venue rate instead of the base 2000ms default (review #8). binance
2645    // declares rateLimit: 50.
2646    #[test]
2647    fn binance_init_applies_describe_rate_limit() {
2648        let b = crate::exchanges::binance::BinanceCore::new(None);
2649        assert_eq!(
2650            b.exchange.rateLimit,
2651            Value::Int(50),
2652            "init() dropped describe().rateLimit; got {:?}",
2653            b.exchange.rateLimit
2654        );
2655    }
2656
2657    // A caller-supplied rateLimit must win over describe()'s value.
2658    #[test]
2659    fn config_rate_limit_overrides_describe() {
2660        let mut cfg = crate::value::HashMap::new();
2661        cfg.insert("rateLimit".to_string(), Value::Int(123));
2662        let b = crate::exchanges::binance::BinanceCore::new(Some(Value::Map(cfg)));
2663        assert_eq!(b.exchange.rateLimit, Value::Int(123), "config rateLimit was clobbered by describe()");
2664    }
2665
2666    #[tokio::test]
2667    async fn implicit_api_preserves_and_calculates_endpoint_cost() {
2668        let mut binance = crate::exchanges::binance::BinanceCore::new(None);
2669        binance.build_implicit_api();
2670        let config = binance
2671            .exchange
2672            .internals
2673            .implicit_api
2674            .get("fapi_public_get_depth")
2675            .expect("Binance futures depth endpoint must be registered")
2676            .3
2677            .clone();
2678        assert_eq!(
2679            crate::get_value(&config, &Value::Str("cost".into())),
2680            Value::Int(2),
2681            "the implicit API table dropped the endpoint's base cost"
2682        );
2683        let params = Value::Map({
2684            let mut map = crate::value::HashMap::new();
2685            map.insert("limit".to_string(), Value::Int(100));
2686            map
2687        });
2688        let cost = binance
2689            .implicit_api_rate_limit_cost("fapi_public_get_depth", params)
2690            .await
2691            .expect("registered endpoint must have a calculable cost");
2692        assert_eq!(cost, Value::Int(5), "Binance byLimit cost was not applied");
2693    }
2694}
2695
2696#[cfg(all(test, feature = "engine", feature = "binance"))]
2697mod sandbox_mode_tests {
2698    use crate::Value;
2699
2700    // super_set_sandbox_mode was a no-op, so venues that override setSandboxMode
2701    // (binance, okx, gate, …) never actually switched to their sandbox URL
2702    // (review #9). After delegating to the base, set_sandbox_mode(true) must
2703    // swap urls['api'] -> urls['test'] and toggle isSandboxModeEnabled.
2704    #[test]
2705    fn binance_sandbox_swaps_api_url() {
2706        let mut b = crate::exchanges::binance::BinanceCore::new(None);
2707        let test_url = crate::get_value(&b.exchange.urls, &Value::Str("test".into()));
2708        assert!(!matches!(test_url, Value::Null), "binance describe() has no test url");
2709        b.set_sandbox_mode(Value::Bool(true));
2710        assert_eq!(b.exchange.isSandboxModeEnabled, Value::Bool(true));
2711        let api_url = crate::get_value(&b.exchange.urls, &Value::Str("api".into()));
2712        assert_eq!(api_url, test_url, "sandbox mode did not switch urls['api'] to urls['test']");
2713    }
2714}
2715
2716#[cfg(all(test, feature = "engine", feature = "binance"))]
2717mod dynamic_dispatch_tests {
2718    use crate::exchange::CallDynamicChecked;
2719    use crate::exchange_generated::ExchangeBase;
2720    use crate::Value;
2721
2722    // The three behaviours the review on #30385 asked for, on the real dispatch
2723    // table (binance's Core) rather than on the name transform alone.
2724
2725    // 1. A unified method re-entered dynamically — the case the PR fixes — must
2726    //    reach a dispatch arm and NOT the `_ => Null` fall-through.
2727    //    `call_method` could never resolve `fetchOHLCV` (it only knows implicit
2728    //    endpoints), so pagination hard-failed with NotSupported. Probe the
2729    //    fall-through directly: dispatch the name and require that the `_` arm
2730    //    did not record a miss for it, which is only true when a real arm
2731    //    matched. `fetch_ohlcv` with no args returns without any network I/O
2732    //    (binance's override throws ArgumentsRequired on a null symbol), so
2733    //    catch the unwind and inspect the miss flag rather than the result.
2734    #[tokio::test]
2735    async fn unified_method_reaches_a_dispatch_arm_not_the_null_fallthrough() {
2736        let mut b = crate::exchanges::binance::BinanceCore::new(None);
2737        let snake = crate::exchange::method_name_to_snake_case(
2738            &Value::Str("fetchOHLCV".into()));
2739        assert_eq!(snake, "fetch_ohlcv");
2740        b.exchange.internals.dynamic_dispatch_miss = None;
2741        let _ = futures::FutureExt::catch_unwind(
2742            std::panic::AssertUnwindSafe(b.call_dynamic(&snake, vec![])),
2743        ).await;
2744        assert_eq!(
2745            b.exchange.internals.dynamic_dispatch_miss, None,
2746            "`{snake}` fell through to the `_ => Null` arm — a paginated \
2747             re-entry would have silently returned an empty page",
2748        );
2749        // Negative control for the probe itself: a name with no arm DOES record.
2750        let _ = b.call_dynamic("fetch_definitely_not_an_arm", vec![]).await;
2751        assert_eq!(
2752            b.exchange.internals.dynamic_dispatch_miss.as_deref(),
2753            Some("fetch_definitely_not_an_arm"),
2754            "the miss probe is inert — the assertion above proves nothing",
2755        );
2756    }
2757
2758    // 2. An implicit endpoint re-entered dynamically (fetchWebEndpoint's
2759    //    endpointMethod) still routes through the `_` arm's implicit_api
2760    //    lookup — the PR must not have broken direct implicit calls.
2761    #[tokio::test]
2762    async fn implicit_endpoint_is_still_reachable_and_is_not_a_miss() {
2763        let mut b = crate::exchanges::binance::BinanceCore::new(None);
2764        b.exchange.build_implicit_api();
2765        let snake = crate::exchange::method_name_to_snake_case(
2766            &Value::Str("publicGetTicker24hr".into()));
2767        assert!(
2768            b.exchange.internals.implicit_api.contains_key(&snake),
2769            "implicit api has no `{snake}` entry — the `_` arm would treat a real \
2770             endpoint as an unknown name",
2771        );
2772    }
2773
2774    // 3. THE REGRESSION GUARD. A name that is neither a dispatch arm nor an
2775    //    implicit endpoint used to yield `Value::Null` — a silent empty page.
2776    //    `call_dynamic_checked` must turn it back into a loud NotSupported,
2777    //    the way `call_method` used to fail.
2778    #[tokio::test]
2779    #[should_panic(expected = "NotSupported")]
2780    async fn unknown_dynamic_name_is_loud_not_null() {
2781        let mut b = crate::exchanges::binance::BinanceCore::new(None);
2782        let _ = b.call_dynamic_checked(
2783            Value::Str("fetchNoSuchThingAtAll".into()),
2784            vec![],
2785        ).await;
2786    }
2787
2788    // …and the bare `call_dynamic` it wraps still returns Null for that name,
2789    // so the loudness comes from the wrapper and optional probes stay cheap.
2790    #[tokio::test]
2791    async fn bare_call_dynamic_still_returns_null_for_optional_probes() {
2792        let mut b = crate::exchanges::binance::BinanceCore::new(None);
2793        let out = b.call_dynamic("fetch_no_such_thing_at_all", vec![]).await;
2794        assert_eq!(out, Value::Null);
2795        assert_eq!(
2796            b.exchange.internals.dynamic_dispatch_miss.as_deref(),
2797            Some("fetch_no_such_thing_at_all"),
2798            "the `_` arm did not record the miss, so call_dynamic_checked \
2799             could never raise on it",
2800        );
2801    }
2802}
2803
2804#[cfg(all(test, feature = "engine"))]
2805mod cow_alias_tests {
2806    use super::Exchange;
2807    use crate::Value;
2808    use crate::runtime::get_array_length;
2809
2810    // convertOHLCVToTradingView does `result[key].push(...)` on an extracted
2811    // local — a COW clone in Rust. Without the write-back the result columns
2812    // stay empty. Assert the data survives (review P0-C).
2813    #[test]
2814    fn convert_ohlcv_to_trading_view_preserves_pushes() {
2815        use crate::exchange_generated::ExchangeBase;
2816        let ex = super::BaseCore::new(Exchange::new(None));
2817        let row = Value::List(vec![
2818            Value::Int(1_700_000_000_000), Value::Int(1), Value::Int(2),
2819            Value::Int(0), Value::Int(1), Value::Int(10),
2820        ]);
2821        let ohlcvs = Value::List(vec![row.clone(), row]);
2822        let r = ex.convert_ohlcv_to_trading_view(ohlcvs, &[]);
2823        for key in ["t", "o", "h", "l", "c", "v"] {
2824            let col = crate::get_value(&r, &Value::Str(key.to_string().into()));
2825            assert_eq!(get_array_length(&col), Value::Int(2),
2826                "result['{key}'] lost its pushes — COW write-back failed");
2827        }
2828    }
2829}
2830
2831#[cfg(test)]
2832mod http_error_tests {
2833    use super::{BaseCore, DerivedExchange, Exchange, ExchangeRuntime};
2834    use crate::Value;
2835    use futures::FutureExt;
2836    use std::io::{Read, Write};
2837
2838    // Answers one request on a local port with the given status line and body.
2839    fn serve_once(status_line: &'static str, body: &'static str) -> String {
2840        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2841        let url = format!("http://{}/", listener.local_addr().unwrap());
2842        std::thread::spawn(move || {
2843            let (mut stream, _) = listener.accept().unwrap();
2844            let mut request = [0u8; 4096];
2845            let _ = stream.read(&mut request);
2846            let response = format!(
2847                "HTTP/1.1 {status_line}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
2848                body.len(),
2849            );
2850            stream.write_all(response.as_bytes()).unwrap();
2851        });
2852        url
2853    }
2854
2855    // A venue that reports failures inside a 200 body, the way okx does.
2856    struct EnvelopeCore {
2857        exchange: Exchange,
2858    }
2859    impl std::ops::Deref for EnvelopeCore {
2860        type Target = Exchange;
2861        fn deref(&self) -> &Exchange { &self.exchange }
2862    }
2863    impl std::ops::DerefMut for EnvelopeCore {
2864        fn deref_mut(&mut self) -> &mut Exchange { &mut self.exchange }
2865    }
2866    impl DerivedExchange for EnvelopeCore {
2867        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 {
2868            let code = crate::get_value(&response, &Value::Str("code".into()));
2869            if !matches!(code, Value::Null) && code != Value::Str("0".into()) {
2870                panic!("{}", crate::exchange_errors::create_error("InsufficientFunds", "code 51008"));
2871            }
2872            Value::Null
2873        }
2874    }
2875    impl crate::exchange_generated::ExchangeBase for EnvelopeCore {
2876        fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<Value>)
2877            -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>>
2878        {
2879            Box::pin(async move { self.call_dynamic_base(method, args).await })
2880        }
2881    }
2882
2883    async fn fetch_error<C: ExchangeRuntime + Send>(core: &mut C, url: String) -> String {
2884        let outcome = std::panic::AssertUnwindSafe(core.fetch(Value::Str(url.into()), &[])).catch_unwind().await;
2885        match outcome {
2886            Ok(value) => format!("no error, returned {value:?}"),
2887            Err(payload) => payload.downcast_ref::<String>().cloned().unwrap_or_default(),
2888        }
2889    }
2890
2891    #[tokio::test]
2892    async fn an_error_in_a_2xx_body_reaches_handle_errors() {
2893        let url = serve_once("200 OK", r#"{"code":"51008","msg":"Insufficient balance"}"#);
2894        let mut core = EnvelopeCore { exchange: Exchange::new(None) };
2895        let error = fetch_error(&mut core, url).await;
2896        assert!(error.contains("InsufficientFunds"), "{error}");
2897    }
2898
2899    #[tokio::test]
2900    async fn a_status_in_http_exceptions_raises_its_class() {
2901        let url = serve_once("401 Unauthorized", "{}");
2902        let mut core = BaseCore::new(Exchange::new(None));
2903        let error = fetch_error(&mut core, url).await;
2904        assert!(error.contains("AuthenticationError"), "{error}");
2905    }
2906
2907    #[tokio::test]
2908    async fn a_status_outside_http_exceptions_still_fails() {
2909        let url = serve_once("402 Payment Required", "{}");
2910        let mut core = BaseCore::new(Exchange::new(None));
2911        let error = fetch_error(&mut core, url).await;
2912        assert!(error.contains("ExchangeError"), "{error}");
2913    }
2914}