Skip to main content

ccxt_common/
exchange.rs

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