Skip to main content

ccxt_base/
exchange.rs

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