Skip to main content

ccxt_common/
exchange.rs

1// Native Rust – Exchange base class.
2//
3// Methods BELOW the `METHODS BELOW THIS LINE ARE TRANSPILED FROM TYPESCRIPT`
4// marker in `ts/src/base/Exchange.ts` are transpiled into
5// `exchange_generated.rs` (opt-in behind the `transpiled-base` feature
6// while the transpiler-port is in progress).
7//
8// Methods ABOVE the marker are hand-written here — they are the
9// language-specific pieces that can't be transpiled:
10//   • HTTP client (reqwest)
11//   • Cryptographic primitives (HMAC-SHA256/512, SHA256/512, MD5)
12//   • Base64/hex encoding, URL-encoding, JSON
13//   • String utilities mirroring CCXT's `js/src/base/functions.ts`
14//
15// **Field layout.** The transpiler treats every field on Exchange as
16// `Value` (Python/PHP-style dynamic typing). To stay compatible without
17// fighting Rust's type system, every public field on `Exchange` is
18// `crate::Value` — transpiled code can read/write them directly.
19// Rust-typed runtime state (the HTTP client, the verbose flag, etc.)
20// lives on the private `Internals` sub-struct.
21
22#![allow(non_snake_case)]
23
24use indexmap::IndexMap as HashMap;
25use std::sync::Arc;
26use hmac::{Hmac, Mac};
27use sha2::{Sha256, Sha512, Digest as Sha2Digest};
28use sha1::Sha1;
29use md5::Md5;
30use base64::{engine::general_purpose::STANDARD as B64, Engine as _};
31use crate::{Value, ExchangeError, Result};
32
33type HmacSha256 = Hmac<Sha256>;
34type HmacSha512 = Hmac<Sha512>;
35type HmacSha1   = Hmac<Sha1>;
36type HmacMd5    = Hmac<Md5>;
37
38/// Callback type used by derived exchanges to provide their `describe()` data.
39pub type DescribeCallback = Arc<dyn Fn() -> Value + Send + Sync>;
40
41// HTTP/JSON timing counters — accumulated by `fetch_typed`, read+reset
42// by the CLI / benchmarks via `take_http_timings()`.
43static HTTP_NANOS:  std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
44static JSON_NANOS:  std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
45static HTTP_CALLS:  std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
46
47tokio::task_local! {
48    // URLs whose WS drive loop is active on the current task's call stack. A
49    // spawned coroutine that does a nested `self.watch(sameUrl)` (bitvavo's
50    // getBook, htx's snapshot req) must NOT start a second drive loop — that
51    // would block the outer loop on a hash the outer loop is responsible for
52    // resolving. Instead it just sends its subscribe frame and returns; the
53    // outer loop processes the reply. Task-local so it survives task migration.
54    static WS_DRIVEN_URLS: std::sync::Mutex<std::collections::HashSet<String>>;
55}
56
57/// Snapshot + reset the global HTTP/JSON timings. Returns
58/// `(http_nanos, json_nanos, http_calls)` and zeroes them.
59pub fn take_http_timings() -> (u64, u64, u64) {
60    use std::sync::atomic::Ordering::Relaxed;
61    (
62        HTTP_NANOS.swap(0, Relaxed),
63        JSON_NANOS.swap(0, Relaxed),
64        HTTP_CALLS.swap(0, Relaxed),
65    )
66}
67
68// ── Internals (Rust-typed runtime state, not exposed to transpiled code) ─────
69
70pub struct Internals {
71    pub http_client:    Option<reqwest::Client>,
72    pub describe_cb:    Option<DescribeCallback>,
73    pub last_rest_ts:   i64,
74    pub headers:        HashMap<String, String>,
75    /// Leaky-bucket rate-limiter state, `(tokens, last_refill_ms)`, shared and
76    /// interior-mutable so the `&self` async `throttle()` can serialize requests
77    /// on one exchange instance. See `Exchange::throttle`.
78    pub throttle:       std::sync::Arc<tokio::sync::Mutex<(f64, i64)>>,
79    /// Cached dispatch table built from `self.api`. Maps the snake-case
80    /// implicit API name (e.g. `public_get_exchange_info`) to
81    /// `(path, api_scope, http_verb, endpoint_config)`.
82    pub implicit_api:   HashMap<String, (String, Vec<String>, String, Value)>,
83    /// Method names currently being dispatched to a derived override. Lets the
84    /// async `dispatch_to_derived` default (in `ExchangeBase`) block recursion
85    /// on a single method while allowing sibling dispatches. This is the only
86    /// dispatch state left — virtual dispatch itself is now static (review #1),
87    /// so there are no raw self-pointers to keep.
88    pub dispatch_stack:       Vec<String>,
89    /// Last snake_case name that reached `call_dynamic_base`'s `_` arm and
90    /// matched neither a dispatch arm nor an implicit-API endpoint. That arm
91    /// must keep returning `Value::Null` (a static-request test may probe an
92    /// optional name), but a dynamic re-entry from `fetchPaginatedCall*` /
93    /// `fetchWebEndpoint` treats a miss as fatal — see
94    /// `crate::exchange::call_dynamic_required`.
95    pub dynamic_dispatch_miss: Option<String>,
96}
97
98/// The Go-style "interface" that every derived exchange implements. When
99/// Exchange.ts calls `this.parseTicker(...)` (and similar), the transpiler
100/// rewrites it to `self.derived().parse_ticker(...)`; that goes through
101/// this trait's vtable to the derived exchange's override.
102///
103/// Default impls return `Value::Null` so an unbound Exchange still
104/// compiles and runs (it just gives back empty results).
105pub trait DerivedExchange {
106    // ── parsers (the dominant override surface) ──────────────────────────
107    fn parse_ticker(&self, _ticker: Value, _market: Value) -> Value { Value::Null }
108    fn parse_trade(&self, _trade: Value, _market: Value) -> Value { Value::Null }
109    fn parse_order(&self, _order: Value, _market: Value) -> Value { Value::Null }
110    fn parse_market(&self, _market: Value) -> Value { Value::Null }
111    fn parse_ohlcv(&self, _ohlcv: Value, _market: Value) -> Value { Value::Null }
112    fn parse_order_book(&self, _ob: Value, _symbol: Value, _ts: Value, _bk: Value, _ak: Value, _pk: Value, _ak2: Value, _ck: Value) -> Value { Value::Null }
113    fn parse_balance(&self, _response: Value) -> Value { Value::Null }
114    fn parse_position(&self, _position: Value, _market: Value) -> Value { Value::Null }
115    fn parse_funding_rate(&self, _rate: Value, _market: Value) -> Value { Value::Null }
116    fn parse_deposit(&self, _tx: Value, _currency: Value) -> Value { Value::Null }
117    fn parse_deposit_address(&self, _addr: Value, _currency: Value) -> Value { Value::Null }
118    fn parse_last_price(&self, _entry: Value, _market: Value) -> Value { Value::Null }
119    fn parse_withdrawal(&self, _tx: Value, _currency: Value) -> Value { Value::Null }
120    fn parse_ledger_entry(&self, _entry: Value, _currency: Value) -> Value { Value::Null }
121    fn parse_transfer(&self, _transfer: Value, _currency: Value) -> Value { Value::Null }
122    fn parse_currency(&self, _currency: Value) -> Value { Value::Null }
123    fn parse_bid_ask(&self, _bidask: Value, _price_key: Value, _amount_key: Value, _market: Value) -> Value { Value::Null }
124    fn parse_open_interest(&self, _interest: Value, _market: Value) -> Value { Value::Null }
125    fn parse_liquidation(&self, _liquidation: Value, _market: Value) -> Value { Value::Null }
126    fn parse_funding_rate_history(&self, _entry: Value, _market: Value) -> Value { Value::Null }
127    fn parse_margin_modification(&self, _data: Value, _market: Value) -> Value { Value::Null }
128    fn parse_account(&self, _account: Value) -> Value { Value::Null }
129    fn parse_my_trade(&self, _trade: Value, _market: Value) -> Value { Value::Null }
130    fn parse_transaction(&self, _transaction: Value, _currency: Value) -> Value { Value::Null }
131    fn parse_borrow_interest(&self, _info: Value, _market: Value) -> Value { Value::Null }
132    fn parse_adl_rank(&self, _info: Value, _market: Value) -> Value { Value::Null }
133    fn parse_income(&self, _info: Value, _market: Value) -> Value { Value::Null }
134    fn parse_greeks(&self, _greeks: Value, _market: Value) -> Value { Value::Null }
135    fn parse_margin_mode(&self, _margin_mode: Value, _market: Value) -> Value { Value::Null }
136    fn parse_conversion(&self, _conversion: Value, _from_currency: Value, _to_currency: Value) -> Value { Value::Null }
137    fn parse_borrow_rate(&self, _info: Value, _currency: Value) -> Value { Value::Null }
138    fn parse_leverage(&self, _leverage: Value, _market: Value) -> Value { Value::Null }
139    fn parse_market_leverage_tiers(&self, _info: Value, _market: Value) -> Value { Value::Null }
140    fn parse_deposit_withdraw_fee(&self, _fee: Value, _currency: Value) -> Value { Value::Null }
141    fn create_expired_option_market(&self, _symbol: Value) -> Value { Value::Null }
142    fn market(&self, _symbol: Value) -> Value { Value::Null }
143    // ── prediction-tier parsers (overridden by prediction venues) ────────
144    fn parse_prediction_trade(&self, _trade: Value, _market: Value) -> Value { Value::Null }
145    fn parse_prediction_order(&self, _order: Value, _market: Value) -> Value { Value::Null }
146    fn parse_prediction_position(&self, _position: Value, _market: Value) -> Value { Value::Null }
147    // ── signers / error handlers ─────────────────────────────────────────
148    /// `nonce()` — the request timestamp. The base default is `seconds()`, but
149    /// 47 venues override it (binance: `milliseconds() - timeDifference`), and
150    /// without a slot here the override is invisible to any caller that reaches
151    /// the base through a trait method — notably a pro Core, which finds
152    /// `ExchangeBase::nonce` at deref step 0 and never looks at the REST
153    /// parent's inherent one. Binance spot then signs its ws-api subscribe with
154    /// a seconds timestamp and the venue answers -1130.
155    fn nonce(&self) -> Value { Value::Null }
156    fn sign(&self, _path: Value, _api: Value, _method: Value, _params: Value, _headers: Value, _body: Value) -> Value { Value::Null }
157    fn handle_errors(&self, _code: Value, _reason: Value, _url: Value, _method: Value, _headers: Value, _body: Value, _response: Value, _request_headers: Value, _request_body: Value) -> Value { Value::Null }
158}
159
160// `Internals` no longer holds raw pointers, so `Send`/`Sync` are auto-derived
161// (its fields — `reqwest::Client`, `Arc<dyn Fn + Send + Sync>`,
162// `Arc<tokio::Mutex<_>>`, maps, `Vec<String>` — are all thread-safe). No manual
163// `unsafe impl` and no `PhantomPinned` are needed now that dispatch is static
164// (review #1: thread safety is compiler-proven, not asserted).
165
166// A cloned Exchange gets a fresh `Internals` — the http client and dispatch
167// state are per-instance and must not be shared.
168// Test-only callers (`clone_self`) only read `Value` fields off the copy.
169impl Clone for Internals {
170    fn clone(&self) -> Self { Internals::default() }
171}
172
173impl Default for Internals {
174    fn default() -> Self {
175        Self {
176            http_client:      None,
177            describe_cb:      None,
178            last_rest_ts:     0,
179            headers:          HashMap::new(),
180            throttle:         std::sync::Arc::new(tokio::sync::Mutex::new((0.0, 0))),
181            implicit_api:     HashMap::new(),
182            dispatch_stack:      Vec::new(),
183            dynamic_dispatch_miss: None,
184        }
185    }
186}
187
188// ── Exchange struct ─────────────────────────────────────────────────────────
189//
190// Every transpiler-visible field is `Value`. Both camelCase and snake_case
191// names appear because the TS source uses both interchangeably.
192
193#[derive(Clone)]
194pub struct Exchange {
195    // identity
196    pub id:          Value,
197    pub name:        Value,
198    pub countries:   Value,
199    pub version:     Value,
200    pub alias:       Value,
201    pub certified:   Value,
202    pub pro:         Value,
203    pub hostname:    Value,
204
205    // credentials
206    pub apiKey:        Value,
207    pub secret:        Value,
208    pub password:      Value,
209    pub uid:           Value,
210    pub walletAddress: Value,
211    pub privateKey:    Value,
212    pub twofa:         Value,
213    pub token:         Value,
214    pub login:         Value,
215    pub accountId:     Value,
216    pub requiredCredentials: Value,
217
218    // rate limiting / connection
219    pub timeout:                Value,
220    pub rateLimit:              Value,
221    pub enableRateLimit:        Value,
222    pub rateLimiterAlgorithm:   Value,
223    pub rollingWindowSize:      Value,
224    pub tokenBucket:            Value,
225    /// The raw constructor config, kept so `initialize_properties` can merge it
226    /// over `describe()` the way Go's `InitParent` does
227    /// (`deepExtend(describe, userConfig)`) instead of relying on per-field
228    /// precedence guards in each Core's generated `init()`.
229    pub userConfig:             Value,
230    pub verbose:                Value,
231    pub isSandboxModeEnabled:   Value,
232
233    // proxy
234    pub proxy:               Value,
235    pub proxyUrl:            Value,
236    pub proxy_url:           Value,
237    pub proxyUrlCallback:    Value,
238    pub proxy_url_callback:  Value,
239    pub httpProxy:           Value,
240    pub http_proxy:          Value,
241    pub httpProxyCallback:   Value,
242    pub http_proxy_callback: Value,
243    pub httpsProxy:          Value,
244    pub https_proxy:         Value,
245    pub httpsProxyCallback:  Value,
246    pub https_proxy_callback: Value,
247    pub socksProxy:          Value,
248    pub socks_proxy:         Value,
249    pub socksProxyCallback:  Value,
250    pub socks_proxy_callback: Value,
251    pub wsProxy:             Value,
252    pub ws_proxy:            Value,
253    pub wssProxy:            Value,
254    pub wss_proxy:           Value,
255    pub wsSocksProxy:        Value,
256    pub ws_socks_proxy:      Value,
257
258    // market data caches
259    pub markets:           Value,
260    pub markets_by_id:     Value,
261    pub currencies:        Value,
262    pub currencies_by_id:  Value,
263    pub commonCurrencies:  Value,
264    pub baseCurrencies:    Value,
265    pub quoteCurrencies:   Value,
266    pub symbols:           Value,
267    pub ids:               Value,
268    pub codes:             Value,
269    pub timeframes:        Value,
270    pub precision:         Value,
271    pub limits:            Value,
272    pub fees:              Value,
273    pub features:          Value,
274    pub has:               Value,
275    pub exceptions:        Value,
276    pub urls:              Value,
277    pub api:               Value,
278    pub options:           Value,
279    pub headers:           Value,
280    pub accounts:          Value,
281    pub accountsById:      Value,
282
283    // runtime state
284    pub orderbooks:        Value,
285    pub orders:            Value,
286    pub trades:            Value,
287    pub myTrades:          Value,
288    pub positions:         Value,
289    // WS state — mirrors `ts/src/base/Exchange.ts` `newUpdates: boolean = true`.
290    // Per-exchange WS code reads `self.newUpdates` to decide whether to call
291    // `cache.getLimit(...)` (return only what's new since the last call) or
292    // emit the whole rolling buffer.
293    pub newUpdates:        Value,
294    pub tickers:           Value,
295    pub bidsasks:          Value,
296    pub ohlcvs:            Value,
297    pub clients:           Value,
298    pub balance:           Value,
299    pub liquidations:      Value,
300    pub myLiquidations:    Value,
301    pub fundingRates:      Value,
302    pub triggerOrders:     Value,
303    pub transactions:      Value,
304    pub reloadingMarkets:  Value,
305    pub marketsLoading:    Value,
306
307    // last-* tracking
308    pub last_request_url:        Value,
309    pub last_request_headers:    Value,
310    pub last_request_body:       Value,
311    pub last_http_response:      Value,
312    pub last_response_headers:   Value,
313    /// Canned HTTP response for static *response* tests — when set,
314    /// `fetch_typed` returns it without hitting the network so the
315    /// exchange's parser runs against fixture data. Mirrors Go's
316    /// `MockResponse` field. Reused for all requests in a fixture; the test
317    /// dispatcher replaces or clears it before the next REST dispatch.
318    pub mock_response:           Value,
319    /// Response-test mock keyed by url fragment, for methods that call several
320    /// endpoints: one shared body cannot cover two endpoints of different
321    /// declared shapes. Consulted before `mock_response`.
322    pub mock_response_by_url:    Value,
323    pub last_json_response:      Value,
324    pub lastRestRequestTimestamp: Value,
325    /// Rolling cache of recent fetch results, capped at
326    /// `fetchHistoryCacheSize`. Mirrors `Exchange.ts` `fetchHistoryCache`
327    /// / `fetchHistoryCacheSize` (hand-written, above the transpile marker).
328    pub fetchHistoryCache:      Value,
329    pub fetchHistoryCacheSize:  Value,
330
331    // misc
332    pub paddingMode:               Value,
333    pub precisionMode:             Value,
334    pub substituteCommonCurrencyCodes: Value,
335    pub reduceFees:                Value,
336    pub minFundingAddressLength:   Value,
337    pub networkAliases:            Value,
338    pub MAX_VALUE:                 Value,
339    pub returnResponseHeaders:     Value,
340    pub httpExceptions:            Value,
341    pub status:                    Value,
342
343    // user-agent / fetch behavior
344    pub userAgent:                 Value,
345    pub user_agent:                Value,
346    pub userAgents:                Value,
347
348    // describe() output (legacy)
349    pub describe_data:             Value,
350    pub derived_describe:          Option<DescribeCallback>,
351
352    // private runtime state (typed)
353    pub internals: Internals,
354}
355
356impl Default for Exchange {
357    fn default() -> Self { Self::new(None) }
358}
359
360// ── base-class describe() defaults (Exchange.ts) ────────────────────────────
361// Mirrors the constant sub-objects returned by the base `describe()` so a
362// plain `Exchange` carries the same shape as CCXT (verified by the
363// transpiled `test.afterConstructor` base test).
364
365fn vmap(pairs: &[(&str, Value)]) -> Value {
366    let mut m = HashMap::new();
367    for (k, v) in pairs { m.insert((*k).to_string(), v.clone()); }
368    Value::Map(m)
369}
370
371fn min_max() -> Value { vmap(&[("min", Value::Null), ("max", Value::Null)]) }
372
373fn base_limits() -> Value {
374    vmap(&[
375        ("leverage", min_max()),
376        ("amount",   min_max()),
377        ("price",    min_max()),
378        ("cost",     min_max()),
379    ])
380}
381
382fn base_fees() -> Value {
383    vmap(&[
384        ("trading", vmap(&[
385            ("tierBased",  Value::Null),
386            ("percentage", Value::Null),
387            ("taker",      Value::Null),
388            ("maker",      Value::Null),
389        ])),
390        ("funding", vmap(&[
391            ("tierBased",  Value::Null),
392            ("percentage", Value::Null),
393            ("withdraw",   Value::Map(HashMap::new())),
394            ("deposit",    Value::Map(HashMap::new())),
395        ])),
396    ])
397}
398
399fn base_urls() -> Value {
400    vmap(&[
401        ("logo", Value::Null), ("api", Value::Null), ("test", Value::Null),
402        ("www", Value::Null), ("doc", Value::Null), ("api_management", Value::Null),
403        ("fees", Value::Null), ("referral", Value::Null),
404    ])
405}
406
407fn base_status() -> Value {
408    vmap(&[
409        ("status",  Value::Str("ok".into())),
410        ("updated", Value::Null),
411        ("eta",     Value::Null),
412        ("url",     Value::Null),
413        ("info",    Value::Null),
414    ])
415}
416
417/// `deepExtend(a, b)` — recursive merge; `b` wins on scalar conflicts,
418/// nested maps merge key-by-key.
419fn deep_merge(a: &Value, b: &Value) -> Value {
420    match (a, b) {
421        (Value::Dict(am), Value::Dict(bm)) => {
422            let mut out = (**am).clone();
423            for (k, bv) in bm.iter() {
424                let merged = match out.get(k) {
425                    Some(av) => deep_merge(av, bv),
426                    None     => bv.clone(),
427                };
428                out.insert(k.clone(), merged);
429            }
430            Value::Map(out)
431        }
432        _ => b.clone(),
433    }
434}
435
436fn base_http_exceptions() -> Value {
437    let mut m = HashMap::new();
438    for (code, class) in [
439        ("422", "ExchangeError"),         ("418", "DDoSProtection"),
440        ("429", "RateLimitExceeded"),     ("404", "ExchangeNotAvailable"),
441        ("409", "ExchangeNotAvailable"),  ("410", "ExchangeNotAvailable"),
442        ("451", "ExchangeNotAvailable"),  ("500", "ExchangeNotAvailable"),
443        ("501", "ExchangeNotAvailable"),  ("502", "ExchangeNotAvailable"),
444        ("520", "ExchangeNotAvailable"),  ("521", "ExchangeNotAvailable"),
445        ("522", "ExchangeNotAvailable"),  ("525", "ExchangeNotAvailable"),
446        ("526", "ExchangeNotAvailable"),  ("400", "ExchangeNotAvailable"),
447        ("403", "ExchangeNotAvailable"),  ("405", "ExchangeNotAvailable"),
448        ("503", "ExchangeNotAvailable"),  ("530", "ExchangeNotAvailable"),
449        ("408", "RequestTimeout"),        ("504", "RequestTimeout"),
450        ("401", "AuthenticationError"),   ("407", "AuthenticationError"),
451        ("511", "AuthenticationError"),
452    ] {
453        m.insert(code.to_string(), Value::Str(class.to_string().into()));
454    }
455    Value::Map(m)
456}
457
458impl Exchange {
459    pub fn new(config: Option<Value>) -> Self {
460        let mut ex = Exchange {
461            // Base-class id (Exchange.ts describe()). A derived exchange's
462            // describe() overrides this with its own id.
463            id:        Value::Str("Exchange".into()),
464            name:      Value::Null,
465            countries: Value::Null,
466            version:   Value::Null,
467            alias:     Value::Bool(false),
468            certified: Value::Bool(false),
469            pro:       Value::Bool(false),
470            hostname:  Value::Null,
471
472            apiKey:        Value::Null,
473            secret:        Value::Null,
474            password:      Value::Null,
475            uid:           Value::Null,
476            walletAddress: Value::Null,
477            privateKey:    Value::Null,
478            twofa:         Value::Null,
479            token:         Value::Null,
480            login:         Value::Null,
481            accountId:     Value::Null,
482            // Base-class default (Exchange.ts). Kept when an exchange's
483            // describe() doesn't override it — so `checkRequiredCredentials`
484            // still works even though `super.describe()` is stubbed.
485            requiredCredentials: {
486                let mut m = HashMap::new();
487                m.insert("apiKey".to_string(),        Value::Bool(true));
488                m.insert("secret".to_string(),        Value::Bool(true));
489                m.insert("uid".to_string(),           Value::Bool(false));
490                m.insert("accountId".to_string(),     Value::Bool(false));
491                m.insert("login".to_string(),         Value::Bool(false));
492                m.insert("password".to_string(),      Value::Bool(false));
493                m.insert("twofa".to_string(),         Value::Bool(false));
494                m.insert("privateKey".to_string(),    Value::Bool(false));
495                m.insert("walletAddress".to_string(), Value::Bool(false));
496                m.insert("token".to_string(),         Value::Bool(false));
497                Value::Map(m)
498            },
499
500            timeout:              Value::Int(10_000),
501            rateLimit:            Value::Int(2_000),
502            enableRateLimit:      Value::Bool(true),
503            rateLimiterAlgorithm: Value::Str("leakyBucket".into()),
504            rollingWindowSize:    Value::Int(60_000),
505            tokenBucket:          Value::Map(HashMap::new()),
506            userConfig:           Value::Null,
507            verbose:              Value::Bool(false),
508            isSandboxModeEnabled: Value::Bool(false),
509
510            proxy:               Value::Null,
511            proxyUrl:            Value::Null,
512            proxy_url:           Value::Null,
513            proxyUrlCallback:    Value::Null,
514            proxy_url_callback:  Value::Null,
515            httpProxy:           Value::Null,
516            http_proxy:          Value::Null,
517            httpProxyCallback:   Value::Null,
518            http_proxy_callback: Value::Null,
519            httpsProxy:          Value::Null,
520            https_proxy:         Value::Null,
521            httpsProxyCallback:  Value::Null,
522            https_proxy_callback: Value::Null,
523            socksProxy:          Value::Null,
524            socks_proxy:         Value::Null,
525            socksProxyCallback:  Value::Null,
526            socks_proxy_callback: Value::Null,
527            wsProxy:             Value::Null,
528            ws_proxy:            Value::Null,
529            wssProxy:            Value::Null,
530            wss_proxy:           Value::Null,
531            wsSocksProxy:        Value::Null,
532            ws_socks_proxy:      Value::Null,
533
534            markets:           Value::Null,
535            markets_by_id:     Value::Null,
536            currencies:        Value::Map(HashMap::new()),
537            currencies_by_id:  Value::Null,
538            commonCurrencies:  {
539                let mut m = HashMap::new();
540                m.insert("XBT".to_string(),   Value::Str("BTC".into()));
541                m.insert("BCHSV".to_string(), Value::Str("BSV".into()));
542                Value::Map(m)
543            },
544            baseCurrencies:    Value::Null,
545            quoteCurrencies:   Value::Null,
546            symbols:           Value::Null,
547            ids:               Value::Null,
548            codes:             Value::Null,
549            timeframes:        Value::Null,
550            precision:         Value::Null,
551            limits:            base_limits(),
552            fees:              base_fees(),
553            features:          Value::Null,
554            has:               Value::Map(HashMap::new()),
555            exceptions:        Value::Null,
556            urls:              base_urls(),
557            api:               Value::Null,
558            // Base-class default `options` (Exchange.ts describe()). Kept
559            // when an exchange's describe() omits it — `super.describe()`
560            // is stubbed, so it wouldn't otherwise flow through.
561            options: {
562                let mk = |p: &str, s: &str, d: &str| {
563                    let mut e = HashMap::new();
564                    e.insert("primary".to_string(),   Value::Str(p.to_string().into()));
565                    e.insert("secondary".to_string(), Value::Str(s.to_string().into()));
566                    e.insert("default".to_string(),   Value::Str(d.to_string().into()));
567                    Value::Map(e)
568                };
569                let mut repl = HashMap::new();
570                repl.insert("ETH".to_string(), mk("ETH", "ERC20", "secondary"));
571                repl.insert("CRO".to_string(), mk("CRONOS", "CRC20", "secondary"));
572                repl.insert("TRX".to_string(), mk("TRX", "TRC20", "secondary"));
573                repl.insert("BTC".to_string(), mk("BTC", "BRC20", "primary"));
574                let mut o = HashMap::new();
575                o.insert("defaultNetworkCodeReplacements".to_string(), Value::Map(repl));
576                Value::Map(o)
577            },
578            headers:           Value::Map(HashMap::new()),
579            accounts:          Value::Null,
580            accountsById:      Value::Null,
581
582            orderbooks:    Value::Map(HashMap::new()),
583            orders:        Value::Null,
584            trades:        Value::Map(HashMap::new()),
585            myTrades:      Value::Null,
586            positions:     Value::Null,
587            newUpdates:    Value::Bool(true),
588            tickers:       Value::Map(HashMap::new()),
589            bidsasks:      Value::Map(HashMap::new()),
590            ohlcvs:        Value::Map(HashMap::new()),
591            clients:       Value::Map(HashMap::new()),
592            balance:       Value::Map(HashMap::new()),
593            liquidations:  Value::Null,
594            myLiquidations: Value::Null,
595            fundingRates:  Value::Null,
596            triggerOrders: Value::Null,
597            transactions:  Value::Map(HashMap::new()),
598            reloadingMarkets: Value::Null,
599            marketsLoading:   Value::Null,
600
601            last_request_url:           Value::Null,
602            last_request_headers:       Value::Null,
603            last_request_body:          Value::Null,
604            last_http_response:         Value::Null,
605            last_response_headers:      Value::Null,
606            mock_response:              Value::Null,
607            mock_response_by_url:       Value::Null,
608            last_json_response:         Value::Null,
609            lastRestRequestTimestamp:   Value::Int(0),
610            fetchHistoryCache:          Value::List(vec![]),
611            fetchHistoryCacheSize:      Value::Int(0),
612
613            paddingMode:                       Value::Null,
614            precisionMode:                     Value::Null,
615            substituteCommonCurrencyCodes:     Value::Bool(true),
616            reduceFees:                        Value::Bool(true),
617            minFundingAddressLength:           Value::Int(1),
618                        networkAliases:                    Value::Dict(std::sync::Arc::new([("ETH".to_string(), Value::Str("ERC20".into())), ("TRX".to_string(), Value::Str("TRC20".into())), ("BSC".to_string(), Value::Str("BEP20".into())), ("BSC20".to_string(), Value::Str("BEP20".into())), ("CRONOS".to_string(), Value::Str("CRC20".into())), ("ARB".to_string(), Value::Str("ARBITRUM".into())), ("ARBONE".to_string(), Value::Str("ARBITRUM".into())), ("ARBNOVA".to_string(), Value::Str("ARBITRUM_NOVA".into()))].into_iter().collect())),
619            MAX_VALUE:                         Value::Float(f64::MAX),
620            returnResponseHeaders:             Value::Bool(false),
621            httpExceptions:                    base_http_exceptions(),
622            status:                            base_status(),
623
624            userAgent:   Value::Null,
625            user_agent:  Value::Null,
626            userAgents:  {
627                let mut m = HashMap::new();
628                m.insert("chrome".to_string(), Value::Str("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36".into()));
629                m.insert("chrome39".to_string(), Value::Str("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36".into()));
630                m.insert("chrome100".to_string(), Value::Str("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36".into()));
631                Value::Map(m)
632            },
633
634            describe_data:     Value::Null,
635            derived_describe:  None,
636
637            internals: Internals::default(),
638        };
639        if let Some(cfg) = config {
640            ex.userConfig = cfg.clone();
641            ex.apply_config(&cfg);
642        }
643        // NOTE: `afterConstruct()` is deliberately NOT run here. In TS the
644        // constructor applies describe() and only then calls afterConstruct,
645        // so the bits it derives (networksById, the features table, the
646        // tokenBucket, the sandbox swap) see the venue's own values. Running
647        // it at this point — before the derived Core's describe() has been
648        // applied — is what made every venue throttle at the base 2000ms and
649        // forced a string of compensations in the generated `init()`. Each
650        // Core's `init()` now calls it last; a bare `Exchange` with no derived
651        // Core (base unit tests, `BaseCore`) calls `after_construct` itself.
652        ex
653    }
654
655    /// Apply a merged `describe()` + constructor-config map onto the typed
656    /// fields. The Rust counterpart of Go's `initializeProperties`
657    /// (`go/v4/exchange_options.go`) and of the TS constructor's
658    /// `deepExtend(this, describe(), userConfig)` — which Rust cannot do
659    /// directly because `Exchange` is a struct, not a dynamic object.
660    ///
661    /// Each Core's generated `init()` used to inline ~84 lines of this, which
662    /// is why every field carried its own precedence guard: config was applied
663    /// in `new()` BEFORE `describe()` ran, so `describe()` had to be stopped
664    /// from clobbering it. Here the config is merged over `describe()` first
665    /// (Go's `deepExtend(describe, userConfig)`), so last-write-wins is the
666    /// precedence rule and no guards are needed.
667    ///
668    /// Absent keys leave the base default in place — the equivalent of Go's
669    /// `SafeString(props, key, default)`.
670    pub fn initialize_properties(&mut self, described: Value) {
671        let props = if matches!(self.userConfig, Value::Null) {
672            described
673        } else {
674            crate::runtime::deep_merge_dict(&described, &self.userConfig.clone())
675        };
676        let get = |k: &str| crate::get_value(&props, &Value::Str(k.to_string().into()));
677        let assign = |field: &mut Value, v: Value| {
678            if !matches!(v, Value::Null) {
679                *field = v;
680            }
681        };
682        assign(&mut self.api, get("api"));
683        assign(&mut self.urls, get("urls"));
684        assign(&mut self.has, get("has"));
685        assign(&mut self.hostname, get("hostname"));
686        assign(&mut self.version, get("version"));
687        assign(&mut self.id, get("id"));
688        assign(&mut self.name, get("name"));
689        assign(&mut self.exceptions, get("exceptions"));
690        assign(&mut self.requiredCredentials, get("requiredCredentials"));
691        assign(&mut self.precisionMode, get("precisionMode"));
692        assign(&mut self.timeframes, get("timeframes"));
693        assign(&mut self.fees, get("fees"));
694        assign(&mut self.features, get("features"));
695        let rate_limit = get("rateLimit");
696        if matches!(rate_limit, Value::Int(_) | Value::Float(_)) {
697            self.rateLimit = rate_limit;
698        }
699        // `options` and `commonCurrencies` MERGE rather than replace: the base
700        // Exchange seeds defaults into both, and describe() only supplies the
701        // venue's additions.
702        if let Value::Dict(extra) = get("options") {
703            let mut merged = match &self.options {
704                Value::Dict(m) => (**m).clone(),
705                _ => HashMap::new(),
706            };
707            let extra = Arc::try_unwrap(extra).unwrap_or_else(|a| (*a).clone());
708            for (k, v) in extra { merged.insert(k, v); }
709            self.options = Value::Map(merged);
710        }
711        if let Value::Dict(extra) = get("commonCurrencies") {
712            let mut merged = match &self.commonCurrencies {
713                Value::Dict(m) => (**m).clone(),
714                _ => HashMap::new(),
715            };
716            let extra = Arc::try_unwrap(extra).unwrap_or_else(|a| (*a).clone());
717            for (k, v) in extra { merged.insert(k, v); }
718            self.commonCurrencies = Value::Map(merged);
719        }
720        // A venue whose describe() ships its own markets (the hard-coded ones)
721        // resolves load_markets without a network call. Guarded on markets not
722        // already being loaded, so config-injected markets win.
723        let described_markets = get("markets");
724        if matches!(&described_markets, Value::Dict(m) if !m.is_empty())
725            && matches!(self.markets, Value::Null)
726        {
727            self.set_markets_inline(described_markets);
728        }
729        self.build_implicit_api();
730    }
731
732    fn apply_config(&mut self, cfg: &Value) {
733        use crate::value::safe_string;
734        if let Some(v) = safe_string(cfg, "id",       None) { self.id       = Value::Str(v.into()); }
735        if let Some(v) = safe_string(cfg, "name",     None) { self.name     = Value::Str(v.into()); }
736        if let Some(v) = safe_string(cfg, "hostname", None) { self.hostname = Value::Str(v.into()); }
737        let rate_limit = crate::get_value(cfg, &Value::Str("rateLimit".into()));
738        if matches!(rate_limit, Value::Int(_) | Value::Float(_)) { self.rateLimit = rate_limit; }
739        let timeout = crate::get_value(cfg, &Value::Str("timeout".into()));
740        if matches!(timeout, Value::Int(_) | Value::Float(_)) { self.timeout = timeout; }
741        let fetch_history_cache_size = crate::get_value(cfg, &Value::Str("fetchHistoryCacheSize".into()));
742        if matches!(fetch_history_cache_size, Value::Int(_) | Value::Float(_)) { self.fetchHistoryCacheSize = fetch_history_cache_size; }
743        let urls = crate::get_value(cfg, &Value::Str("urls".into()));
744        if let Value::Dict(_) = urls { self.urls = deep_merge(&self.urls, &urls); }
745        if let Some(v) = safe_string(cfg, "apiKey",        None) { self.apiKey        = Value::Str(v.into()); }
746        if let Some(v) = safe_string(cfg, "secret",        None) { self.secret        = Value::Str(v.into()); }
747        if let Some(v) = safe_string(cfg, "password",      None) { self.password      = Value::Str(v.into()); }
748        if let Some(v) = safe_string(cfg, "uid",           None) { self.uid           = Value::Str(v.into()); }
749        if let Some(v) = safe_string(cfg, "walletAddress", None) { self.walletAddress = Value::Str(v.into()); }
750        if let Some(v) = safe_string(cfg, "privateKey",    None) { self.privateKey    = Value::Str(v.into()); }
751        if let Some(v) = safe_string(cfg, "token",         None) { self.token         = Value::Str(v.into()); }
752        if let Some(v) = safe_string(cfg, "login",         None) { self.login         = Value::Str(v.into()); }
753        if let Some(v) = safe_string(cfg, "accountId",     None) { self.accountId     = Value::Str(v.into()); }
754        if let Some(v) = safe_string(cfg, "httpProxy",     None) { self.httpProxy     = Value::Str(v.into()); }
755        if let Some(v) = safe_string(cfg, "httpsProxy",    None) { self.httpsProxy    = Value::Str(v.into()); }
756        if let Some(v) = safe_string(cfg, "socksProxy",    None) { self.socksProxy    = Value::Str(v.into()); }
757        // WS proxies: the `watch*` transport dials these through an HTTP
758        // CONNECT tunnel. Without them here a config-supplied `wsProxy` set
759        // the field on nothing and the socket quietly went direct.
760        if let Some(v) = safe_string(cfg, "wsProxy",       None) { self.wsProxy       = Value::Str(v.into()); }
761        if let Some(v) = safe_string(cfg, "wssProxy",      None) { self.wssProxy      = Value::Str(v.into()); }
762        if let Some(b) = crate::value::safe_bool(cfg, "verbose",         None) { self.verbose         = Value::Bool(b); }
763        if let Some(b) = crate::value::safe_bool(cfg, "enableRateLimit", None) { self.enableRateLimit = Value::Bool(b); }
764        // Pre-populated state (mirrors CCXT TS Exchange constructor):
765        // markets/currencies/options arrive ready to use from offline
766        // tests, the CLI, or library users seeding state. `setMarkets`
767        // also derives markets_by_id and symbols.
768        let markets    = crate::get_value(cfg, &Value::Str("markets".into()));
769        let currencies = crate::get_value(cfg, &Value::Str("currencies".into()));
770        if !matches!(markets,    Value::Null) { self.set_markets_inline(markets); }
771        if !matches!(currencies, Value::Null) { self.currencies = currencies; }
772        let opts = crate::get_value(cfg, &Value::Str("options".into()));
773        if let Value::Dict(extra) = opts {
774            let mut merged = match &self.options {
775                Value::Dict(m) => (**m).clone(),
776                _ => HashMap::new(),
777            };
778            let extra = Arc::try_unwrap(extra).unwrap_or_else(|a| (*a).clone());
779            for (k, v) in extra { merged.insert(k, v); }
780            self.options = Value::Map(merged);
781        }
782        let accounts = crate::get_value(cfg, &Value::Str("accounts".into()));
783        if !matches!(accounts, Value::Null) { self.accounts = accounts; }
784    }
785
786    /// `markets`-from-config → derives `markets_by_id` + `symbols`.
787    /// Accepts either Map<symbol, market> or Array<market>.
788    fn set_markets_inline(&mut self, markets: Value) {
789        let arr: Vec<Value> = match &markets {
790            Value::Dict(m)   => m.values().cloned().collect(),
791            Value::Arr(a) => (**a).clone(),
792            _ => return,
793        };
794        let mut by_symbol = HashMap::new();
795        // `markets_by_id` maps an exchange market id → the *list* of
796        // markets sharing that id (e.g. binance spot + swap both have
797        // id `BTCUSDT`); `safeMarket` disambiguates by market type.
798        let mut by_id: HashMap<String, Vec<Value>> = HashMap::new();
799        let mut symbols   = Vec::new();
800        for m in &arr {
801            if let Some(s) = crate::value::safe_string(m, "symbol", None) {
802                by_symbol.insert(s.clone(), m.clone());
803                symbols.push(Value::Str(s.into()));
804            }
805            if let Some(i) = crate::value::safe_string(m, "id", None) {
806                by_id.entry(i).or_default().push(m.clone());
807            }
808        }
809        self.markets       = if by_symbol.is_empty() { markets } else { Value::Map(by_symbol) };
810        self.markets_by_id = Value::Map(
811            by_id.into_iter().map(|(k, v)| (k, Value::Array(v))).collect()
812        );
813        self.symbols       = Value::Array(symbols);
814    }
815
816    // ── http client ─────────────────────────────────────────────────────────
817
818    fn http_client(&mut self) -> &reqwest::Client {
819        if self.internals.http_client.is_none() {
820            let mut b = reqwest::Client::builder()
821                .timeout(std::time::Duration::from_millis(self.timeout_ms()))
822                // Transparent gzip: many exchanges return large JSON payloads
823                // (binance spot exchangeInfo is ~17 MB raw vs ~0.3 MB gzipped).
824                // Other CCXT langs request gzip by default; without this rust
825                // downloads the full uncompressed body, dominating load time.
826                .gzip(true);
827            if let Some(ua) = self.user_agent_str() { b = b.user_agent(ua); }
828            // Apply scheme-specific proxies. Order matters for reqwest's
829            // proxy matcher: SOCKS catches everything when set, HTTP/HTTPS
830            // only match their own scheme. The legacy `proxy` (and its
831            // snake_case alias) plus tests' `httpsProxy` use the catch-all
832            // form via Proxy::all(...). The `socks` feature on `reqwest`
833            // is what makes `socks5://...` URIs actually route — without
834            // it `Proxy::all` would build but the connection silently
835            // never goes through SOCKS.
836            let mut proxies: Vec<reqwest::Proxy> = Vec::new();
837            for field in [&self.socksProxy, &self.socks_proxy] {
838                if let Value::Str(s) = field {
839                    if !s.is_empty() {
840                        if let Ok(p) = reqwest::Proxy::all(s.as_ref()) { proxies.push(p); }
841                    }
842                }
843            }
844            for field in [&self.httpsProxy, &self.https_proxy] {
845                if let Value::Str(s) = field {
846                    if !s.is_empty() {
847                        if let Ok(p) = reqwest::Proxy::https(s.as_ref()) { proxies.push(p); }
848                    }
849                }
850            }
851            for field in [&self.httpProxy, &self.http_proxy] {
852                if let Value::Str(s) = field {
853                    if !s.is_empty() {
854                        if let Ok(p) = reqwest::Proxy::http(s.as_ref()) { proxies.push(p); }
855                    }
856                }
857            }
858            // Legacy single `proxy` setter (catch-all). Only honoured if
859            // none of the scheme-specific fields fired.
860            if proxies.is_empty() {
861                if let Value::Str(s) = &self.proxy {
862                    if !s.is_empty() {
863                        if let Ok(p) = reqwest::Proxy::all(s.as_ref()) { proxies.push(p); }
864                    }
865                }
866            }
867            for p in proxies { b = b.proxy(p); }
868            self.internals.http_client = Some(b.build().expect("reqwest client"));
869        }
870        self.internals.http_client.as_ref().unwrap()
871    }
872
873    fn timeout_ms(&self) -> u64 {
874        match &self.timeout {
875            Value::Int(n)   => *n as u64,
876            Value::Float(f) => *f as u64,
877            _ => 10_000,
878        }
879    }
880
881    fn user_agent_str(&self) -> Option<&str> {
882        match &self.userAgent { Value::Str(s) => Some(s.as_ref()), _ => match &self.user_agent {
883            Value::Str(s) => Some(s.as_ref()), _ => None
884        }}
885    }
886
887
888    fn is_verbose(&self) -> bool {
889        matches!(self.verbose, Value::Bool(true))
890    }
891
892
893    // ── encoding / URL helpers ──────────────────────────────────────────────
894
895    pub fn urlencode_kv(&self, params: &Value) -> String {
896        let m = match params { Value::Dict(m) => m, _ => return String::new() };
897        m.iter().map(|(k, v)| format!(
898            "{}={}",
899            url_pct(k),
900            url_pct(&crate::runtime::stringify_param(v)),
901        )).collect::<Vec<_>>().join("&")
902    }
903
904    pub fn implode_params(&self, path: Value, params: Value) -> Value {
905        let path_str = match &path { Value::Str(s) => s.clone(), _ => return path };
906        let m = match &params { Value::Dict(m) => m, _ => return Value::Str(path_str) };
907        let mut out = path_str;
908        for (k, v) in m.iter() {
909            let needle = format!("{{{k}}}");
910            if out.contains(&needle) {
911                out = out.replace(&needle, &crate::runtime::stringify_param(v)).into();
912            }
913        }
914        Value::Str(out)
915    }
916
917    pub fn json_str(&self, v: &Value) -> String {
918        serde_json::to_string(&v.to_json()).unwrap_or_default()
919    }
920
921    // ── crypto ──────────────────────────────────────────────────────────────
922
923    pub fn hmac(&self, data: Value, secret: Value, hash: Value, optional_args: &[Value]) -> Value {
924        // `data`/`secret` may be a string OR the byte-array produced by
925        // `encode()` (CCXT's `hmac` takes the encoded request/secret).
926        let dbytes = value_to_bytes(&data);
927        let sbytes = value_to_bytes(&secret);
928        let h = match &hash { Value::Str(s) => s.clone(), _ => "sha256".to_string().into() };
929        let digest = match optional_args.get(0) {
930            Some(Value::Str(d)) => d.clone(),
931            _ => "hex".to_string().into(),
932        };
933        match self.hmac_typed(&dbytes, &sbytes, &h, &digest) {
934            Ok(v) => Value::Str(v.into()),
935            Err(_) => Value::Null,
936        }
937    }
938
939    pub fn hmac_typed(&self, data: &[u8], secret: &[u8], hash: &str, digest: &str) -> Result<String> {
940        let dbytes = data;
941        let sbytes = secret;
942        let raw: Vec<u8> = match hash.to_ascii_lowercase().as_str() {
943            "sha256" => { let mut m = HmacSha256::new_from_slice(sbytes).unwrap(); m.update(dbytes); m.finalize().into_bytes().to_vec() }
944            "sha512" => { let mut m = HmacSha512::new_from_slice(sbytes).unwrap(); m.update(dbytes); m.finalize().into_bytes().to_vec() }
945            "sha1"   => { let mut m = HmacSha1::new_from_slice(sbytes).unwrap();   m.update(dbytes); m.finalize().into_bytes().to_vec() }
946            "md5"    => { let mut m = HmacMd5::new_from_slice(sbytes).unwrap();    m.update(dbytes); m.finalize().into_bytes().to_vec() }
947            other    => return Err(ExchangeError::new("BadRequest", format!("unknown hmac: {other}"))),
948        };
949        Ok(match digest {
950            "base64" => B64.encode(&raw),
951            _        => hex::encode(&raw),
952        })
953    }
954
955    pub fn hash(&self, data: Value, algo: Value, optional_args: &[Value]) -> Value {
956        // `data` may be a string OR the byte-array produced by `encode()`.
957        let dbytes = value_to_bytes(&data);
958        let a = match &algo { Value::Str(s) => s.clone(), _ => "sha256".to_string().into() };
959        let digest = match optional_args.get(0) {
960            Some(Value::Str(d)) => d.clone(),
961            _ => "hex".to_string().into(),
962        };
963        let raw = hash_raw(&dbytes, &a);
964        match digest.as_ref() {
965            // `binary` → a byte-array Value (consumed by another crypto step).
966            "binary" => Value::Array(raw.iter().map(|b| Value::Int(*b as i64)).collect()),
967            "base64" => Value::Str(B64.encode(&raw).into()),
968            _        => Value::Str(hex::encode(&raw).into()),
969        }
970    }
971
972    pub fn hash_typed(&self, data: &[u8], algo: &str, digest: &str) -> String {
973        let raw = hash_raw(data, algo);
974        match digest {
975            "base64" => B64.encode(&raw),
976            _        => hex::encode(&raw),
977        }
978    }
979
980    pub fn binary_to_base64(&self, data: Value, _optional_args: &[Value]) -> Value {
981        let bytes = value_to_bytes(&data);
982        Value::Str(B64.encode(&bytes).into())
983    }
984    pub fn base64_to_binary(&self, s: Value, _optional_args: &[Value]) -> Value {
985        let str_val = match &s { Value::Str(s) => s.clone(), _ => return Value::Null };
986        match B64.decode(&*str_val) {
987            Ok(b) => Value::Array(b.into_iter().map(|n| Value::Int(n as i64)).collect()),
988            Err(_) => Value::Null,
989        }
990    }
991    pub fn binary_to_base16(&self, data: Value, _optional_args: &[Value]) -> Value {
992        let bytes = value_to_bytes(&data);
993        Value::Str(hex::encode(&bytes).into())
994    }
995    pub fn base16_to_binary(&self, s: Value, _optional_args: &[Value]) -> Value {
996        let str_val = match &s { Value::Str(s) => s.clone(), _ => return Value::Null };
997        match hex::decode(&*str_val) {
998            Ok(b) => Value::Array(b.into_iter().map(|n| Value::Int(n as i64)).collect()),
999            Err(_) => Value::Null,
1000        }
1001    }
1002
1003    // ── time ────────────────────────────────────────────────────────────────
1004
1005    pub fn milliseconds(&self) -> Value {
1006        let n = std::time::SystemTime::now()
1007            .duration_since(std::time::UNIX_EPOCH)
1008            .map(|d| d.as_millis() as i64).unwrap_or(0);
1009        Value::Int(n)
1010    }
1011    pub fn seconds(&self) -> Value {
1012        match self.milliseconds() { Value::Int(n) => Value::Int(n / 1000), v => v }
1013    }
1014    pub fn microseconds(&self) -> Value {
1015        match self.milliseconds() { Value::Int(n) => Value::Int(n * 1000), v => v }
1016    }
1017
1018    pub fn iso8601(&self, ts: Value) -> Value {
1019        let n = match ts {
1020            Value::Int(n)   => n,
1021            Value::Float(f) => f as i64,
1022            Value::Str(ref s) => match s.parse::<i64>() { Ok(v) => v, Err(_) => return Value::Null },
1023            _ => return Value::Null,
1024        };
1025        if n < 0 {
1026            return Value::Null;
1027        }
1028        chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n)
1029            .map(|t| Value::Str(t.to_rfc3339_opts(chrono::SecondsFormat::Millis, true).into()))
1030            .unwrap_or(Value::Null)
1031    }
1032
1033    pub fn parse8601(&self, s: Value) -> Value {
1034        let str_val = match s { Value::Str(s) => s, _ => return Value::Null };
1035        if str_val.is_empty() {
1036            return Value::Null;
1037        }
1038        // rfc3339 (`T…Z` / `+00:00` offset forms).
1039        if let Ok(t) = chrono::DateTime::parse_from_rfc3339(&str_val) {
1040            return Value::Int(t.timestamp_millis());
1041        }
1042        // Numeric timezone offset WITHOUT a colon (`+0000`) — not valid
1043        // rfc3339 but common (e.g. bitso `2024-03-13T10:59:59+0000`). JS
1044        // `Date.parse` accepts it; chrono needs an explicit `%z` format.
1045        for fmt in [
1046            "%Y-%m-%dT%H:%M:%S%.f%z", "%Y-%m-%dT%H:%M:%S%z",
1047            "%Y-%m-%d %H:%M:%S%.f%z", "%Y-%m-%d %H:%M:%S%z",
1048        ] {
1049            if let Ok(t) = chrono::DateTime::parse_from_str(&str_val, fmt) {
1050                return Value::Int(t.timestamp_millis());
1051            }
1052        }
1053        // Lenient fallbacks — naive forms are interpreted as UTC.
1054        for fmt in [
1055            "%Y-%m-%d %H:%M:%S%.f", "%Y-%m-%d %H:%M:%S",
1056            "%Y-%m-%dT%H:%M:%S%.f", "%Y-%m-%dT%H:%M:%S",
1057            "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M",
1058        ] {
1059            if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(&str_val, fmt) {
1060                return Value::Int(ndt.and_utc().timestamp_millis());
1061            }
1062        }
1063        if let Ok(d) = chrono::NaiveDate::parse_from_str(&str_val, "%Y-%m-%d") {
1064            if let Some(ndt) = d.and_hms_opt(0, 0, 0) {
1065                return Value::Int(ndt.and_utc().timestamp_millis());
1066            }
1067        }
1068        Value::Null
1069    }
1070
1071    // safe_string/safe_number/safe_integer/safe_bool live on the transpiled
1072    // side (`exchange_generated.rs`) when the `transpiled-base` feature is
1073    // enabled. The free-functions in `crate::value` are the typed
1074    // equivalents — used internally by hand-written code below.
1075
1076
1077}
1078
1079// ── small helper used by url-encoding above ─────────────────────────────────
1080
1081// ── derived dispatch re-entry guard ─────────────────────────────────────────
1082//
1083// Virtual dispatch itself is now STATIC: `ExchangeBase`'s default methods call
1084// `DerivedExchange::X(self, ...)` and `self.call_dynamic(...)` directly on the
1085// concrete Core, with no stored self-pointer (review #1). All that remains here
1086// is the per-method re-entry guard the async `dispatch_to_derived` default (in
1087// `exchange_generated::ExchangeBase`) uses so a base method that dispatches its
1088// own name falls through to the base body instead of looping.
1089
1090impl Exchange {
1091    /// Enter the guard for `method`. Returns `false` if `method` is already on
1092    /// the dispatch stack (re-entry — caller should fall through to the base
1093    /// body); otherwise pushes it and returns `true`.
1094    pub fn dispatch_guard_enter(&mut self, method: &str) -> bool {
1095        if self.internals.dispatch_stack.iter().any(|m| m == method) { return false; }
1096        self.internals.dispatch_stack.push(method.to_string());
1097        true
1098    }
1099
1100    /// Leave the guard (pop the most-recently entered method).
1101    pub fn dispatch_guard_exit(&mut self) {
1102        self.internals.dispatch_stack.pop();
1103    }
1104}
1105
1106// ── ExchangeRuntime: base methods that reach derived overrides ───────────────
1107//
1108// A handful of hand-written base methods must call a derived override
1109// (`sign`, `handle_errors`) or dispatch async-by-name, so they need the
1110// concrete Core as `Self` to resolve statically (review #1). They live in this
1111// trait, blanket-impl'd for every `ExchangeBase`, so `self.fetch(...)`,
1112// `self.request_typed(...)`, … on a Core (or inside an `ExchangeBase` default)
1113// resolve here. Bodies reach `Exchange` fields via the `DerefMut` bound, other
1114// base methods via `ExchangeBase`, and pure `impl Exchange` helpers via `Deref`.
1115/// Coerce a `Value` (string, or list of strings) into a `Vec<String>` of
1116/// message/subscribe hashes for the WS drive loop.
1117fn ws_string_list(v: &Value) -> Vec<String> {
1118    match v {
1119        Value::Str(s) => vec![s.to_string()],
1120        Value::Arr(a) => a
1121            .iter()
1122            .filter_map(|x| match x {
1123                Value::Str(s) => Some(s.to_string()),
1124                _ => None,
1125            })
1126            .collect(),
1127        _ => Vec::new(),
1128    }
1129}
1130
1131pub trait ExchangeRuntime: crate::exchange_generated::ExchangeBase {
1132    fn fetch(&mut self, url: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1133        let url_str = match &url { Value::Str(s) => s.to_string(), _ => crate::runtime::stringify_param(&url).into() };
1134        let method = optional_args.get(0).cloned().unwrap_or(Value::Str("GET".into()));
1135        let headers = optional_args.get(1).cloned().unwrap_or(Value::Null);
1136        let body = optional_args.get(2).cloned().unwrap_or(Value::Null);
1137        let method_str = match &method { Value::Str(s) => s.to_string(), _ => "GET".to_string().into() };
1138        let body_str = match &body { Value::Str(s) => Some(s.to_string()), _ => None };
1139        let headers_map: HashMap<String, String> = match &headers {
1140            Value::Dict(m) => m.iter().filter_map(|(k, v)| match v {
1141                Value::Str(s) => Some((k.clone(), s.to_string())),
1142                _ => None,
1143            }).collect(),
1144            _ => HashMap::new(),
1145        };
1146        match self.fetch_typed(&url_str, &method_str, headers_map, body_str).await {
1147            Ok(v) => v,
1148            // `panic!` is the transpiled error convention — `ExchangeError`'s Display
1149            // renders `[Kind] message`, which `is_instance` matches on.
1150            Err(e) => panic!("{}", e),
1151        }
1152    } }
1153
1154    // ── WebSocket (pro) drive loop ──────────────────────────────────────────
1155    //
1156    // Port of the runtime side of `Exchange.watch` / `watchMultiple`. These are
1157    // trait methods (not inherent on `Exchange`) so `self` is the concrete Core
1158    // and `dispatch_to_derived("handle_message", …)` reaches the venue override.
1159    //
1160    // Model: `watch` drives synchronously — it connects, sends the subscribe
1161    // frame once, then loops reading inbound frames and feeding each to the
1162    // venue's `handle_message` (which calls `client.resolve(value, hash)`),
1163    // returning as soon as one of the awaited hashes is settled. A repeated
1164    // `while true { watch_x().await }` consumer therefore gets one update per
1165    // call, exactly like the TS Future model. (Concurrently awaiting two streams
1166    // on the *same* socket via join is a known limitation — each drive loop
1167    // pulls from the shared frame queue.)
1168
1169    /// Shared drive loop for `watch` / `watch_multiple`.
1170    fn ws_run(
1171        &mut self,
1172        url: String,
1173        hashes: Vec<String>,
1174        message: Value,
1175        subscribe_hashes: Vec<String>,
1176        subscription: Value,
1177    ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1178        let __ws_proxy = [&self.wsProxy, &self.ws_proxy, &self.wssProxy]
1179            .iter()
1180            .find_map(|v| match v { Value::Str(s) if !s.is_empty() => Some(s.to_string()), _ => None });
1181        // binary frames are decompressed unless the exchange opts out (mexc, paradex)
1182        let __decompress_binary = !matches!(crate::get_value(&self.options, &Value::Str("decompressBinary".into())), Value::Bool(false));
1183        // options.ws.options.headers ride on the upgrade request, as in the other ports
1184        let __ws_options = crate::get_value(&crate::get_value(&self.options, &Value::Str("ws".into())), &Value::Str("options".into()));
1185        let __ws_headers: Vec<(String, String)> = match crate::get_value(&__ws_options, &Value::Str("headers".into())) {
1186            Value::Dict(m) => m.iter().filter_map(|(k, v)| match v {
1187                Value::Str(s) => Some((k.clone(), s.to_string())),
1188                Value::Int(n) => Some((k.clone(), n.to_string())),
1189                _ => None,
1190            }).collect(),
1191            _ => Vec::new(),
1192        };
1193        let client = match crate::pro::ws_client::ensure_client_with_headers(&url, &__ws_headers, __ws_proxy, __decompress_binary).await {
1194            Ok(c) => c,
1195            Err(e) => panic!("{}", e),
1196        };
1197        if std::env::var("CCXT_WS_DEBUG").is_ok() {
1198            eprintln!("[wswait] {:?}", hashes);
1199        }
1200        client.note_futures(&hashes);
1201        // Subscribe once per hash. Send the message if any subscribe hash was
1202        // newly added, or if none were provided (mirrors TS's
1203        // `subscribeHashes === undefined || missingSubscriptions.length`).
1204        let mut send_subscribe = subscribe_hashes.is_empty();
1205        for sh in &subscribe_hashes {
1206            if client.subscribe_once(sh, subscription.clone()) {
1207                send_subscribe = true;
1208            }
1209        }
1210        if send_subscribe && !matches!(message, Value::Null) {
1211            let payload = match &message {
1212                Value::Str(s) => s.to_string(),
1213                v => v.to_json().to_string(),
1214            };
1215            client.send_text(payload);
1216        }
1217        // Mirror the connection into `self.clients`, the map TS venues iterate
1218        // to decide whether a stream is still worth keeping alive (binance's
1219        // `keepAliveListenKey` re-arms only while some client still holds a
1220        // subscription for the type). The handle serves `subscriptions` /
1221        // `futures` live from the registry, so this stays coherent as
1222        // subscriptions come and go.
1223        crate::runtime::add_element_to_object(
1224            &mut self.clients,
1225            &Value::Str(url.clone().into()),
1226            crate::pro::ws_client::client_value(&url),
1227        );
1228        // If an ancestor ws_run on this task is already driving `url`, don't
1229        // start a nested loop — the subscribe frame was sent above; report the
1230        // current settled state and let the outer loop resolve `hashes`.
1231        let nested_same = WS_DRIVEN_URLS
1232            .try_with(|s| s.lock().unwrap().contains(&url))
1233            .unwrap_or(false);
1234        if nested_same {
1235            return match client.take_settled(&hashes) {
1236                Some(Ok(v)) => v,
1237                _ => Value::Null,
1238            };
1239        }
1240        // Drive the loop, marking `url` for the duration so a nested watch on
1241        // the same url takes the branch above. Establish the task-local set on
1242        // the first (top-level) drive; nested-different-url calls extend it.
1243        if WS_DRIVEN_URLS.try_with(|_| ()).is_ok() {
1244            WS_DRIVEN_URLS.with(|s| { s.lock().unwrap().insert(url.clone()); });
1245            let r = self.ws_drive_loop(client, hashes, url.clone()).await;
1246            WS_DRIVEN_URLS.with(|s| { s.lock().unwrap().remove(&url); });
1247            r
1248        } else {
1249            let mut set = std::collections::HashSet::new();
1250            set.insert(url.clone());
1251            WS_DRIVEN_URLS
1252                .scope(std::sync::Mutex::new(set), self.ws_drive_loop(client, hashes, url.clone()))
1253                .await
1254        }
1255    } }
1256
1257    /// Read → dispatch → drain loop, split out so `ws_run` can wrap it in the
1258    /// `WS_DRIVEN_URLS` task-local scope.
1259    fn ws_drive_loop(
1260        &mut self,
1261        client: std::sync::Arc<crate::pro::ws_client::ClientState>,
1262        hashes: Vec<String>,
1263        url: String,
1264    ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1265        loop {
1266            // Run coroutines scheduled via spawn/delay, inline (they need
1267            // &mut self). Drain repeatedly: a coroutine may schedule another
1268            // (handle_order_book → delay(watch_order_book_snapshot)). Runs at
1269            // the top of the iteration rather than after the dispatch below so
1270            // the `continue` on a fired deadline reaches it too.
1271            loop {
1272                let batch = crate::exchange_stubs::drain_spawn_queue();
1273                if batch.is_empty() { break; }
1274                for (method, args) in batch {
1275                    if std::env::var("CCXT_WS_DEBUG").is_ok() {
1276                        eprintln!("[wsdrain] {}", method);
1277                    }
1278                    if method == "load_order_book" {
1279                        self.ws_load_order_book(args).await;
1280                    } else {
1281                        let _ = self.dispatch_to_derived(&method, args).await;
1282                    }
1283                }
1284            }
1285            if let Some(settled) = client.take_settled(&hashes) {
1286                match settled {
1287                    Ok(v) => return v,
1288                    Err(e) => panic!(
1289                        "{}",
1290                        match &e {
1291                            Value::Str(s) => s.clone(),
1292                            v => crate::runtime::stringify_param(v).into(),
1293                        }
1294                    ),
1295                }
1296            }
1297            // Bound the read by the earliest pending `delay` deadline, so a
1298            // periodic coroutine (binance's `keepAliveListenKey`) still fires
1299            // on a stream that has gone quiet. `next_message` keeps its frames
1300            // in the client's queue, so timing out drops nothing.
1301            let next_due = crate::exchange_stubs::next_spawn_due();
1302            let received = match next_due {
1303                Some(d) => match tokio::time::timeout(d, client.next_message()).await {
1304                    Ok(m) => m,
1305                    // Deadline reached: loop back round to the drain above.
1306                    Err(_) => continue,
1307                },
1308                None => client.next_message().await,
1309            };
1310            let msg = match received {
1311                Some(m) => m,
1312                None => panic!("[NetworkError] {} websocket connection closed", url),
1313            };
1314            if std::env::var("CCXT_WS_DEBUG").is_ok() {
1315                let n: usize = std::env::var("CCXT_WS_DEBUG").ok()
1316                    .and_then(|v| v.parse().ok()).filter(|v| *v > 1).unwrap_or(220);
1317                let s = msg.to_json().to_string();
1318                eprintln!("[wsmsg] {}", s.chars().take(n).collect::<String>());
1319            }
1320            let client_value = crate::pro::ws_client::client_value(&url);
1321            let _ = self
1322                .dispatch_to_derived("handle_message", vec![client_value, msg])
1323                .await;
1324        }
1325    } }
1326
1327    /// Base `loadOrderBook`: fetch the REST depth snapshot, splice the buffered
1328    /// WS cache onto it, and resolve the watcher. Venues spawn this after
1329    /// buffering enough deltas (bitstamp, …). Runs in the drive loop so it can
1330    /// reach the venue's `get_cache_index` / `handle_deltas` overrides.
1331    fn ws_load_order_book(
1332        &mut self,
1333        args: Vec<Value>,
1334    ) -> impl ::std::future::Future<Output = ()> + Send { async move {
1335        let client = args.get(0).cloned().unwrap_or(Value::Null);
1336        let message_hash = args.get(1).cloned().unwrap_or(Value::Null);
1337        let symbol = args.get(2).cloned().unwrap_or(Value::Null);
1338        let limit = args.get(3).cloned().unwrap_or(Value::Null);
1339        let params = args.get(4).cloned().unwrap_or(Value::Map(indexmap::IndexMap::new()));
1340        let err = |id: &Value| Value::Str(format!(
1341            "[ExchangeError] {} loadOrderBook() failed to synchronize",
1342            match id { Value::Str(s) => s.as_ref(), _ => "" }).into());
1343        if !crate::runtime::in_op(&self.orderbooks, &symbol) {
1344            crate::pro::ws_client::value_reject(&client, &[err(&self.id), message_hash]);
1345            return;
1346        }
1347        let max_retries: i64 = 3;
1348        let mut tries = 0;
1349        while tries < max_retries {
1350            let mut stored = crate::get_value(&self.orderbooks, &symbol);
1351            let cache = crate::get_value(&stored, &Value::Str("cache".into()));
1352            let snapshot = self
1353                .dispatch_to_derived("fetch_rest_order_book_safe",
1354                    vec![symbol.clone(), limit.clone(), params.clone()])
1355                .await
1356                .unwrap_or(Value::Null);
1357            let index = self
1358                .dispatch_to_derived("get_cache_index", vec![snapshot.clone(), cache.clone()])
1359                .await;
1360            let idx = match index { Some(Value::Int(n)) => n, _ => -1 };
1361            if idx >= 0 {
1362                stored.reset(snapshot);
1363                let clen = match crate::runtime::get_array_length(&cache) { Value::Int(n) => n, _ => 0 };
1364                let deltas: Vec<Value> = (idx..clen)
1365                    .map(|i| crate::get_value(&cache, &Value::Int(i)))
1366                    .collect();
1367                self.dispatch_to_derived("handle_deltas", vec![stored.clone(), Value::List(deltas)]).await;
1368                crate::set_value(&mut stored, &Value::Str("cache".into()), Value::List(Vec::new()));
1369                crate::pro::ws_client::value_resolve(&client, &[stored.clone(), message_hash.clone()]);
1370                return;
1371            }
1372            tries += 1;
1373        }
1374        crate::pro::ws_client::value_reject(&client, &[err(&self.id), message_hash]);
1375    } }
1376
1377    fn watch(
1378        &mut self,
1379        url: Value,
1380        message_hash: Value,
1381        optional_args: &[Value],
1382    ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1383        let url_s = match &url { Value::Str(s) => s.to_string(), v => crate::runtime::stringify_param(v) };
1384        let hash_s = match &message_hash { Value::Str(s) => s.to_string(), v => crate::runtime::stringify_param(v) };
1385        let message = optional_args.get(0).cloned().unwrap_or(Value::Null);
1386        let subscribe_hash = optional_args.get(1).cloned().unwrap_or(message_hash.clone());
1387        let sub_hash_s = match &subscribe_hash { Value::Str(s) => s.to_string(), v => crate::runtime::stringify_param(v) };
1388        let subscription = optional_args.get(2).cloned().unwrap_or(Value::Null);
1389        self.ws_run(url_s, vec![hash_s], message, vec![sub_hash_s], subscription).await
1390    } }
1391
1392    fn watch_multiple(
1393        &mut self,
1394        url: Value,
1395        message_hashes: Value,
1396        optional_args: &[Value],
1397    ) -> impl ::std::future::Future<Output = Value> + Send { async move {
1398        let url_s = match &url { Value::Str(s) => s.to_string(), v => crate::runtime::stringify_param(v) };
1399        let hashes = ws_string_list(&message_hashes);
1400        let message = optional_args.get(0).cloned().unwrap_or(Value::Null);
1401        let subscribe_hashes = ws_string_list(&optional_args.get(1).cloned().unwrap_or(Value::Null));
1402        let subscription = optional_args.get(2).cloned().unwrap_or(Value::Null);
1403        self.ws_run(url_s, hashes, message, subscribe_hashes, subscription).await
1404    } }
1405
1406    fn fetch_typed(
1407        &mut self,
1408        url:     &str,
1409        method:  &str,
1410        headers: HashMap<String, String>,
1411        body:    Option<String>,
1412    ) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1413        let _fetch_call_count = HTTP_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1414        self.last_request_url     = Value::Str(url.to_string().into());
1415        self.last_request_headers = Value::Map(headers.iter()
1416            .map(|(k, v)| (k.clone(), Value::Str(v.clone().into())))
1417            .collect());
1418        self.last_request_body    = match &body {
1419            Some(b) => Value::Str(b.clone().into()),
1420            None    => Value::Null,
1421        };
1422        // map iteration is unordered, so sort the fragments for a deterministic pick
1423        if let Value::Dict(byUrl) = &self.mock_response_by_url {
1424            let mut fragments: Vec<&String> = byUrl.keys().collect();
1425            fragments.sort();
1426            for fragment in &fragments {
1427                if url.contains(fragment.as_str()) {
1428                    return Ok(byUrl.get(*fragment).cloned().unwrap_or(Value::Null));
1429                }
1430            }
1431            if let Some(first) = fragments.first() {
1432                return Ok(byUrl.get(*first).cloned().unwrap_or(Value::Null));
1433            }
1434        }
1435        if !matches!(self.mock_response, Value::Null) {
1436            return Ok(self.mock_response.clone());
1437        }
1438        let proxy_defined = |v: &Value| matches!(v, Value::Str(s) if !s.is_empty());
1439        let used_proxies = [
1440            proxy_defined(&self.httpProxy)  || proxy_defined(&self.http_proxy),
1441            proxy_defined(&self.httpsProxy) || proxy_defined(&self.https_proxy),
1442            proxy_defined(&self.socksProxy) || proxy_defined(&self.socks_proxy),
1443        ].iter().filter(|x| **x).count();
1444        if used_proxies > 1 {
1445            return Err(ExchangeError::new(
1446                "InvalidProxySettings",
1447                format!("{} you have multiple conflicting proxy settings, please use only one from: httpProxy, httpsProxy, socksProxy",
1448                    match &self.id { Value::Str(s) => s.as_ref(), _ => "" }),
1449            ));
1450        }
1451        let client = self.http_client().clone();
1452        let method_parsed = reqwest::Method::from_bytes(method.as_bytes())
1453            .map_err(|_| ExchangeError::new("BadRequest", format!("invalid HTTP method: {method}")))?;
1454        let mut req = client.request(method_parsed, url);
1455        for (k, v) in &self.internals.headers { req = req.header(k, v); }
1456        for (k, v) in &headers                { req = req.header(k, v); }
1457        if self.is_verbose() {
1458            eprintln!("[ccxt] {method} {url}");
1459            for (k, v) in &self.internals.headers { eprintln!("[ccxt]   {k}: {v}"); }
1460            for (k, v) in &headers                { eprintln!("[ccxt]   {k}: {v}"); }
1461            if let Some(b) = &body {
1462                eprintln!("[ccxt]   request body: {b}");
1463            }
1464        }
1465        if let Some(b) = body                 { req = req.body(b); }
1466        let __http_t0 = std::time::Instant::now();
1467        let resp = req.send().await?;
1468        let status = resp.status().as_u16();
1469        let reason = resp.status().canonical_reason().unwrap_or("");
1470        let text   = resp.text().await?;
1471        HTTP_NANOS.fetch_add(__http_t0.elapsed().as_nanos() as u64,
1472            std::sync::atomic::Ordering::Relaxed);
1473        if self.is_verbose() {
1474            eprintln!("[ccxt] ← {status} {} bytes", text.len());
1475            const CAP: usize = 16384;
1476            if text.len() > CAP {
1477                eprintln!("[ccxt]   response body: {}… ({} bytes total)",
1478                    &text[..text.char_indices().take_while(|(i, _)| *i < CAP).last().map(|(i, c)| i + c.len_utf8()).unwrap_or(0)],
1479                    text.len());
1480            } else {
1481                eprintln!("[ccxt]   response body: {text}");
1482            }
1483        }
1484        let __json_t0 = std::time::Instant::now();
1485        let json = match serde_json::from_str::<serde_json::Value>(&text) {
1486            Ok(j)  => Value::from_json(&j),
1487            Err(_) => Value::Null,
1488        };
1489        JSON_NANOS.fetch_add(__json_t0.elapsed().as_nanos() as u64,
1490            std::sync::atomic::Ordering::Relaxed);
1491        // Venues also report failures in a 2xx body, so every response goes through
1492        // the derived handle_errors; a Null result falls back to httpExceptions.
1493        let handled = crate::exchange::DerivedExchange::handle_errors(
1494            self,
1495            Value::Int(status as i64),
1496            Value::Str(reason.into()),
1497            Value::Str(url.to_string().into()),
1498            Value::Str(method.to_string().into()),
1499            Value::Null,
1500            Value::Str(text.clone().into()),
1501            json.clone(),
1502            Value::Null,
1503            Value::Null,
1504        );
1505        if matches!(handled, Value::Null) {
1506            self.handle_http_status_code(
1507                Value::Int(status as i64),
1508                Value::Str(reason.into()),
1509                Value::Str(url.to_string().into()),
1510                Value::Str(method.to_string().into()),
1511                Value::Str(text.clone().into()),
1512            );
1513        }
1514        if status >= 400 {
1515            return Err(ExchangeError::new(
1516                if status == 429 { "RateLimitExceeded" }
1517                else if status >= 500 { "ExchangeNotAvailable" }
1518                else { "ExchangeError" },
1519                format!("HTTP {status}: {text}"),
1520            ));
1521        }
1522        if matches!(json, Value::Null) {
1523            return Ok(Value::Str(text.into()));
1524        }
1525        Ok(json)
1526    } }
1527
1528    fn request_typed(&mut self, path: &str, scope_segments: &[String], verb: &str, params: Value, cost: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1529        // Mock transport responses only; preserve the signed request metadata.
1530        if matches!(self.mock_response, Value::Null) && matches!(self.mock_response_by_url, Value::Null) {
1531            self.throttle(&[cost]).await;
1532        }
1533        let api_arg = Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect());
1534        let scope_lookup: String = scope_segments.first().cloned().unwrap_or_default();
1535        // Static dispatch to the derived exchange's sign override.
1536        let signed = crate::exchange::DerivedExchange::sign(
1537            self,
1538            Value::Str(path.to_string().into()),
1539            api_arg,
1540            Value::Str(verb.to_string().into()),
1541            params.clone(),
1542            Value::Null,
1543            Value::Null,
1544        );
1545        if let Value::Dict(m) = &signed {
1546            let url = match m.get("url") { Some(Value::Str(s)) => s.to_string(), _ => String::new().into() };
1547            let method = match m.get("method") { Some(Value::Str(s)) => s.to_string(), _ => verb.to_string().into() };
1548            let body = match m.get("body") { Some(Value::Str(s)) => Some(s.to_string()), _ => None };
1549            let headers = match m.get("headers") {
1550                Some(Value::Dict(h)) => h.iter()
1551                    .filter_map(|(k, v)| match v { Value::Str(s) => Some((k.clone(), s.to_string())), _ => None })
1552                    .collect::<HashMap<_, _>>(),
1553                _ => HashMap::new(),
1554            };
1555            if !url.is_empty() {
1556                return self.fetch_typed(&url, &method, headers, body).await;
1557            }
1558        }
1559        let base = self.url_for_scope(&scope_lookup).ok_or_else(|| ExchangeError::new(
1560            "BadRequest",
1561            format!("no URL configured for api scope `{scope_lookup}`"),
1562        ))?;
1563        let imploded = self.implode_params(Value::Str(path.to_string().into()), params.clone());
1564        let path_str = match &imploded { Value::Str(s) => s.clone(), _ => path.to_string().into() };
1565        let consumed_keys = self.extract_path_params(path);
1566        let remaining_params = match params {
1567            Value::Dict(m) => {
1568                let mut keep = HashMap::new();
1569                let m = Arc::try_unwrap(m).unwrap_or_else(|a| (*a).clone());
1570                for (k, v) in m {
1571                    if !consumed_keys.contains(&k) { keep.insert(k, v); }
1572                }
1573                Value::Map(keep)
1574            }
1575            other => other,
1576        };
1577        let mut url = format!("{}/{}", base.trim_end_matches('/'), path_str.trim_start_matches('/'));
1578        let mut body: Option<String> = None;
1579        let qs = match &remaining_params {
1580            Value::Dict(m) if !m.is_empty() => self.urlencode_kv(&remaining_params),
1581            _ => String::new(),
1582        };
1583        if verb == "GET" || verb == "DELETE" {
1584            if !qs.is_empty() {
1585                url = format!("{}?{}", url, qs);
1586            }
1587        } else if !qs.is_empty() {
1588            body = Some(qs);
1589        }
1590        let mut headers = HashMap::new();
1591        if scope_lookup != "public" {
1592            if let Value::Str(k) = &self.apiKey {
1593                headers.insert("X-MBX-APIKEY".to_string(), k.to_string());
1594            }
1595        }
1596        self.fetch_typed(&url, verb, headers, body).await
1597    } }
1598
1599    /// Route an implicit-API method name to `request_typed`.
1600    fn implicit_api_call(&mut self, name: &str, params: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1601        if self.internals.implicit_api.is_empty() {
1602            self.build_implicit_api();
1603        }
1604        let entry = self.internals.implicit_api.get(name).cloned();
1605        let (path, scope_segments, verb, config) = match entry {
1606            Some(t) => t,
1607            None => return Err(ExchangeError::new(
1608                "NotSupported",
1609                format!("implicit API method {name} not found in api block"),
1610            )),
1611        };
1612        let api = Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect());
1613        let cost = if matches!(self.enableRateLimit, Value::Bool(true)) {
1614            self.call_dynamic(
1615                "calculate_rate_limiter_cost",
1616                vec![api, Value::Str(verb.clone().into()), Value::Str(path.clone().into()), params.clone(), config],
1617            ).await
1618        } else {
1619            Value::Null
1620        };
1621        self.request_typed(&path, &scope_segments, &verb, params, cost).await
1622    } }
1623
1624    #[doc(hidden)]
1625    fn implicit_api_rate_limit_cost(&mut self, name: &str, params: Value) -> impl ::std::future::Future<Output = Result<Value>> + Send { async move {
1626        if self.internals.implicit_api.is_empty() {
1627            self.build_implicit_api();
1628        }
1629        let (path, scope_segments, verb, config) = self.internals.implicit_api
1630            .get(name)
1631            .cloned()
1632            .ok_or_else(|| ExchangeError::new("NotSupported", format!("implicit API method {name} not found in api block")))?;
1633        let api = Value::Array(scope_segments.iter().map(|s| Value::Str(s.clone().into())).collect());
1634        Ok(self.call_dynamic(
1635            "calculate_rate_limiter_cost",
1636            vec![api, Value::Str(verb.into()), Value::Str(path.into()), params, config],
1637        ).await)
1638    } }
1639
1640    /// Dispatch an implicit-API method by name (from transpiled `_api.rs`).
1641    fn call_method(&mut self, name: Value, args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1642        let n = match name { Value::Str(s) => s, _ => return Value::Null };
1643        let params = args.get(0).cloned().unwrap_or(Value::Map(HashMap::new()));
1644        match self.implicit_api_call(&n, params).await {
1645            Ok(v) => v,
1646            Err(e) => {
1647                if matches!(self.verbose, Value::Bool(true)) {
1648                    eprintln!("[ccxt] {n} failed: {e}");
1649                }
1650                panic!("{e}");
1651            }
1652        }
1653    } }
1654
1655    /// Loads markets (and currencies), dispatching `fetch_markets` /
1656    /// `fetch_currencies` / `set_markets` to the derived overrides.
1657    fn load_markets(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
1658        let reload = optional_args.get(0).cloned().unwrap_or(Value::Bool(false));
1659        let reload_b = matches!(reload, Value::Bool(true));
1660        if !reload_b && !self.markets.is_null() {
1661            return self.markets.clone();
1662        }
1663        let has_fetch_currencies = matches!(
1664            crate::get_value(&self.has, &Value::Str("fetchCurrencies".into())),
1665            Value::Bool(true),
1666        );
1667        let mut currencies = Value::Null;
1668        if has_fetch_currencies {
1669            if let Some(v) = self.dispatch_to_derived("fetch_currencies", Vec::new()).await {
1670                currencies = v;
1671            }
1672        }
1673        let fetched = match self.dispatch_to_derived("fetch_markets", Vec::new()).await {
1674            Some(v) => v,
1675            None => return Value::Null,
1676        };
1677        if matches!(fetched, Value::Null) {
1678            return self.markets.clone();
1679        }
1680        let preloaded_non_empty = matches!(&self.currencies, Value::Dict(m) if !m.is_empty());
1681        let currencies_arg = if matches!(&currencies, Value::Dict(m) if !m.is_empty()) {
1682            currencies
1683        } else if preloaded_non_empty {
1684            self.currencies.clone()
1685        } else {
1686            crate::exchange_stubs::synthesize_currencies_from_markets(&fetched, &self.precisionMode)
1687        };
1688        let is_prediction = matches!(
1689            crate::get_value(&self.has, &Value::Str("prediction".into())),
1690            Value::Bool(true),
1691        );
1692        if is_prediction {
1693            let _ = self.dispatch_to_derived("set_markets", vec![fetched, currencies_arg]).await;
1694        } else {
1695            <Self as crate::exchange_generated::ExchangeBase>::set_markets(self, fetched, &[currencies_arg]);
1696        }
1697        // Index markets_by_id by the secondary id (`id2`, e.g. apex's
1698        // crossSymbolName) too, so a WS handler that resolves a market from the
1699        // id2-based stream id (`safeMarket(data['s'])`) reaches the unified
1700        // symbol instead of a synthetic one.
1701        let markets_snapshot = self.markets.clone();
1702        if let Value::Dict(markets) = &markets_snapshot {
1703            if let Value::Dict(by_id_arc) = &self.markets_by_id {
1704                let mut by_id = (**by_id_arc).clone();
1705                for market in markets.values() {
1706                    let id  = crate::get_value(market, &Value::Str("id".into()));
1707                    let id2 = crate::get_value(market, &Value::Str("id2".into()));
1708                    if let (Value::Str(id2s), Value::Str(ids)) = (&id2, &id) {
1709                        if id2s != ids && !id2s.is_empty() && !by_id.contains_key(id2s.as_ref()) {
1710                            by_id.insert(id2s.to_string(), Value::List(vec![market.clone()]));
1711                        }
1712                    }
1713                }
1714                self.markets_by_id = Value::Map(by_id);
1715            }
1716        }
1717        self.markets.clone()
1718    } }
1719
1720    // ── super.X() shims — call the BASE (ExchangeBase) method, fully-qualified
1721    // so a derived override is bypassed (that is what `super.X()` means).
1722    fn super_describe(&self) -> Value {
1723        <Self as crate::exchange_generated::ExchangeBase>::describe(self)
1724    }
1725    fn super_set_sandbox_mode(&mut self, enabled: Value) {
1726        <Self as crate::exchange_generated::ExchangeBase>::set_sandbox_mode(self, enabled);
1727    }
1728    fn super_safe_market(&self, id: Value, market: Value, delim: Value, market_type: Value) -> Value {
1729        <Self as crate::exchange_generated::ExchangeBase>::safe_market(self, &[id, market, delim, market_type])
1730    }
1731    fn super_handle_market_type_and_params(&self, method_name: Value, market: Value, params: Value, default_value: Value) -> Value {
1732        <Self as crate::exchange_generated::ExchangeBase>::handle_market_type_and_params(self, method_name, &[market, params, default_value])
1733    }
1734    fn super_market(&self, symbol: Value) -> Value {
1735        <Self as crate::exchange_generated::ExchangeBase>::market_non_virtual(self, symbol)
1736    }
1737    fn super_amount_to_precision(&self, symbol: Value, amount: Value) -> Value {
1738        <Self as crate::exchange_generated::ExchangeBase>::amount_to_precision(self, symbol, amount)
1739    }
1740    fn super_handle_margin_mode_and_params(&self, method_name: Value, params: Value, default_value: Value) -> Value {
1741        <Self as crate::exchange_generated::ExchangeBase>::handle_margin_mode_and_params(self, method_name, &[params, default_value])
1742    }
1743    fn super_safe_currency_code(&self, currency_id: Value, currency: Value) -> Value {
1744        <Self as crate::exchange_generated::ExchangeBase>::safe_currency_code(self, currency_id, &[currency])
1745    }
1746    fn super_set_markets(&mut self, markets: Value, currencies: Value) -> Value {
1747        <Self as crate::exchange_generated::ExchangeBase>::set_markets(self, markets, &[currencies])
1748    }
1749    fn super_network_id_to_code(&self, optional_args: &[Value]) -> Value {
1750        <Self as crate::exchange_generated::ExchangeBase>::network_id_to_code(self, optional_args)
1751    }
1752    fn super_network_code_to_id(&self, network_code: Value, optional_args: &[Value]) -> Value {
1753        <Self as crate::exchange_generated::ExchangeBase>::network_code_to_id(self, network_code, optional_args)
1754    }
1755    fn super_fetch_deposit_address(&mut self, code: Value, params: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
1756        self.fetch_deposit_address(code, &[params]).await
1757    } }
1758    fn super_load_markets(&mut self, reload: Value, params: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
1759        self.load_markets(&[reload, params]).await
1760    } }
1761}
1762
1763impl<T: crate::exchange_generated::ExchangeBase> ExchangeRuntime for T {}
1764
1765/// Normalize a TS dynamic method name for the generated Rust dispatch table.
1766///
1767/// Must stay byte-identical to the transpiler's `toSnakeCase`
1768/// (`build/rustTranspiler.ts`) and to `Exchange::to_snake_case` (which names
1769/// the implicit-API entries `call_dynamic`'s fall-through looks up) — it is the
1770/// only thing deciding whether a paginated `this[method](...)` re-entry lands
1771/// on a dispatch arm. `method_name_snake_case_tests` pins all three.
1772///
1773/// A name that is not a `Value::Str` (or is empty) is a hard bug: TS
1774/// `this[name](...)` always indexes with a string. Returning `""` here would
1775/// resolve to no dispatch arm and no implicit endpoint, so `call_dynamic`
1776/// would hand back `Value::Null` and the caller would silently see an empty
1777/// page instead of an error — exactly the failure this PR set out to remove.
1778/// Panic instead, mirroring the TS `TypeError: this[method] is not a function`
1779/// (the transpiled try/catch turns it back into a catchable error).
1780pub fn method_name_to_snake_case(name: &Value) -> String {
1781    let name = match name {
1782        Value::Str(name) if !name.is_empty() => name,
1783        _ => panic!(
1784            "{}",
1785            crate::exchange_errors::not_supported(format!(
1786                "dynamic method dispatch requires a non-empty string method name, got {name:?}"
1787            )),
1788        ),
1789    };
1790    let chars: Vec<char> = name.chars().collect();
1791    let mut out = String::with_capacity(name.len() + 4);
1792    for (i, &c) in chars.iter().enumerate() {
1793        if c.is_ascii_uppercase() {
1794            let lower_before = i > 0
1795                && (chars[i - 1].is_ascii_lowercase() || chars[i - 1].is_ascii_digit());
1796            let acronym_end = i > 0 && chars[i - 1].is_ascii_uppercase()
1797                && chars.get(i + 1).map(|next| next.is_ascii_lowercase()).unwrap_or(false);
1798            if lower_before || acronym_end {
1799                out.push('_');
1800            }
1801            out.push(c.to_ascii_lowercase());
1802        } else {
1803            out.push(c);
1804        }
1805    }
1806    out
1807}
1808
1809/// Wraps a `call_dynamic` re-entry that MUST resolve. `call_dynamic_base`'s
1810/// `_` arm returns `Value::Null` for a name that is neither a dispatch arm nor
1811/// an implicit-API endpoint — fine for an optional probe, but a dynamic
1812/// re-entry from `fetchPaginatedCall*` / `fetchWebEndpoint` would then hand the
1813/// caller an empty page instead of an error. That arm records the miss on
1814/// `internals.dynamic_dispatch_miss`; this raises it as a loud `NotSupported`,
1815/// the way `call_method` used to fail, so a dispatch regression surfaces as an
1816/// error rather than as null data (review on #30385).
1817pub trait CallDynamicChecked: crate::exchange_generated::ExchangeBase {
1818    fn call_dynamic_checked(&mut self, name: Value, args: Vec<Value>) -> impl ::std::future::Future<Output = Value> + Send { async move {
1819        let snake = method_name_to_snake_case(&name);
1820        // Clear first: a miss recorded by an unrelated earlier probe must not
1821        // be attributed to this call.
1822        self.internals.dynamic_dispatch_miss = None;
1823        let out = self.call_dynamic(&snake, args).await;
1824        // Only OUR name counts — a nested optional probe inside the dispatched
1825        // method legitimately misses and must stay silent.
1826        if self.internals.dynamic_dispatch_miss.as_deref() == Some(snake.as_str()) {
1827            self.internals.dynamic_dispatch_miss = None;
1828            panic!(
1829                "{}",
1830                crate::exchange_errors::not_supported(format!(
1831                    "{} dynamic method {snake}() resolved to no dispatch arm and no implicit API endpoint",
1832                    crate::runtime::stringify_param(&self.id),
1833                )),
1834            );
1835        }
1836        out
1837    } }
1838}
1839
1840impl<T: crate::exchange_generated::ExchangeBase> CallDynamicChecked for T {}
1841
1842/// A minimal Core wrapping a bare `Exchange` with NO overrides. Lets code that
1843/// only has an `Exchange` value — `Value` snapshots (value.rs), the constructor
1844/// (`after_construct`), and base unit tests — call `ExchangeBase`/`ExchangeRuntime`
1845/// trait methods, which all resolve to the base defaults (review #1: base
1846/// methods are trait methods now, so a bare `Exchange` can't call them directly).
1847pub struct BaseCore {
1848    pub exchange: Exchange,
1849}
1850impl BaseCore {
1851    pub fn new(exchange: Exchange) -> Self { Self { exchange } }
1852    pub fn into_inner(self) -> Exchange { self.exchange }
1853}
1854impl std::ops::Deref for BaseCore {
1855    type Target = Exchange;
1856    fn deref(&self) -> &Exchange { &self.exchange }
1857}
1858impl std::ops::DerefMut for BaseCore {
1859    fn deref_mut(&mut self) -> &mut Exchange { &mut self.exchange }
1860}
1861impl DerivedExchange for BaseCore {}
1862impl crate::exchange_generated::ExchangeBase for BaseCore {
1863    fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<Value>)
1864        -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>>
1865    {
1866        Box::pin(async move { self.call_dynamic_base(method, args).await })
1867    }
1868}
1869
1870// ── implicit API dispatch ───────────────────────────────────────────────────
1871
1872impl Exchange {
1873    /// Builds the `name → (path, scope, verb)` dispatch table by walking
1874    /// the `self.api` Value::Map. Called lazily on first dynamic call.
1875    ///
1876    /// The `api` block layout is:
1877    ///   { <scope>: { <verb>: [path, path, ...] } }
1878    ///   { <scope>: { <subscope>: { <verb>: [path, ...] } } }
1879    /// — arbitrary nesting before the verb level. The verb is one of
1880    /// `get`/`post`/`put`/`delete`/`patch` (any case). All path components
1881    /// before the verb concatenate into the scope (joined by `_`).
1882    pub fn build_implicit_api(&mut self) {
1883        let mut map: HashMap<String, (String, Vec<String>, String, Value)> = HashMap::new();
1884        Self::walk_api_node(&self.api, &[], &mut map);
1885        self.internals.implicit_api = map;
1886    }
1887
1888    fn walk_api_node(
1889        node: &Value,
1890        crumbs: &[String],
1891        out: &mut HashMap<String, (String, Vec<String>, String, Value)>,
1892    ) {
1893        let known_verbs = ["get", "post", "put", "delete", "patch"];
1894        let last_is_verb = crumbs.last()
1895            .map(|c| known_verbs.iter().any(|v| *v == c.to_lowercase().as_str()))
1896            .unwrap_or(false);
1897        match node {
1898            // If the current level is a verb (`get`/`post`/…) and its child
1899            // is a Map, the keys ARE the paths (and values are rate-limit
1900            // costs — exchange-specific).
1901            Value::Dict(m) if last_is_verb => {
1902                let verb = crumbs.last().unwrap().to_lowercase();
1903                // Method name uses snake-cased scope (`fapi_public_get_X`).
1904                let scope_snake = Self::api_scope_from_crumbs(&crumbs[..crumbs.len() - 1]);
1905                // But sign()/urls.api lookup uses the original segments
1906                // (camelCase, e.g. `["fapiPublic"]` for binance,
1907                //  `["public","common"]` for bitget, `["public","spot"]`
1908                //  for gate). Preserve as Vec<String> so the dispatcher
1909                //  can choose Value::Str (single) vs Value::Array (multi).
1910                let scope_segments: Vec<String> = crumbs[..crumbs.len() - 1].to_vec();
1911                for (path_key, endpoint_config) in m.iter() {
1912                    let config = match endpoint_config {
1913                        Value::Dict(_) => endpoint_config.clone(),
1914                        Value::Int(_) | Value::Float(_) => Value::Map({
1915                            let mut config = crate::value::HashMap::new();
1916                            config.insert("cost".to_string(), endpoint_config.clone());
1917                            config
1918                        }),
1919                        _ => Value::Map(crate::value::HashMap::new()),
1920                    };
1921                    Self::register_implicit(&verb, &scope_snake, &scope_segments, path_key, config, out);
1922                }
1923            }
1924            Value::Dict(m) => {
1925                for (key, child) in m.iter() {
1926                    let mut next = crumbs.to_vec();
1927                    next.push(key.clone());
1928                    Self::walk_api_node(child, &next, out);
1929                }
1930            }
1931            // Some exchanges use `Array<path-string>` at the verb level.
1932            Value::Arr(a) if last_is_verb => {
1933                let verb = crumbs.last().unwrap().to_lowercase();
1934                let scope_snake = Self::api_scope_from_crumbs(&crumbs[..crumbs.len() - 1]);
1935                let scope_segments: Vec<String> = crumbs[..crumbs.len() - 1].to_vec();
1936                for path in a.iter() {
1937                    let (path_str, config) = match path {
1938                        Value::Str(s) => (s.clone(), Value::Map(crate::value::HashMap::new())),
1939                        Value::Dict(pm) => match pm.get("method").or_else(|| pm.get("path")) {
1940                            Some(Value::Str(s)) => (s.clone(), path.clone()),
1941                            _ => continue,
1942                        },
1943                        _ => continue,
1944                    };
1945                    Self::register_implicit(&verb, &scope_snake, &scope_segments, &path_str, config, out);
1946                }
1947            }
1948            _ => {}
1949        }
1950    }
1951
1952    fn api_scope_from_crumbs(crumbs: &[String]) -> String {
1953        // The scope identifier in TS is camelCase (e.g. `fapiPrivate`),
1954        // but transpiled call sites are snake_case (`fapi_private_get_X`).
1955        // Convert each crumb camelCase → snake_case and join with `_`.
1956        crumbs.iter()
1957            .map(|s| s
1958                .chars()
1959                .enumerate()
1960                .flat_map(|(i, c)| {
1961                    if c.is_ascii_uppercase() && i > 0 {
1962                        vec!['_', c.to_ascii_lowercase()]
1963                    } else {
1964                        vec![c.to_ascii_lowercase()]
1965                    }
1966                })
1967                .collect::<String>())
1968            .collect::<Vec<_>>()
1969            .join("_")
1970    }
1971
1972    fn register_implicit(
1973        verb: &str,
1974        scope_snake: &str,
1975        scope_segments: &[String],
1976        path: &str,
1977        config: Value,
1978        out: &mut HashMap<String, (String, Vec<String>, String, Value)>,
1979    ) {
1980        // CCXT's TS `defineRestApiEndpoint` builds the method name by
1981        // splitting the path on EVERY non-alphanumeric character:
1982        //   `path.split(/[^a-zA-Z0-9]/)` → capitalize each part → join.
1983        // So `:`, `{`, `}`, `/`, `.`, `-` are all separators. Examples:
1984        //   `ticker/24hr`                      → `Ticker24hr` → `ticker24hr`
1985        //   `lending/auto-invest`              → `LendingAutoInvest` → `lending_auto_invest`
1986        //   `candles/trade:{tf}:{sym}/hist`    → `CandlesTradeTfSymHist`
1987        //                                      → `candles_trade_tf_sym_hist`
1988        let camel: String = path
1989            .split(|c: char| !c.is_ascii_alphanumeric())
1990            .filter(|s| !s.is_empty())
1991            .map(|seg| {
1992                let mut chars = seg.chars();
1993                match chars.next() {
1994                    None => String::new(),
1995                    Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
1996                }
1997            })
1998            .collect();
1999        // snake_case from camel: insert `_` between [a-z\d] and [A-Z],
2000        // and between [A-Z]+ and [A-Z][a-z]. Mirrors the transpiler's
2001        // toSnakeCase exactly.
2002        let snake = Self::to_snake_case(&camel);
2003        // An empty path (e.g. nado's `archive: { post: { '': 1 } }`, method
2004        // name `archivePost`) must NOT append a trailing `_` — the transpiled
2005        // call site looks up `archive_post`, not `archive_post_`.
2006        let snake_name = if snake.is_empty() {
2007            format!("{scope_snake}_{verb}")
2008        } else {
2009            format!("{scope_snake}_{verb}_{snake}")
2010        };
2011        // CamelCase variant: `<scope_camel><Verb><PathCamel>` — TS often
2012        // constructs method names dynamically as camelCase (e.g. bit2c's
2013        // `"privatePostOrderAddOrder"`). `self.call_method(name, ...)`
2014        // looks up by exact string, so register both keys.
2015        let scope_camel: String = scope_segments.iter()
2016            .enumerate()
2017            .map(|(i, s)| {
2018                if i == 0 {
2019                    s.to_string()
2020                } else {
2021                    let mut chars = s.chars();
2022                    match chars.next() {
2023                        None => String::new(),
2024                        Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
2025                    }
2026                }
2027            })
2028            .collect();
2029        let verb_camel = {
2030            let mut chars = verb.chars();
2031            match chars.next() {
2032                None => String::new(),
2033                Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str().to_lowercase().as_str(),
2034            }
2035        };
2036        let camel_name = format!("{scope_camel}{verb_camel}{camel}");
2037        // Snake-cased from the WHOLE camel name, which is what the transpiler
2038        // does to produce the call site. It usually equals `snake_name` above,
2039        // but the two diverge when a path segment starts with a digit: joining
2040        // pre-snaked parts forces a separator the transpiler never inserts, so
2041        // revolutx's `1.0/public/tickers` registers as
2042        // `public_get_10_public_tickers` while the generated code calls
2043        // `public_get10_public_tickers` (toSnakeCase puts no `_` between a
2044        // digit and the preceding letter). Register both spellings so either
2045        // resolves.
2046        let camel_snake_name = Self::to_snake_case(&camel_name);
2047        let entry = (path.to_string(), scope_segments.to_vec(), verb.to_uppercase(), config);
2048        out.insert(snake_name, entry.clone());
2049        if !out.contains_key(&camel_snake_name) {
2050            out.insert(camel_snake_name, entry.clone());
2051        }
2052        if !out.contains_key(&camel_name) {
2053            out.insert(camel_name, entry);
2054        }
2055    }
2056
2057    fn to_snake_case(s: &str) -> String {
2058        // 1st pass: `[A-Z]+([A-Z][a-z])` → `$1_$2`
2059        let bytes: Vec<char> = s.chars().collect();
2060        let mut out = String::with_capacity(s.len() + 4);
2061        for i in 0..bytes.len() {
2062            let c = bytes[i];
2063            let prev = if i > 0 { Some(bytes[i - 1]) } else { None };
2064            let next = if i + 1 < bytes.len() { Some(bytes[i + 1]) } else { None };
2065            if c.is_ascii_uppercase() {
2066                let prev_lower_or_digit = prev
2067                    .map(|p| p.is_ascii_lowercase() || p.is_ascii_digit())
2068                    .unwrap_or(false);
2069                let prev_upper = prev.map(|p| p.is_ascii_uppercase()).unwrap_or(false);
2070                let next_lower = next.map(|n| n.is_ascii_lowercase()).unwrap_or(false);
2071                if prev_lower_or_digit {
2072                    out.push('_');
2073                } else if prev_upper && next_lower {
2074                    out.push('_');
2075                }
2076            }
2077            out.push(c.to_ascii_lowercase());
2078        }
2079        // Collapse any `__` runs introduced by underscores already in input.
2080        while out.contains("__") {
2081            out = out.replace("__", "_");
2082        }
2083        out.trim_matches('_').to_string()
2084    }
2085
2086    /// Resolves the base URL for a given api scope. Looks up
2087    /// `urls.api.<scope>`; if that's itself a map, prefers `rest`.
2088    fn url_for_scope(&self, scope: &str) -> Option<String> {
2089        let api = crate::get_value(&self.urls, &Value::Str("api".into()));
2090        // Try scoped first (binance-style: urls.api.public, urls.api.private).
2091        let scoped = crate::get_value(&api, &Value::Str(scope.to_string().into()));
2092        let raw = match scoped {
2093            Value::Str(s) => s,
2094            Value::Dict(m) => match m.get("rest").or_else(|| m.get("current")) {
2095                Some(Value::Str(s)) => s.clone(),
2096                _ => return self.fallback_rest_url(&api),
2097            },
2098            _ => return self.fallback_rest_url(&api),
2099        };
2100        Some(self.implode_hostname_typed(&raw))
2101    }
2102
2103    /// Many exchanges (okx, kucoin, bitget, gate, hyperliquid, …) use
2104    /// a single `urls.api.rest` URL for all scopes. Fall back to it
2105    /// when the per-scope lookup misses.
2106    fn fallback_rest_url(&self, api: &Value) -> Option<String> {
2107        let rest = crate::get_value(api, &Value::Str("rest".into()));
2108        if let Value::Str(s) = rest {
2109            return Some(self.implode_hostname_typed(&s));
2110        }
2111        // Last resort: if urls.api itself is a string, use it.
2112        if let Value::Str(s) = api {
2113            return Some(self.implode_hostname_typed(s));
2114        }
2115        None
2116    }
2117
2118    /// Internal typed `{hostname}` substitution.
2119    fn implode_hostname_typed(&self, url: &str) -> String {
2120        let host = match &self.hostname {
2121            Value::Str(s) => s.clone(),
2122            _ => return url.to_string(),
2123        };
2124        url.replace("{hostname}", &host)
2125    }
2126
2127    // Dispatches an implicit API call. Looks the method up in the dispatch
2128    // table (building it on first use) and routes through `request`.
2129    // Public-endpoint request: imploding params into the path/query and
2130    // hitting `fetch`. Private endpoints need per-exchange signing — for
2131    // now we treat anything outside `public` as a stub that returns Null.
2132    fn extract_path_params(&self, path: &str) -> Vec<String> {
2133        let mut out: Vec<String> = vec![];
2134        let mut chars = path.chars().peekable();
2135        while let Some(c) = chars.next() {
2136            if c == '{' {
2137                let mut name = String::new();
2138                while let Some(&nc) = chars.peek() {
2139                    if nc == '}' { chars.next(); break; }
2140                    name.push(nc); chars.next();
2141                }
2142                if !name.is_empty() { out.push(name); }
2143            }
2144        }
2145        out
2146    }
2147}
2148
2149/// Raw digest bytes for a named hash algorithm — includes Keccak-256
2150/// (`keccak`), used by ETH-style signing (hyperliquid, etc.).
2151pub(crate) fn hash_raw(data: &[u8], algo: &str) -> Vec<u8> {
2152    match algo.to_ascii_lowercase().as_str() {
2153        "sha256" => { let mut h = Sha256::new(); h.update(data); h.finalize().to_vec() }
2154        "sha512" => { let mut h = Sha512::new(); h.update(data); h.finalize().to_vec() }
2155        "sha1"   => { let mut h = Sha1::new();   h.update(data); h.finalize().to_vec() }
2156        "md5"    => { let mut h = Md5::new();    h.update(data); h.finalize().to_vec() }
2157        "keccak" | "keccak256" => {
2158            use sha3::{Keccak256, Digest as _};
2159            let mut h = Keccak256::new();
2160            h.update(data);
2161            h.finalize().to_vec()
2162        }
2163        _ => Vec::new(),
2164    }
2165}
2166
2167/// EIP-712 `encode` — produces the `\x19\x01 || domainSeparator ||
2168/// hashStruct(message)` preimage. The caller keccak-hashes this into the
2169/// 32-byte digest that gets ECDSA-signed (hyperliquid, etc.).
2170type Eip712Types = std::collections::BTreeMap<String, Vec<(String, String)>>;
2171
2172/// Strip a trailing `[...]` array suffix from an EIP-712 field type, so
2173/// `Order[]` and `Order` both resolve to the struct name `Order`.
2174fn eip712_base_type(ty: &str) -> &str {
2175    match ty.find('[') { Some(i) => &ty[..i], None => ty }
2176}
2177
2178/// EIP-712 `encodeType`: the primary type's signature followed by every
2179/// referenced struct type, sorted alphabetically (per the spec), so a nested
2180/// `TypedDataSign(Order contents,…)` correctly appends `Order(uint256 salt,…)`.
2181fn eip712_encode_type(primary: &str, types: &Eip712Types) -> String {
2182    fn collect(name: &str, types: &Eip712Types, deps: &mut std::collections::BTreeSet<String>) {
2183        if let Some(fields) = types.get(name) {
2184            for (_, ty) in fields {
2185                let base = eip712_base_type(ty).to_string();
2186                if types.contains_key(&base) && deps.insert(base.clone()) {
2187                    collect(&base, types, deps);
2188                }
2189            }
2190        }
2191    }
2192    let fmt = |name: &str| -> String {
2193        let fields = types.get(name).cloned().unwrap_or_default();
2194        let inner: Vec<String> = fields.iter().map(|(n, t)| format!("{t} {n}")).collect();
2195        format!("{}({})", name, inner.join(","))
2196    };
2197    let mut deps = std::collections::BTreeSet::new();
2198    collect(primary, types, &mut deps);
2199    deps.remove(primary);
2200    let mut out = fmt(primary);
2201    for dep in &deps { out.push_str(&fmt(dep)); } // BTreeSet iterates sorted
2202    out
2203}
2204
2205pub(crate) fn eip712_encode(domain: &Value, types: &Value, message: &Value) -> Vec<u8> {
2206    let dm = match domain { Value::Dict(m) => m, _ => return Vec::new() };
2207    // EIP712Domain field set — canonical order, only the keys present.
2208    let mut domain_fields: Vec<(String, String)> = Vec::new();
2209    for (n, t) in [("name", "string"), ("version", "string"), ("chainId", "uint256"),
2210                   ("verifyingContract", "address"), ("salt", "bytes32")] {
2211        if dm.contains_key(n) { domain_fields.push((n.to_string(), t.to_string())); }
2212    }
2213    // Domain has no nested structs — a flat (empty type-map) hash.
2214    let mut domain_types: Eip712Types = Eip712Types::new();
2215    domain_types.insert("EIP712Domain".to_string(), domain_fields);
2216    let domain_sep = eip712_hash_struct("EIP712Domain", domain, &domain_types);
2217
2218    // Collect all user-defined types (name → fields), excluding EIP712Domain.
2219    let mut type_map: Eip712Types = Eip712Types::new();
2220    if let Value::Dict(m) = types {
2221        for (name, def) in m.iter() {
2222            if name == "EIP712Domain" { continue; }
2223            if let Value::Arr(arr) = def {
2224                let fields: Vec<(String, String)> = arr.iter().filter_map(|it| match it {
2225                    Value::Dict(fm) => Some((
2226                        fm.get("name")?.as_str()?.to_string(),
2227                        fm.get("type")?.as_str()?.to_string(),
2228                    )),
2229                    _ => None,
2230                }).collect();
2231                type_map.insert(name.clone(), fields);
2232            }
2233        }
2234    }
2235    if type_map.is_empty() { return Vec::new(); }
2236    // Primary type = the one not referenced as a field type by any other type
2237    // (the top-level struct). Falls back to the first key.
2238    let referenced: std::collections::HashSet<String> = type_map.values()
2239        .flat_map(|fs| fs.iter().map(|(_, t)| eip712_base_type(t).to_string()))
2240        .collect();
2241    let primary = type_map.keys().find(|k| !referenced.contains(*k)).cloned()
2242        .unwrap_or_else(|| type_map.keys().next().cloned().unwrap_or_default());
2243    let struct_hash = eip712_hash_struct(&primary, message, &type_map);
2244    let mut out = vec![0x19u8, 0x01u8];
2245    out.extend_from_slice(&domain_sep);
2246    out.extend_from_slice(&struct_hash);
2247    out
2248}
2249
2250/// EIP-712 `hashStruct(typeName, data)`: keccak(typeHash ‖ encoded-fields),
2251/// where a field whose type is itself a struct in `types` is hashed recursively.
2252fn eip712_hash_struct(type_name: &str, data: &Value, types: &Eip712Types) -> Vec<u8> {
2253    let type_str = eip712_encode_type(type_name, types);
2254    let mut enc = hash_raw(type_str.as_bytes(), "keccak"); // typeHash (32 bytes)
2255    let dm = match data { Value::Dict(m) => Some(m), _ => None };
2256    let fields = types.get(type_name).cloned().unwrap_or_default();
2257    for (name, ty) in &fields {
2258        let v = dm.and_then(|m| m.get(name)).cloned().unwrap_or(Value::Null);
2259        let base = eip712_base_type(ty);
2260        if types.contains_key(base) {
2261            // Nested struct field — recurse.
2262            enc.extend_from_slice(&eip712_hash_struct(base, &v, types));
2263        } else {
2264            enc.extend_from_slice(&eip712_encode_value(ty, &v));
2265        }
2266    }
2267    hash_raw(&enc, "keccak")
2268}
2269
2270/// Encodes an integer into a 32-byte EIP-712 / ABI word for a `uintN`/`intN`
2271/// type, validating the declared bit width. Fails closed (panics) on a negative
2272/// value in an unsigned type, or any value that overflows the declared width,
2273/// instead of silently truncating to 32 bytes or routing a negative through the
2274/// unsigned branch (review #15). Valid, in-range values encode exactly as
2275/// before (big-endian right-aligned for uint; two's-complement sign-extended
2276/// for int), so signing of well-formed payloads is unchanged.
2277pub(crate) fn eip712_int_word(ty: &str, n: &num_bigint::BigInt) -> [u8; 32] {
2278    use num_bigint::{BigInt, Sign};
2279    let signed = ty.starts_with("int");
2280    let digits = ty.trim_start_matches(if signed { "int" } else { "uint" });
2281    let mut width: usize = if digits.is_empty() { 256 } else { digits.parse().unwrap_or(256) };
2282    if !((8..=256).contains(&width) && width % 8 == 0) { width = 256; }
2283    let mut out = [0u8; 32];
2284    if !signed {
2285        if n.sign() == Sign::Minus {
2286            panic!("eip712/abi: negative value {n} supplied for unsigned type {ty}");
2287        }
2288        let max = (BigInt::from(1) << width) - 1;
2289        if n > &max {
2290            panic!("eip712/abi: value {n} overflows {ty} (max {max})");
2291        }
2292        let (_, be) = n.to_bytes_be();
2293        let take = be.len().min(32);
2294        out[32 - take..].copy_from_slice(&be[be.len() - take..]);
2295    } else {
2296        let min = -(BigInt::from(1) << (width - 1));
2297        let max = (BigInt::from(1) << (width - 1)) - 1;
2298        if n < &min || n > &max {
2299            panic!("eip712/abi: value {n} out of range for {ty} ([{min}, {max}])");
2300        }
2301        if n.sign() == Sign::Minus { out = [0xff; 32]; }
2302        let be = n.to_signed_bytes_be();
2303        let take = be.len().min(32);
2304        out[32 - take..].copy_from_slice(&be[be.len() - take..]);
2305    }
2306    out
2307}
2308
2309fn eip712_encode_value(ty: &str, v: &Value) -> [u8; 32] {
2310    let mut out = [0u8; 32];
2311    if ty == "string" || ty == "bytes" {
2312        out.copy_from_slice(&hash_raw(&value_to_bytes(v), "keccak"));
2313    } else if ty.starts_with("bytes") {
2314        // bytesN — left-aligned.
2315        let b = eip712_bytes(v);
2316        let n = b.len().min(32);
2317        out[..n].copy_from_slice(&b[..n]);
2318    } else if ty == "address" {
2319        // 20-byte address, right-aligned (left-padded with zeros).
2320        let b = eip712_bytes(v);
2321        let take = b.len().min(20);
2322        out[32 - take..].copy_from_slice(&b[b.len() - take..]);
2323    } else if ty == "bool" {
2324        if matches!(v, Value::Bool(true)) { out[31] = 1; }
2325    } else if ty.starts_with("uint") || ty.starts_with("int") {
2326        // uint256 (e.g. polymarket tokenId) exceeds u128 — use BigInt. Signed
2327        // intN uses two's-complement, sign-extended to 32 bytes.
2328        use num_bigint::BigInt;
2329        let n: BigInt = match v {
2330            Value::Int(i)   => BigInt::from(*i),
2331            Value::Float(f) => BigInt::from(*f as i64),
2332            Value::Str(s)   => {
2333                let t = s.trim();
2334                if let Some(h) = t.strip_prefix("0x") {
2335                    BigInt::parse_bytes(h.as_bytes(), 16).unwrap_or_default()
2336                } else {
2337                    BigInt::parse_bytes(t.as_bytes(), 10).unwrap_or_default()
2338                }
2339            }
2340            _ => BigInt::from(0),
2341        };
2342        out = eip712_int_word(ty, &n);
2343    }
2344    out
2345}
2346
2347/// Decode an EIP-712 byte value: a `0x`-hex string or a byte-array Value.
2348fn eip712_bytes(v: &Value) -> Vec<u8> {
2349    match v {
2350        Value::Str(s) => {
2351            let h = s.strip_prefix("0x").unwrap_or(s);
2352            hex::decode(h).unwrap_or_else(|_| s.as_bytes().to_vec())
2353        }
2354        _ => value_to_bytes(v),
2355    }
2356}
2357
2358pub(crate) fn value_to_bytes(v: &Value) -> Vec<u8> {
2359    match v {
2360        Value::Str(s) => s.as_bytes().to_vec(),
2361        Value::Arr(a) => a.iter().filter_map(|x| match x {
2362            Value::Int(n) => Some(*n as u8),
2363            _ => None,
2364        }).collect(),
2365        _ => Vec::new(),
2366    }
2367}
2368
2369pub(crate) fn url_pct(s: &str) -> String {
2370    s.bytes().map(|b| match b {
2371        b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
2372        _ => format!("%{b:02X}"),
2373    }).collect()
2374}
2375
2376/// Pins the `mock_response` contract that `request_typed` implements: the canned
2377/// payload is returned by `fetch_typed` only AFTER the request has been built and
2378/// signed, so `last_request_url` / `_headers` / `_body` still describe the real
2379/// request a static *response* fixture would have sent; and the payload stays set
2380/// until the caller replaces or clears it, so one fixture can serve the several
2381/// `fetch_typed` calls a single paginating `fetchX` issues.
2382
2383/// Pins `method_name_to_snake_case` — the transform that decides whether a
2384/// paginated `this[method](...)` re-entry lands on a `call_dynamic` arm — against
2385/// the two implementations it must agree with: the transpiler's `toSnakeCase`
2386/// (`build/rustTranspiler.ts`, which names the arms) and `Exchange::to_snake_case`
2387/// (which names the implicit-API entries the `_` arm falls through to).
2388/// Requested in review on #30385.
2389#[cfg(test)]
2390mod method_name_snake_case_tests {
2391    use super::{method_name_to_snake_case, Exchange};
2392    use crate::Value;
2393
2394    fn snake(name: &str) -> String {
2395        method_name_to_snake_case(&Value::Str(name.to_string().into()))
2396    }
2397
2398    // The four names the review called out, plus the digit/acronym shapes that
2399    // are the only places the three transforms could plausibly diverge.
2400    #[test]
2401    fn matches_the_transpiler_dispatch_arm_names() {
2402        // unified methods re-entered by fetchPaginatedCall* — these must hit an arm
2403        assert_eq!(snake("fetchTransfers"), "fetch_transfers");
2404        assert_eq!(snake("fetchOHLCV"), "fetch_ohlcv");                 // trailing acronym
2405        assert_eq!(snake("fetchOpenOrdersWs"), "fetch_open_orders_ws");
2406        assert_eq!(snake("fetchL2OrderBook"), "fetch_l2_order_book");   // letter+digit token
2407        assert_eq!(snake("getLeverageTiersPaginated"), "get_leverage_tiers_paginated");
2408        // implicit endpoints re-entered by fetchWebEndpoint — these must hit the
2409        // `_` arm's implicit_api lookup, which is keyed by to_snake_case
2410        assert_eq!(snake("publicGetTicker24hr"), "public_get_ticker24hr"); // NO `_` before a digit
2411        assert_eq!(snake("webExchangeGetV3Assets"), "web_exchange_get_v3_assets");
2412        assert_eq!(snake("webApiGetAjaxCoinCoinInfo"), "web_api_get_ajax_coin_coin_info");
2413        // acronym runs: `[A-Z]+[A-Z][a-z]` splits before the last capital only
2414        assert_eq!(snake("parseHTTPResponse"), "parse_http_response");
2415        assert_eq!(snake("fetchOHLCVWs"), "fetch_ohlcv_ws");
2416        // already-snake and single-token names are pass-through
2417        assert_eq!(snake("fetch"), "fetch");
2418        assert_eq!(snake("fetch_transfers"), "fetch_transfers");
2419    }
2420
2421    // `method_name_to_snake_case` and `Exchange::to_snake_case` must produce the
2422    // SAME key, or a dynamic name would snake to something the implicit-api map
2423    // does not hold. Differential over the shapes above; the full 11k-name sweep
2424    // over every ts/src method + abstract endpoint also reports zero divergence.
2425    #[test]
2426    fn agrees_with_exchange_to_snake_case() {
2427        for name in [
2428            "fetchTransfers", "fetchOHLCV", "fetchOpenOrdersWs", "publicGetTicker24hr",
2429            "fetchL2OrderBook", "webExchangeGetV3Assets", "webApiGetAjaxCoinCoinInfo",
2430            "parseHTTPResponse", "fetchOHLCVWs", "privatePostSPEIWithdrawal",
2431            "sapiV3GetAsset", "fapiPublicGetTicker24hr", "publicGet10PublicTickers",
2432            "fetch", "fetchPositionsRisk", "createOrderWs", "fetchMyLiquidations",
2433        ] {
2434            assert_eq!(
2435                snake(name),
2436                Exchange::to_snake_case(name),
2437                "method_name_to_snake_case and Exchange::to_snake_case diverge on {name}",
2438            );
2439        }
2440    }
2441
2442    // A non-string / empty dynamic name used to snake to "" and then resolve to
2443    // Value::Null — a silent empty page. It must be loud instead.
2444    #[test]
2445    #[should_panic(expected = "NotSupported")]
2446    fn non_string_method_name_is_loud() {
2447        let _ = method_name_to_snake_case(&Value::Int(7));
2448    }
2449
2450    #[test]
2451    #[should_panic(expected = "NotSupported")]
2452    fn empty_method_name_is_loud() {
2453        let _ = method_name_to_snake_case(&Value::Str(String::new().into()));
2454    }
2455}
2456
2457#[cfg(test)]
2458mod eip712_int_tests {
2459    use super::eip712_int_word;
2460    use num_bigint::BigInt;
2461
2462    #[test]
2463    fn uint8_max_ok_and_int8_bounds_ok() {
2464        assert_eq!(eip712_int_word("uint8", &BigInt::from(255))[31], 255);
2465        let _ = eip712_int_word("int8", &BigInt::from(127));
2466        let _ = eip712_int_word("int8", &BigInt::from(-128));
2467    }
2468
2469    #[test]
2470    fn i64_u64_boundaries_ok() {
2471        let _ = eip712_int_word("int64", &BigInt::from(i64::MAX));
2472        let _ = eip712_int_word("int64", &BigInt::from(i64::MIN));
2473        let _ = eip712_int_word("uint64", &BigInt::from(u64::MAX));
2474    }
2475
2476    // u64::MAX + 1 (2^64) must fit a uint256 exactly: 0x01 followed by 8 zero
2477    // bytes, right-aligned → byte index 23.
2478    #[test]
2479    fn u64_plus_one_preserved_in_uint256() {
2480        let n = BigInt::from(u64::MAX) + 1;
2481        assert_eq!(eip712_int_word("uint256", &n)[23], 1);
2482    }
2483
2484    #[test]
2485    fn negative_int_is_twos_complement() {
2486        assert_eq!(eip712_int_word("int256", &BigInt::from(-1)), [0xff; 32]);
2487    }
2488
2489    #[test]
2490    #[should_panic(expected = "overflows")]
2491    fn uint8_overflow_rejected() { let _ = eip712_int_word("uint8", &BigInt::from(256)); }
2492
2493    #[test]
2494    #[should_panic(expected = "negative")]
2495    fn uint_negative_rejected() { let _ = eip712_int_word("uint256", &BigInt::from(-1)); }
2496
2497    #[test]
2498    #[should_panic(expected = "out of range")]
2499    fn int8_overflow_rejected() { let _ = eip712_int_word("int8", &BigInt::from(128)); }
2500
2501    #[test]
2502    #[should_panic(expected = "overflows")]
2503    fn uint64_plus_one_rejected() {
2504        let _ = eip712_int_word("uint64", &(BigInt::from(u64::MAX) + 1));
2505    }
2506}
2507
2508#[cfg(test)]
2509mod throttle_tests {
2510    use super::Exchange;
2511    use crate::Value;
2512
2513    #[test]
2514    fn implicit_api_retains_endpoint_cost_config() {
2515        let mut by_limit = crate::value::HashMap::new();
2516        by_limit.insert("cost".to_string(), Value::Int(2));
2517        by_limit.insert("byLimit".to_string(), Value::List(vec![
2518            Value::List(vec![Value::Int(100), Value::Int(5)]),
2519        ]));
2520        let mut endpoints = crate::value::HashMap::new();
2521        endpoints.insert("ticker".to_string(), Value::Float(0.1));
2522        endpoints.insert("depth".to_string(), Value::Map(by_limit.clone()));
2523        let mut verbs = crate::value::HashMap::new();
2524        verbs.insert("get".to_string(), Value::Map(endpoints));
2525        let mut api = crate::value::HashMap::new();
2526        api.insert("public".to_string(), Value::Map(verbs));
2527        let mut exchange = Exchange::new(None);
2528        exchange.api = Value::Map(api);
2529        exchange.build_implicit_api();
2530        let ticker_config = &exchange.internals.implicit_api["public_get_ticker"].3;
2531        assert_eq!(
2532            crate::get_value(ticker_config, &Value::Str("cost".into())),
2533            Value::Float(0.1),
2534            "numeric endpoint costs must be normalized to a config object"
2535        );
2536        let depth_config = &exchange.internals.implicit_api["public_get_depth"].3;
2537        assert_eq!(depth_config, &Value::Map(by_limit), "object endpoint config must be retained");
2538    }
2539
2540    // The leaky-bucket limiter must space requests by ~rateLimit ms (real time).
2541    #[tokio::test]
2542    async fn spaces_requests_by_rate_limit() {
2543        let mut ex = Exchange::new(None);
2544        ex.enableRateLimit = Value::Bool(true);
2545        ex.rateLimit = Value::Int(15); // 15 ms per token
2546        let start = std::time::Instant::now();
2547        for _ in 0..5 { ex.throttle(&[]).await; }
2548        let elapsed = start.elapsed().as_millis();
2549        // 1st immediate, next 4 each wait ~15ms → ≥ ~45ms (generous lower bound).
2550        assert!(elapsed >= 45, "throttle did not space requests: {elapsed}ms");
2551    }
2552
2553    // Disabled rate limiting must not sleep at all.
2554    #[tokio::test]
2555    async fn disabled_is_noop() {
2556        let mut ex = Exchange::new(None);
2557        ex.enableRateLimit = Value::Bool(false);
2558        ex.rateLimit = Value::Int(1000);
2559        let start = std::time::Instant::now();
2560        for _ in 0..5 { ex.throttle(&[]).await; }
2561        assert!(start.elapsed().as_millis() < 50, "disabled throttle slept");
2562    }
2563}
2564
2565#[cfg(all(test, feature = "engine"))]
2566mod cow_alias_tests {
2567    use super::Exchange;
2568    use crate::Value;
2569    use crate::runtime::get_array_length;
2570
2571    // convertOHLCVToTradingView does `result[key].push(...)` on an extracted
2572    // local — a COW clone in Rust. Without the write-back the result columns
2573    // stay empty. Assert the data survives (review P0-C).
2574    #[test]
2575    fn convert_ohlcv_to_trading_view_preserves_pushes() {
2576        use crate::exchange_generated::ExchangeBase;
2577        let ex = super::BaseCore::new(Exchange::new(None));
2578        let row = Value::List(vec![
2579            Value::Int(1_700_000_000_000), Value::Int(1), Value::Int(2),
2580            Value::Int(0), Value::Int(1), Value::Int(10),
2581        ]);
2582        let ohlcvs = Value::List(vec![row.clone(), row]);
2583        let r = ex.convert_ohlcv_to_trading_view(ohlcvs, &[]);
2584        for key in ["t", "o", "h", "l", "c", "v"] {
2585            let col = crate::get_value(&r, &Value::Str(key.to_string().into()));
2586            assert_eq!(get_array_length(&col), Value::Int(2),
2587                "result['{key}'] lost its pushes — COW write-back failed");
2588        }
2589    }
2590}
2591
2592#[cfg(test)]
2593mod http_error_tests {
2594    use super::{BaseCore, DerivedExchange, Exchange, ExchangeRuntime};
2595    use crate::Value;
2596    use futures::FutureExt;
2597    use std::io::{Read, Write};
2598
2599    // Answers one request on a local port with the given status line and body.
2600    fn serve_once(status_line: &'static str, body: &'static str) -> String {
2601        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2602        let url = format!("http://{}/", listener.local_addr().unwrap());
2603        std::thread::spawn(move || {
2604            let (mut stream, _) = listener.accept().unwrap();
2605            let mut request = [0u8; 4096];
2606            let _ = stream.read(&mut request);
2607            let response = format!(
2608                "HTTP/1.1 {status_line}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
2609                body.len(),
2610            );
2611            stream.write_all(response.as_bytes()).unwrap();
2612        });
2613        url
2614    }
2615
2616    // A venue that reports failures inside a 200 body, the way okx does.
2617    struct EnvelopeCore {
2618        exchange: Exchange,
2619    }
2620    impl std::ops::Deref for EnvelopeCore {
2621        type Target = Exchange;
2622        fn deref(&self) -> &Exchange { &self.exchange }
2623    }
2624    impl std::ops::DerefMut for EnvelopeCore {
2625        fn deref_mut(&mut self) -> &mut Exchange { &mut self.exchange }
2626    }
2627    impl DerivedExchange for EnvelopeCore {
2628        fn handle_errors(&self, _code: Value, _reason: Value, _url: Value, _method: Value, _headers: Value, _body: Value, response: Value, _request_headers: Value, _request_body: Value) -> Value {
2629            let code = crate::get_value(&response, &Value::Str("code".into()));
2630            if !matches!(code, Value::Null) && code != Value::Str("0".into()) {
2631                panic!("{}", crate::exchange_errors::create_error("InsufficientFunds", "code 51008"));
2632            }
2633            Value::Null
2634        }
2635    }
2636    impl crate::exchange_generated::ExchangeBase for EnvelopeCore {
2637        fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<Value>)
2638            -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + 'a>>
2639        {
2640            Box::pin(async move { self.call_dynamic_base(method, args).await })
2641        }
2642    }
2643
2644    async fn fetch_error<C: ExchangeRuntime + Send>(core: &mut C, url: String) -> String {
2645        let outcome = std::panic::AssertUnwindSafe(core.fetch(Value::Str(url.into()), &[])).catch_unwind().await;
2646        match outcome {
2647            Ok(value) => format!("no error, returned {value:?}"),
2648            Err(payload) => payload.downcast_ref::<String>().cloned().unwrap_or_default(),
2649        }
2650    }
2651
2652    #[tokio::test]
2653    async fn an_error_in_a_2xx_body_reaches_handle_errors() {
2654        let url = serve_once("200 OK", r#"{"code":"51008","msg":"Insufficient balance"}"#);
2655        let mut core = EnvelopeCore { exchange: Exchange::new(None) };
2656        let error = fetch_error(&mut core, url).await;
2657        assert!(error.contains("InsufficientFunds"), "{error}");
2658    }
2659
2660    #[tokio::test]
2661    async fn a_status_in_http_exceptions_raises_its_class() {
2662        let url = serve_once("401 Unauthorized", "{}");
2663        let mut core = BaseCore::new(Exchange::new(None));
2664        let error = fetch_error(&mut core, url).await;
2665        assert!(error.contains("AuthenticationError"), "{error}");
2666    }
2667
2668    #[tokio::test]
2669    async fn a_status_outside_http_exceptions_still_fails() {
2670        let url = serve_once("402 Payment Required", "{}");
2671        let mut core = BaseCore::new(Exchange::new(None));
2672        let error = fetch_error(&mut core, url).await;
2673        assert!(error.contains("ExchangeError"), "{error}");
2674    }
2675}