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