Skip to main content

ccxt_base/
exchange_stubs.rs

1// Hand-written methods that are ABOVE the
2// `METHODS BELOW THIS LINE ARE TRANSPILED FROM TYPESCRIPT` marker in
3// `ts/src/base/Exchange.ts`. These are TS class-field aliases that bind
4// imported free functions (`safeValue = safeValue;` etc.) — they aren't
5// transpiled, so we implement them by hand here.
6//
7// Signature convention to match the transpiler's call shape:
8//
9//   pub fn name(&self, arg1: Value, arg2: Value, optional_args: &[Value]) -> Value
10//
11// The call-site post-processor in `build/rustTranspiler.ts` wraps trailing
12// args (defaults) into the `&[Value]` slice so `self.safe_value(obj, key)`
13// becomes `self.safe_value(obj, key, &[])` and `self.safe_value(obj, key, d)`
14// becomes `self.safe_value(obj, key, &[d])`.
15
16#![allow(non_snake_case, dead_code, unused_variables)]
17
18use crate::exchange::Exchange;
19use crate::runtime::stringify_param;
20use crate::{ExchangeError, Value};
21use indexmap::IndexMap as HashMap;
22use std::sync::Arc;
23
24/// Coerces `&Exchange` to `&mut Exchange`. The lint that warns about
25/// this is suppressed locally — see the safety note on the call site.
26#[allow(clippy::mut_from_ref, invalid_reference_casting)]
27unsafe fn coerce_to_mut_unsafe(e: &Exchange) -> &mut Exchange {
28    let ptr = e as *const Exchange as *mut Exchange;
29    &mut *ptr
30}
31
32/// Non-cryptographic 64-bit PRNG (splitmix64) seeded from a global
33/// counter mixed with the high-resolution clock. Good enough for the
34/// `uuid*` helpers — uniqueness across calls, not security.
35fn random_u64() -> u64 {
36    use std::sync::atomic::{AtomicU64, Ordering};
37    static COUNTER: AtomicU64 = AtomicU64::new(0);
38    let now = std::time::SystemTime::now()
39        .duration_since(std::time::UNIX_EPOCH)
40        .map(|d| d.as_nanos() as u64)
41        .unwrap_or(0);
42    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
43    let mut z = now ^ n.wrapping_mul(0x9E37_79B9_7F4A_7C15);
44    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
45    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
46    z ^ (z >> 31)
47}
48
49/// Returns `n` random lowercase hex characters.
50fn random_hex(n: usize) -> String {
51    let mut s = String::with_capacity(n);
52    while s.len() < n {
53        s.push_str(&format!("{:016x}", random_u64()));
54    }
55    s.truncate(n);
56    s
57}
58
59/// Wraps a byte slice into the port's binary representation —
60/// a `Value::Array` of `Value::Int` byte values.
61pub(crate) fn bytes_to_value(bytes: &[u8]) -> Value {
62    Value::Array(bytes.iter().map(|b| Value::Int(*b as i64)).collect())
63}
64
65/// True when `v` is a `Value::Array` whose elements are all integer
66/// byte values (0..=255) — the port's stand-in for a binary buffer.
67fn is_byte_array(v: &Value) -> bool {
68    match v {
69        Value::Arr(a) => a
70            .iter()
71            .all(|x| matches!(x, Value::Int(n) if (0..=255).contains(n))),
72        _ => false,
73    }
74}
75
76/// Recursive helper for `urlencodeNested` — flattens nested maps and
77/// arrays into bracketed keys (`b[c]`, `d[0]`), encoding only values.
78fn urlencode_nested_walk(prefix: &str, v: &Value, out: &mut Vec<String>) {
79    match v {
80        Value::Dict(m) => {
81            for (k, val) in m.iter() {
82                urlencode_nested_walk(&format!("{prefix}[{k}]"), val, out);
83            }
84        }
85        Value::Arr(a) => {
86            for (i, val) in a.iter().enumerate() {
87                urlencode_nested_walk(&format!("{prefix}[{i}]"), val, out);
88            }
89        }
90        scalar => {
91            out.push(format!(
92                "{}={}",
93                prefix,
94                crate::exchange::url_pct(&stringify_param(scalar))
95            ));
96        }
97    }
98}
99
100/// f64 → plain decimal string (Rust's `{}` never uses scientific
101/// notation for f64, matching TS `numberToString`).
102fn dtp_num_to_string(x: f64) -> String {
103    format!("{x}")
104}
105
106/// Free-function form of `precisionFromString` (returns i64).
107fn precision_from_string_i64(s: &str) -> i64 {
108    if let Some(idx) = s.find(['e', 'E']) {
109        let exp: i64 = s[idx + 1..].parse().unwrap_or(0);
110        return -exp;
111    }
112    let trimmed = s.trim_end_matches('0');
113    match trimmed.split_once('.') {
114        Some((_, frac)) => frac.len() as i64,
115        None => 0,
116    }
117}
118
119/// Port of `truncate_to_string` from `functions/number.ts`.
120fn truncate_to_string(num: &str, precision: i64) -> String {
121    if precision > 0 {
122        if let Some(dot) = num.find('.') {
123            let frac = &num[dot + 1..];
124            if frac.len() as i64 > precision {
125                return format!("{}.{}", &num[..dot], &frac[..precision as usize]);
126            }
127        }
128        return num.to_string();
129    }
130    let int_part = num.split('.').next().unwrap_or("0");
131    int_part
132        .parse::<i64>()
133        .map(|n| n.to_string())
134        .unwrap_or_else(|_| "0".to_string())
135}
136
137/// Faithful port of `_decimalToPrecision` from `functions/number.ts`.
138fn decimal_to_precision_impl(
139    x: &str,
140    rounding_mode: i64,
141    num_precision_digits: f64,
142    counting_mode: i64,
143    padding_mode: i64,
144) -> String {
145    use crate::runtime::{
146        DECIMAL_PLACES, NO_PADDING, ROUND, SIGNIFICANT_DIGITS, TICK_SIZE, TRUNCATE,
147    };
148    const ZERO: i64 = 48;
149    const ONE: i64 = 49;
150    const FIVE: i64 = 53;
151    const NINE: i64 = 57;
152
153    // ── negative precision ───────────────────────────────────────────
154    if num_precision_digits < 0.0 {
155        let to_nearest = 10f64.powf(-num_precision_digits);
156        let xnum: f64 = x.parse().unwrap_or(0.0);
157        if rounding_mode == ROUND {
158            let inner = decimal_to_precision_impl(
159                &dtp_num_to_string(xnum / to_nearest),
160                rounding_mode,
161                0.0,
162                counting_mode,
163                padding_mode,
164            );
165            let inner_num: f64 = inner.parse().unwrap_or(0.0);
166            return dtp_num_to_string(to_nearest * inner_num);
167        }
168        if rounding_mode == TRUNCATE {
169            return dtp_num_to_string(xnum - (xnum % to_nearest));
170        }
171    }
172
173    // ── tick size ────────────────────────────────────────────────────
174    if counting_mode == TICK_SIZE {
175        let precision_digits_string = decimal_to_precision_impl(
176            &dtp_num_to_string(num_precision_digits),
177            ROUND,
178            22.0,
179            DECIMAL_PLACES,
180            NO_PADDING,
181        );
182        let new_npd = precision_from_string_i64(&precision_digits_string);
183        if rounding_mode == TRUNCATE {
184            let truncated_x = truncate_to_string(x, new_npd.max(0));
185            let x_num: f64 = truncated_x.parse().unwrap_or(0.0);
186            let scale = 10f64.powi(new_npd as i32);
187            let x_scaled = (x_num * scale).round();
188            let tick_scaled = (num_precision_digits * scale).round();
189            let ticks = (x_scaled / tick_scaled).trunc();
190            let x_new = (ticks * tick_scaled) / scale;
191            if padding_mode == NO_PADDING {
192                let fixed = format!("{:.*}", new_npd.max(0) as usize, x_new);
193                let renum: f64 = fixed.parse().unwrap_or(0.0);
194                return dtp_num_to_string(renum);
195            }
196            return decimal_to_precision_impl(
197                &dtp_num_to_string(x_new),
198                ROUND,
199                new_npd as f64,
200                DECIMAL_PLACES,
201                padding_mode,
202            );
203        }
204        let mut x_num: f64 = x.parse().unwrap_or(0.0);
205        let mut missing = x_num % num_precision_digits;
206        missing = decimal_to_precision_impl(
207            &dtp_num_to_string(missing),
208            ROUND,
209            8.0,
210            DECIMAL_PLACES,
211            NO_PADDING,
212        )
213        .parse()
214        .unwrap_or(0.0);
215        let fp_error = decimal_to_precision_impl(
216            &dtp_num_to_string(missing / num_precision_digits),
217            ROUND,
218            new_npd.max(8) as f64,
219            DECIMAL_PLACES,
220            NO_PADDING,
221        );
222        if precision_from_string_i64(&fp_error) != 0 {
223            if x_num > 0.0 {
224                if missing >= num_precision_digits / 2.0 {
225                    x_num = x_num - missing + num_precision_digits;
226                } else {
227                    x_num -= missing;
228                }
229            } else if missing >= num_precision_digits / 2.0 {
230                x_num -= missing;
231            } else {
232                x_num = x_num - missing - num_precision_digits;
233            }
234        }
235        return decimal_to_precision_impl(
236            &dtp_num_to_string(x_num),
237            ROUND,
238            new_npd as f64,
239            DECIMAL_PLACES,
240            padding_mode,
241        );
242    }
243
244    // ── main char-buffer path ────────────────────────────────────────
245    let npd = num_precision_digits as i64;
246    let bytes: Vec<u8> = x.as_bytes().to_vec();
247    let str_end = bytes.len() as i64;
248    if str_end == 0 {
249        return String::new();
250    }
251    let is_negative = bytes[0] == b'-';
252    let str_start: i64 = if is_negative { 1 } else { 0 };
253    let mut str_dot = str_end;
254    for k in 0..str_end {
255        if bytes[k as usize] == b'.' {
256            str_dot = k;
257            break;
258        }
259    }
260    let has_dot = str_dot < str_end;
261    let chars_len = ((str_end - str_start) + if has_dot { 0 } else { 1 }) as usize;
262    let mut chars = vec![ZERO as u8; chars_len];
263
264    let mut after_dot = chars_len as i64;
265    let mut digits_start: i64 = -1;
266    let mut digits_end: i64;
267    {
268        let mut i: i64 = 1;
269        let mut j: i64 = str_start;
270        while j < str_end {
271            let c = bytes[j as usize];
272            if c == b'.' {
273                after_dot = i;
274                i -= 1;
275            } else if !c.is_ascii_digit() {
276                return x.to_string();
277            } else {
278                if (i as usize) < chars.len() {
279                    chars[i as usize] = c;
280                }
281                if c != b'0' && digits_start < 0 {
282                    digits_start = i;
283                }
284            }
285            j += 1;
286            i += 1;
287        }
288    }
289    if digits_start < 0 {
290        digits_start = 1;
291    }
292
293    let mut precision_start = if counting_mode == DECIMAL_PLACES {
294        after_dot
295    } else {
296        digits_start
297    };
298
299    digits_end = -1;
300    let mut all_zeros = true;
301    let mut sign_needed = is_negative;
302    {
303        let mut memo: i64 = 0;
304        let mut i = chars.len() as i64 - 1;
305        while i >= 0 {
306            let mut c = chars[i as usize] as i64;
307            if i != 0 {
308                c += memo;
309                if i >= precision_start + npd {
310                    let ceil =
311                        (rounding_mode == ROUND) && (c >= FIVE) && !((c == FIVE) && memo != 0);
312                    c = if ceil { NINE + 1 } else { ZERO };
313                }
314                if c > NINE {
315                    c = ZERO;
316                    memo = 1;
317                } else {
318                    memo = 0;
319                }
320            } else if memo != 0 {
321                c = ONE;
322            }
323            chars[i as usize] = c as u8;
324            if c != ZERO {
325                all_zeros = false;
326                digits_start = i;
327                digits_end = if digits_end < 0 { i + 1 } else { digits_end };
328            }
329            i -= 1;
330        }
331    }
332
333    if counting_mode == SIGNIFICANT_DIGITS {
334        precision_start = digits_start;
335    }
336    let precision_end = precision_start + npd;
337    if all_zeros {
338        sign_needed = false;
339    }
340
341    let read_start = if digits_start >= after_dot || all_zeros {
342        after_dot - 1
343    } else {
344        digits_start
345    };
346    let read_end = if digits_end < after_dot {
347        after_dot
348    } else {
349        digits_end
350    };
351
352    let n_sign: i64 = if sign_needed { 1 } else { 0 };
353    let n_before_dot = n_sign + (after_dot - read_start);
354    let n_after_dot = (read_end - after_dot).max(0);
355    let actual_length = read_end - read_start;
356    let desired_length = if padding_mode == NO_PADDING {
357        actual_length
358    } else {
359        precision_end - read_start
360    };
361    let pad = (desired_length - actual_length).max(0);
362    let pad_start = n_before_dot + 1 + n_after_dot;
363    let pad_end = pad_start + pad;
364    let is_integer = (n_after_dot + pad) == 0;
365
366    let out_len =
367        (n_before_dot + if is_integer { 0 } else { 1 } + n_after_dot + pad).max(0) as usize;
368    let mut out = vec![ZERO as u8; out_len];
369    let get_char = |idx: i64| -> u8 {
370        if idx >= 0 && (idx as usize) < chars.len() {
371            chars[idx as usize]
372        } else {
373            ZERO as u8
374        }
375    };
376    if sign_needed && !out.is_empty() {
377        out[0] = b'-';
378    }
379    {
380        let mut i = n_sign;
381        let mut j = read_start;
382        while i < n_before_dot {
383            if (i as usize) < out.len() {
384                out[i as usize] = get_char(j);
385            }
386            i += 1;
387            j += 1;
388        }
389    }
390    if !is_integer && (n_before_dot as usize) < out.len() {
391        out[n_before_dot as usize] = b'.';
392    }
393    {
394        let mut i = n_before_dot + 1;
395        let mut j = after_dot;
396        while i < pad_start {
397            if (i as usize) < out.len() {
398                out[i as usize] = get_char(j);
399            }
400            i += 1;
401            j += 1;
402        }
403    }
404    {
405        let mut i = pad_start;
406        while i < pad_end {
407            if (i as usize) < out.len() {
408                out[i as usize] = ZERO as u8;
409            }
410            i += 1;
411        }
412    }
413    String::from_utf8(out).unwrap_or_default()
414}
415
416/// Coerces a `Value` (or a missing one) to `f64` — used by `aggregate`.
417fn value_as_f64(v: Option<&Value>) -> f64 {
418    match v {
419        Some(Value::Int(n)) => *n as f64,
420        Some(Value::Float(f)) => *f,
421        Some(Value::Str(s)) => s.parse().unwrap_or(0.0),
422        _ => 0.0,
423    }
424}
425
426/// Generic ordering for `Value`s — numeric when both sides are
427/// numbers, lexical for strings, used by `sortBy`/`sortBy2`.
428fn value_cmp(a: &Value, b: &Value) -> std::cmp::Ordering {
429    use std::cmp::Ordering;
430    let num = |v: &Value| -> Option<f64> {
431        match v {
432            Value::Int(n) => Some(*n as f64),
433            Value::Float(f) => Some(*f),
434            _ => None,
435        }
436    };
437    match (num(a), num(b)) {
438        (Some(x), Some(y)) => x.partial_cmp(&y).unwrap_or(Ordering::Equal),
439        _ => stringify_param(a).cmp(&stringify_param(b)),
440    }
441}
442
443const BASE58_ALPHABET: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
444
445/// Base58 encode (Bitcoin alphabet).
446fn base58_encode(input: &[u8]) -> String {
447    if input.is_empty() {
448        return String::new();
449    }
450    let zeros = input.iter().take_while(|&&b| b == 0).count();
451    let mut digits: Vec<u8> = Vec::new();
452    for &byte in input {
453        let mut carry = byte as u32;
454        for d in digits.iter_mut() {
455            carry += (*d as u32) << 8;
456            *d = (carry % 58) as u8;
457            carry /= 58;
458        }
459        while carry > 0 {
460            digits.push((carry % 58) as u8);
461            carry /= 58;
462        }
463    }
464    let mut out = String::with_capacity(zeros + digits.len());
465    for _ in 0..zeros {
466        out.push('1');
467    }
468    for &d in digits.iter().rev() {
469        out.push(BASE58_ALPHABET[d as usize] as char);
470    }
471    out
472}
473
474/// Base58 decode (Bitcoin alphabet). Returns `None` on invalid input.
475fn base58_decode(input: &str) -> Option<Vec<u8>> {
476    if input.is_empty() {
477        return Some(Vec::new());
478    }
479    let zeros = input.bytes().take_while(|&b| b == b'1').count();
480    let mut bytes: Vec<u8> = Vec::new();
481    for ch in input.bytes() {
482        let mut carry = BASE58_ALPHABET.iter().position(|&a| a == ch)? as u32;
483        for b in bytes.iter_mut() {
484            carry += (*b as u32) * 58;
485            *b = (carry & 0xff) as u8;
486            carry >>= 8;
487        }
488        while carry > 0 {
489            bytes.push((carry & 0xff) as u8);
490            carry >>= 8;
491        }
492    }
493    let mut out = vec![0u8; zeros];
494    out.extend(bytes.iter().rev());
495    Some(out)
496}
497
498fn arg_default(opt: &[Value]) -> Value {
499    opt.get(0).cloned().unwrap_or(Value::Null)
500}
501
502
503fn key_str(key: &Value) -> String {
504    stringify_param(key)
505}
506
507// ── deferred coroutine (`spawn` / `delay`) queue ─────────────────────────────
508// JS `this.spawn(this.method, ...args)` backgrounds a coroutine. We can't truly
509// background it (it needs `&mut self`, held by the WS drive loop), so `spawn`
510// records the (method-name, args) and the drive loop (`ws_run`) drains and runs
511// them inline. The transpiler already lowers the method reference to a
512// dispatchable name string.
513/// A queued coroutine. `due_at` is `None` for `spawn` (run at the next drain)
514/// and `Some(instant)` for `delay` (run at the first drain at or after it —
515/// the drive loop bounds its socket read by the earliest deadline so a timer
516/// fires even on a silent stream).
517///
518/// The queue is thread-local, so a coroutine is only ever run by the drive loop
519/// that queued it. That holds because a `watch` drive loop and the venue code
520/// feeding it are one task, and tokio only migrates a task when another worker
521/// steals it — measured as not happening for this loop. A long-deadline item
522/// (a 20-minute `keepAliveListenKey`) now sits here across many iterations
523/// rather than being drained immediately, so if a future change contends the
524/// runtime hard enough to provoke stealing, this queue is the thing to move to
525/// a task-local.
526struct QueuedSpawn {
527    method: String,
528    args: Vec<Value>,
529    due_at: Option<std::time::Instant>,
530}
531
532thread_local! {
533    static SPAWN_QUEUE: std::cell::RefCell<Vec<QueuedSpawn>> =
534        std::cell::RefCell::new(Vec::new());
535}
536
537/// Take everything queued by `spawn`, plus every `delay` whose deadline has
538/// passed. Items still waiting on their deadline stay queued.
539pub(crate) fn drain_spawn_queue() -> Vec<(String, Vec<Value>)> {
540    let now = std::time::Instant::now();
541    SPAWN_QUEUE.with(|q| {
542        let mut q = q.borrow_mut();
543        let mut due = Vec::new();
544        let mut pending = Vec::new();
545        for item in std::mem::take(&mut *q) {
546            if item.due_at.map(|t| t <= now).unwrap_or(true) {
547                due.push((item.method, item.args));
548            } else {
549                pending.push(item);
550            }
551        }
552        *q = pending;
553        due
554    })
555}
556
557/// How long until the earliest not-yet-due `delay` fires, or `None` when
558/// nothing is waiting on a deadline. The WS drive loop uses this to bound its
559/// read, so a timer still fires on a stream that has gone quiet.
560pub(crate) fn next_spawn_due() -> Option<std::time::Duration> {
561    let now = std::time::Instant::now();
562    SPAWN_QUEUE.with(|q| {
563        q.borrow()
564            .iter()
565            .filter_map(|i| i.due_at)
566            .min()
567            .map(|t| t.saturating_duration_since(now))
568    })
569}
570
571/// Await a WS single-flight handle (what `client.future ()` /
572/// `client.reusable_future ()` return). Re-exported here because the generated
573/// venue files reach the base through `crate::exchange_stubs::…`, a path that
574/// resolves in both `ccxt-base` and `ccxt-pro`.
575pub async fn ws_await_flight(handle: &Value) -> Value {
576    crate::pro::ws_client::ws_await_flight(handle).await
577}
578
579/// Queue an async WS handler for the drive loop to run. The sync
580/// `dispatch_ws_handler` can't `.await` an async handler (e.g. htx's
581/// `handle_order_book_snapshot`), so it enqueues it here; `ws_run` drains and
582/// dispatches it asynchronously right after the current `handle_message`.
583pub fn enqueue_spawn(name: &str, args: Vec<Value>) {
584    SPAWN_QUEUE.with(|q| q.borrow_mut().push(QueuedSpawn {
585        method: name.to_string(),
586        args,
587        due_at: None,
588    }));
589}
590
591/// Queue a coroutine to run no earlier than `ms` from now — the scheduling half
592/// of `delay`. Used for the venues' periodic self-rescheduling loops
593/// (`keepAliveListenKey`, token refresh, …), which must fire on their own
594/// cadence rather than on the next inbound frame.
595pub fn enqueue_spawn_after(name: &str, args: Vec<Value>, ms: i64) {
596    let due_at = std::time::Instant::now()
597        + std::time::Duration::from_millis(ms.max(0) as u64);
598    SPAWN_QUEUE.with(|q| q.borrow_mut().push(QueuedSpawn {
599        method: name.to_string(),
600        args,
601        due_at: Some(due_at),
602    }));
603}
604
605impl Exchange {
606    // ── safe_* aliases (above-marker in TS) ─────────────────────────────────
607
608    /// Coerce a caught panic payload into the `[ClassName] message`
609    /// shape TS uses (see `Exchange.exceptionMessage`). Truncates to
610    /// 100k chars to match. Rust panics carry just a string in `Value`,
611    /// so we trust it as the formatted message and trim it. Used by
612    /// exchanges that re-throw with a contextual prefix in their
613    /// catch arms (grvt.transfer is the canonical case).
614    pub fn exception_message(&self, exc: Value, _optional_args: &[Value]) -> Value {
615        let s = match exc {
616            Value::Str(s) => s,
617            other => crate::runtime::stringify_param(&other),
618        };
619        let n = s.chars().count().min(100_000);
620        Value::Str(s.chars().take(n).collect())
621    }
622
623    /// Port of `Exchange.getCcxtVersion()`. The TS reads the static
624    /// `Exchange.ccxtVersion` (a class member the release process bumps); the
625    /// transpiler can't lower that `(Exchange as any).ccxtVersion` static access,
626    /// so `getCcxtVersion` is dropped from `exchange_generated.rs` and lives here
627    /// as a hand-written stub instead. Value mirrors `ts/src/base/Exchange.ts`'s
628    /// `static ccxtVersion` (== package.json "version"); only foxbit consumes it
629    /// (the `X-FB-CLIENT-VERSION` request header), and no static fixture asserts
630    /// the header, so a version bump can't break the suites.
631    pub fn get_ccxt_version(&self) -> Value {
632        Value::Str("4.5.71".to_string())
633    }
634
635    // ── Hot-path `safe_*_k` variants — take `key: &str` directly so the
636    // transpiler can skip wrapping every literal key in a `Value::Str`.
637    // Each `_k` saves two String allocations per call (the key Value +
638    // the key_str re-extraction). On a 500-trade fetchTrades, cumulative
639    // savings are several thousand allocations.
640
641    #[inline]
642    pub fn safe_value_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
643        let v = crate::value::get_value_k(&obj, key);
644        let missing = matches!(&v, Value::Null) || matches!(&v, Value::Str(s) if s.is_empty());
645        if missing {
646            arg_default(optional_args)
647        } else {
648            v
649        }
650    }
651
652    #[inline]
653    pub fn safe_string_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
654        let v = self.safe_value_k(obj, key, &[]);
655        match v {
656            Value::Str(_) => v,
657            Value::Int(n) => Value::Str(n.to_string()),
658            Value::Float(f) => Value::Str(f.to_string()),
659            // Booleans/lists/dicts are not strings or finite numbers → return
660            // the default, matching TS `safeString` (base/functions/type.ts).
661            _ => arg_default(optional_args),
662        }
663    }
664
665    #[inline]
666    pub fn safe_integer_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
667        let v = self.safe_value_k(obj, key, &[]);
668        match v {
669            Value::Int(_) => v,
670            Value::Float(f) => Value::Int(f as i64),
671            Value::Str(s) => match s.parse::<i64>() {
672                Ok(n) => Value::Int(n),
673                Err(_) => match s.parse::<f64>() {
674                    Ok(f) if f.is_finite() => Value::Int(f as i64),
675                    _ => arg_default(optional_args),
676                },
677            },
678            _ => arg_default(optional_args),
679        }
680    }
681
682    #[inline]
683    pub fn safe_float_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
684        let v = self.safe_value_k(obj, key, &[]);
685        match v {
686            Value::Float(_) => v,
687            Value::Int(n) => Value::Float(n as f64),
688            Value::Str(s) => match s.parse::<f64>() {
689                Ok(n) => Value::Float(n),
690                Err(_) => arg_default(optional_args),
691            },
692            _ => arg_default(optional_args),
693        }
694    }
695
696    #[inline]
697    pub fn safe_number_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
698        self.safe_float_k(obj, key, optional_args)
699    }
700
701    #[inline]
702    pub fn safe_bool_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
703        // Mirror CCXT `safeBool`: the value is returned ONLY when it is an
704        // actual boolean (`typeof value === 'boolean'`). A string like
705        // "true" or an integer is NOT a boolean, so it yields the default
706        // — coercing them (as a previous version did) diverges from every
707        // other language and broke e.g. zebpay `fetchCurrencies`, where
708        // `isDepositEnabled: "true"` (a string) must read as the default.
709        let v = self.safe_value_k(obj, key, &[]);
710        match v {
711            Value::Bool(_) => v,
712            _ => arg_default(optional_args),
713        }
714    }
715
716    #[inline]
717    pub fn safe_dict_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
718        let v = self.safe_value_k(obj, key, &[]);
719        if matches!(v, Value::Dict(_)) {
720            v
721        } else {
722            arg_default(optional_args)
723        }
724    }
725
726    #[inline]
727    pub fn safe_list_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
728        let v = self.safe_value_k(obj, key, &[]);
729        if matches!(v, Value::Arr(_)) {
730            v
731        } else {
732            arg_default(optional_args)
733        }
734    }
735
736    pub fn safe_value(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
737        // Match TS `prop` semantics: an empty string is treated as
738        // "missing" — same as null/undefined. Without this, exchanges
739        // that signal end-of-pagination with `cursor: ""` loop forever
740        // because `is_equal(&Value::Str(""), &Value::Null)` is false.
741        let v = crate::get_value(&obj, &Value::Str(key_str(&key)));
742        let missing = matches!(&v, Value::Null) || matches!(&v, Value::Str(s) if s.is_empty());
743        if missing {
744            arg_default(optional_args)
745        } else {
746            v
747        }
748    }
749
750    pub fn safe_value2(&self, obj: Value, k1: Value, k2: Value, optional_args: &[Value]) -> Value {
751        let v = self.safe_value(obj.clone(), k1, &[]);
752        if !v.is_null() {
753            return v;
754        }
755        let v = self.safe_value(obj, k2, &[]);
756        if !v.is_null() {
757            v
758        } else {
759            arg_default(optional_args)
760        }
761    }
762
763    pub fn safe_value_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
764        if let Value::Arr(ks) = keys {
765            for k in ks.iter().cloned() {
766                let v = self.safe_value(obj.clone(), k, &[]);
767                if !v.is_null() {
768                    return v;
769                }
770            }
771        }
772        arg_default(optional_args)
773    }
774
775    pub fn safe_string(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
776        let v = self.safe_value(obj, key, &[]);
777        match v {
778            Value::Str(_) => v,
779            Value::Int(n) => Value::Str(n.to_string()),
780            Value::Float(f) => Value::Str(f.to_string()),
781            // A boolean is NOT a string or finite number — TS `safeString`
782            // (base/functions/type.ts) returns the default for it, not "true"/
783            // "false". Same for lists/dicts (the `_` arm).
784            Value::Null => arg_default(optional_args),
785            _ => arg_default(optional_args),
786        }
787    }
788
789    pub fn safe_string2(&self, obj: Value, k1: Value, k2: Value, optional_args: &[Value]) -> Value {
790        let v = self.safe_string(obj.clone(), k1, &[]);
791        if !v.is_null() {
792            return v;
793        }
794        let v = self.safe_string(obj, k2, &[]);
795        if !v.is_null() {
796            v
797        } else {
798            arg_default(optional_args)
799        }
800    }
801
802    pub fn safe_string_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
803        if let Value::Arr(ks) = keys {
804            for k in ks.iter().cloned() {
805                let v = self.safe_string(obj.clone(), k, &[]);
806                if !v.is_null() {
807                    return v;
808                }
809            }
810        }
811        arg_default(optional_args)
812    }
813
814    // NB: case-transform the *found* value only, and return the default
815    // UNCHANGED — matching TS `safeStringLower/Upper` (type.ts), which lower/
816    // upper-cases `String(x)` when the key resolves and otherwise returns
817    // `$default` verbatim. Passing the default through `safe_string` first
818    // (and then casing the result) wrongly lower-cased mixed-case defaults
819    // such as hyperliquid's checksummed builder address.
820    pub fn safe_string_upper(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
821        let v = self.safe_string(obj, key, &[]);
822        if !v.is_null() {
823            if let Value::Str(s) = v {
824                return Value::Str(s.to_uppercase());
825            }
826            return v;
827        }
828        arg_default(optional_args)
829    }
830
831    pub fn safe_string_lower_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
832        if let Value::Arr(ks) = keys {
833            for k in ks.iter().cloned() {
834                let v = self.safe_string(obj.clone(), k, &[]);
835                if !v.is_null() {
836                    if let Value::Str(s) = v {
837                        return Value::Str(s.to_lowercase());
838                    }
839                    return v;
840                }
841            }
842        }
843        arg_default(optional_args)
844    }
845
846    pub fn safe_string_upper_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
847        if let Value::Arr(ks) = keys {
848            for k in ks.iter().cloned() {
849                let v = self.safe_string(obj.clone(), k, &[]);
850                if !v.is_null() {
851                    if let Value::Str(s) = v {
852                        return Value::Str(s.to_uppercase());
853                    }
854                    return v;
855                }
856            }
857        }
858        arg_default(optional_args)
859    }
860
861    pub fn safe_string_lower(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
862        let v = self.safe_string(obj, key, &[]);
863        if !v.is_null() {
864            if let Value::Str(s) = v {
865                return Value::Str(s.to_lowercase());
866            }
867            return v;
868        }
869        arg_default(optional_args)
870    }
871
872    pub fn safe_string_lower2(
873        &self,
874        obj: Value,
875        k1: Value,
876        k2: Value,
877        optional_args: &[Value],
878    ) -> Value {
879        let v = self.safe_string2(obj, k1, k2, &[]);
880        if !v.is_null() {
881            if let Value::Str(s) = v {
882                return Value::Str(s.to_lowercase());
883            }
884            return v;
885        }
886        arg_default(optional_args)
887    }
888
889    pub fn safe_string_upper2(
890        &self,
891        obj: Value,
892        k1: Value,
893        k2: Value,
894        optional_args: &[Value],
895    ) -> Value {
896        let v = self.safe_string2(obj, k1, k2, &[]);
897        if !v.is_null() {
898            if let Value::Str(s) = v {
899                return Value::Str(s.to_uppercase());
900            }
901            return v;
902        }
903        arg_default(optional_args)
904    }
905
906    /// `super.X(...)` from derived exchanges — routes back to the base
907    /// Exchange impl. These stubs return Value::Null; they exist so
908    /// transpiled `self.super_X()` calls type-check.
909    pub fn super_currency(&self, _code: Value) -> Value {
910        Value::Null
911    }
912    pub fn super_handle_errors(
913        &self,
914        _code: Value,
915        _reason: Value,
916        _url: Value,
917        _method: Value,
918        _headers: Value,
919        _body: Value,
920        _response: Value,
921        _request_headers: Value,
922        _request_body: Value,
923    ) -> Value {
924        Value::Null
925    }
926
927    // ── request bookkeeping (hand-written, above the transpile marker) ──
928    // These live above the `METHODS BELOW THIS LINE ...` marker in
929    // `ts/src/base/Exchange.ts` (plain assignments in most languages), so
930    // they are implemented by hand rather than transpiled. They mutate
931    // instance fields; the `&self` receiver matches the transpiler's call
932    // shape and we reborrow `&mut` via the same helper as `super_set_markets`.
933    pub fn set_last_rest_request_timestamp(&self) {
934        let me = unsafe { coerce_to_mut_unsafe(self) };
935        me.lastRestRequestTimestamp = self.milliseconds();
936    }
937
938    pub fn set_last_request(&self, request: Value) {
939        let me = unsafe { coerce_to_mut_unsafe(self) };
940        me.last_request_headers =
941            crate::runtime::get_value(&request, &Value::Str("headers".to_string()));
942        me.last_request_body = crate::runtime::get_value(&request, &Value::Str("body".to_string()));
943        me.last_request_url = crate::runtime::get_value(&request, &Value::Str("url".to_string()));
944    }
945
946    pub fn get_fetch_cache(&self) -> Value {
947        self.fetchHistoryCache.clone()
948    }
949
950    pub fn add_fetch_cache(&self, data: Value) {
951        let me = unsafe { coerce_to_mut_unsafe(self) };
952        if crate::runtime::is_less_than_or_equal(&me.fetchHistoryCacheSize, &Value::Int(0)) {
953            return;
954        }
955        while crate::runtime::is_greater_than_or_equal(
956            &crate::runtime::get_array_length(&me.fetchHistoryCache),
957            &me.fetchHistoryCacheSize,
958        ) {
959            crate::runtime::remove(&mut me.fetchHistoryCache, &Value::Int(0));
960        }
961        crate::runtime::append_to_array(&mut me.fetchHistoryCache, data);
962    }
963
964    // ── WS (pro) stubs ─────────────────────────────────────────────────────
965    // The transpiled pro/<id>.rs files reference `self.watch()`, `self.client()`,
966    // `self.spawn()` etc. from the WS Client infrastructure that hasn't been
967    // ported yet. These stubs make the WS-extends-REST inheritance compile —
968    // calls at runtime panic with a clear "WS not yet ported" error so we
969    // surface the gap loudly instead of silently no-op'ing.
970    //
971    // `watch()` / `watch_multiple()` are the WS drive loop and live in the
972    // `ExchangeRuntime` trait (generic `self`) so they can dispatch to the
973    // concrete Core's `handle_message` override — see exchange.rs.
974    //
975    // `client(url)` returns the client-handle `Value` (`Map{url, subscriptions,
976    // futures}`) the transpiled `handle_message` reads; the live connection is
977    // established lazily by `watch()`.
978    pub fn client(&mut self, args: &[Value]) -> Value {
979        match args.get(0) {
980            Some(Value::Str(url)) => crate::pro::ws_client::client_value(url),
981            _ => Value::Null,
982        }
983    }
984    // `spawn(fn, ...)` / `delay(ms, fn, ...)`: the transpiler lowers the JS
985    // function reference to `Value::Null` (it has no Rust callable to pass), so
986    // these can't invoke the coroutine and are necessarily no-ops. Background
987    // keep-alive/auth-refresh loops that rely on them are a known gap.
988    pub fn spawn(&self, args: &[Value]) -> Value {
989        // args = [ method_name, ...call_args ]; queue it for the drive loop.
990        if let Some(Value::Str(name)) = args.get(0) {
991            let call_args: Vec<Value> = args.get(1..).map(|s| s.to_vec()).unwrap_or_default();
992            enqueue_spawn(name, call_args);
993        }
994        Value::Null
995    }
996    pub async fn delay(&mut self, ms: Value, args: &[Value]) -> Value {
997        // `delay(ms, method, ...args)` schedules a coroutine after a warm-up
998        // delay (bitvavo's snapshot fetch, htx's resync retry) or on a long
999        // period (binance's `keepAliveListenKey`, every 20 min). We can't sleep
1000        // and then call it — that needs &mut self — so queue it with its
1001        // deadline; the WS drive loop bounds its socket read by the earliest
1002        // deadline and runs the coroutine when it comes due.
1003        if let Some(Value::Str(name)) = args.get(0) {
1004            let call_args: Vec<Value> = args.get(1..).map(|s| s.to_vec()).unwrap_or_default();
1005            enqueue_spawn_after(name, call_args, ms.as_f64().unwrap_or(0.0) as i64);
1006        }
1007        Value::Null
1008    }
1009    pub fn order_book(&self, args: &[Value]) -> Value {
1010        crate::pro::OrderBook::new(crate::runtime::get_arg(args, 0, Value::Null), crate::runtime::get_arg(args, 1, Value::Null))
1011    }
1012    pub fn indexed_order_book(&self, args: &[Value]) -> Value {
1013        crate::pro::IndexedOrderBook::new(crate::runtime::get_arg(args, 0, Value::Null), crate::runtime::get_arg(args, 1, Value::Null))
1014    }
1015    pub fn counted_order_book(&self, args: &[Value]) -> Value {
1016        crate::pro::CountedOrderBook::new(crate::runtime::get_arg(args, 0, Value::Null), crate::runtime::get_arg(args, 1, Value::Null))
1017    }
1018    pub fn safe_order_tracker(&self, _args: &[Value]) -> Value {
1019        Value::Null
1020    }
1021    pub async fn un_watch(&mut self, _topic: Value, _args: &[Value]) -> Value {
1022        Value::Null
1023    }
1024    pub fn send(&self, _payload: Value) -> Value {
1025        Value::Null
1026    }
1027    pub fn lock_id(&self, _args: &[Value]) -> Value {
1028        Value::Null
1029    }
1030    pub fn unlock_id(&self, _args: &[Value]) -> Value {
1031        Value::Null
1032    }
1033    pub fn extend_exchange_options(&self, _args: &[Value]) -> Value {
1034        Value::Null
1035    }
1036    pub fn on_error(&self, _args: &[Value]) -> Value {
1037        Value::Null
1038    }
1039    pub fn on_close(&self, _args: &[Value]) -> Value {
1040        Value::Null
1041    }
1042    pub fn on_pong(&self, _args: &[Value]) -> Value {
1043        Value::Null
1044    }
1045    /// CRC-32 checksum — used by a few WS order-book reconcilers
1046    /// (bitget, bitfinex, independentreserve). Stub returns 0; will be
1047    /// replaced with the real algorithm when those order books need it.
1048    pub fn crc32(&self, args: &[Value]) -> Value {
1049        let payload = args.get(0).cloned().unwrap_or(Value::Str(String::new()));
1050        let signed = args.get(1).cloned().unwrap_or(Value::Bool(false));
1051        crate::runtime::crc32(payload, signed)
1052    }
1053    /// `decode_proto_msg(message)` — exchange-specific protobuf decoder
1054    /// (mexc). `message` is the binary frame carried as a byte array; decode
1055    /// it into mexc's `PushDataV3ApiWrapper` shape (matching protobufjs
1056    /// `.toJSON()`) so the ported handlers consume it unchanged.
1057    pub fn decode_proto_msg(&self, args: &[Value]) -> Value {
1058        match args.get(0) {
1059            Some(v) if is_byte_array(v) => {
1060                let bytes = crate::exchange::value_to_bytes(v);
1061                crate::runtime::decode_mexc_push_data(&bytes)
1062            }
1063            Some(v) => v.clone(),
1064            None => Value::Null,
1065        }
1066    }
1067    /// `loadOrderBook` — WS helper used by some bookkeeping methods.
1068    /// Stubbed identically to the unwatch flow.
1069    pub async fn load_order_book(&mut self, _args: &[Value]) -> Value {
1070        Value::Null
1071    }
1072
1073    // ── hand-written base helpers ──────────────────────────────────────────
1074    // These live above the `METHODS BELOW THIS LINE ARE TRANSPILED` marker in
1075    // ts/src/base/Exchange.ts, so they are language-specific hand-written code
1076    // rather than transpiled into exchange_generated.rs.
1077
1078    /// `remove0xPrefix(hexData)` — strips a leading `0x`/`0X` if present.
1079    pub fn remove0x_prefix(&self, hex_data: Value) -> Value {
1080        match &hex_data {
1081            Value::Str(s) if s.len() >= 2 && (&s[0..2] == "0x" || &s[0..2] == "0X") => {
1082                Value::Str(s[2..].to_string())
1083            }
1084            _ => hex_data,
1085        }
1086    }
1087
1088    /// `checkRequiredDependencies()` — a no-op in Rust; all crypto deps are
1089    /// compiled in.
1090    pub fn check_required_dependencies(&self) -> Value {
1091        Value::Null
1092    }
1093
1094    /// `randNumber(size)` — a random integer with `size` decimal digits.
1095    pub fn rand_number(&self, size: Value) -> Value {
1096        use rand::Rng;
1097        let n = size.as_i64().unwrap_or(0).max(0) as usize;
1098        let mut rng = rand::thread_rng();
1099        let mut s = String::new();
1100        for _ in 0..n {
1101            s.push(char::from(b'0' + rng.gen_range(0..10u8)));
1102        }
1103        Value::Int(s.parse::<i64>().unwrap_or(0))
1104    }
1105
1106    /// `randomBytes(length)` — `length` random bytes as a hex string.
1107    pub fn random_bytes(&self, length: Value) -> Value {
1108        use rand::Rng;
1109        let n = length.as_i64().unwrap_or(0).max(0) as usize;
1110        let mut rng = rand::thread_rng();
1111        let bytes: Vec<u8> = (0..n).map(|_| rng.gen()).collect();
1112        Value::Str(hex::encode(bytes))
1113    }
1114
1115    /// `convertToBigInt(value)` — the Value-bag has no distinct bigint type,
1116    /// so coerce to a 64-bit integer.
1117    pub fn convert_to_big_int(&self, value: Value) -> Value {
1118        match &value {
1119            Value::Int(_) => value,
1120            Value::Float(f) => Value::Int(*f as i64),
1121            Value::Str(s) => {
1122                let t = s.trim();
1123                // A uint256 (e.g. polymarket tokenId) overflows i64; keep the
1124                // decimal/0x-hex string so downstream big-int consumers
1125                // (eth_abi_encode) encode the full value instead of truncating.
1126                match t.parse::<i64>() {
1127                    Ok(n) => Value::Int(n),
1128                    Err(_) => Value::Str(t.to_string()),
1129                }
1130            }
1131            _ => Value::Int(0),
1132        }
1133    }
1134
1135    /// `fixStringifiedJsonMembers(content)` — un-escapes a JSON string whose
1136    /// members are themselves stringified JSON (used by bingx).
1137    pub fn fix_stringified_json_members(&self, content: Value) -> Value {
1138        match &content {
1139            Value::Str(s) => Value::Str(
1140                s.replace('\\', "")
1141                    .replace("\"{", "{")
1142                    .replace("}\"", "}")
1143                    .replace("\"[", "[")
1144                    .replace("]\"", "]"),
1145            ),
1146            _ => content,
1147        }
1148    }
1149
1150    /// `binaryConcatArray(arrayOfChunks)` — concatenates hex-string chunks.
1151    pub fn binary_concat_array(&self, arr: Value) -> Value {
1152        let mut out = String::new();
1153        if let Value::Arr(items) = &arr {
1154            for it in items.iter() {
1155                if let Value::Str(s) = it {
1156                    out.push_str(s);
1157                }
1158            }
1159        }
1160        Value::Str(out)
1161    }
1162
1163    /// `uuid5(namespace, name)` — RFC-4122 v5 (SHA-1 based) UUID.
1164    pub fn uuid5(&self, namespace: Value, name: Value) -> Value {
1165        use sha1::{Digest, Sha1};
1166        let ns = namespace.as_str().unwrap_or("").replace('-', "");
1167        let mut data: Vec<u8> = Vec::new();
1168        let mut i = 0;
1169        while i + 1 < ns.len() {
1170            if let Ok(b) = u8::from_str_radix(&ns[i..i + 2], 16) {
1171                data.push(b);
1172            }
1173            i += 2;
1174        }
1175        data.extend_from_slice(name.as_str().unwrap_or("").as_bytes());
1176        let mut hasher = Sha1::new();
1177        hasher.update(&data);
1178        let mut hash = hasher.finalize().to_vec();
1179        hash[6] = (hash[6] & 0x0f) | 0x50;
1180        hash[8] = (hash[8] & 0x3f) | 0x80;
1181        let h = hex::encode(&hash[0..16]);
1182        Value::Str(format!(
1183            "{}-{}-{}-{}-{}",
1184            &h[0..8],
1185            &h[8..12],
1186            &h[12..16],
1187            &h[16..20],
1188            &h[20..32]
1189        ))
1190    }
1191
1192    /// `ethAbiEncode(types, values)` — Solidity `abi.encode` of a head-only
1193    /// (all-static) tuple: every element becomes one 32-byte word. Supports the
1194    /// static types the callers use (address, bytesN, uint*/int*, bool). Dynamic
1195    /// types (`bytes`, `string`, arrays) are not needed (polymarket ERC-7739) and
1196    /// return Null. Values arrive as: bytesN → binary `Value::Arr` (or 0x-hex
1197    /// string); uint/int → `Value::Int` or a decimal/0x-hex string (big uint256
1198    /// like tokenId exceed i64, so string form is preserved by convert_to_big_int);
1199    /// address → 0x-hex string. Result is a binary `Value::Arr` that `hash(...)`
1200    /// consumes via value_to_bytes.
1201    pub fn eth_abi_encode(&self, types: Value, values: Value) -> Value {
1202        use num_bigint::BigInt;
1203        let ts: Vec<Value> = match &types  { Value::Arr(a) => (**a).clone(), _ => return Value::Null };
1204        let vs: Vec<Value> = match &values { Value::Arr(a) => (**a).clone(), _ => return Value::Null };
1205        let to_bytes = |v: &Value| -> Vec<u8> {
1206            match v {
1207                Value::Arr(a) => a.iter().filter_map(|x| if let Value::Int(n) = x { Some(*n as u8) } else { None }).collect(),
1208                Value::Str(s) => hex::decode(s.trim_start_matches("0x")).unwrap_or_default(),
1209                _ => Vec::new(),
1210            }
1211        };
1212        let to_bigint = |v: &Value| -> BigInt {
1213            match v {
1214                Value::Int(n)   => BigInt::from(*n),
1215                Value::Float(f) => BigInt::from(*f as i64),
1216                Value::Str(s)   => {
1217                    let t = s.trim();
1218                    if let Some(h) = t.strip_prefix("0x") {
1219                        BigInt::parse_bytes(h.as_bytes(), 16).unwrap_or_default()
1220                    } else {
1221                        BigInt::parse_bytes(t.as_bytes(), 10).unwrap_or_default()
1222                    }
1223                }
1224                _ => BigInt::from(0),
1225            }
1226        };
1227        let mut out: Vec<u8> = Vec::new();
1228        for (t, v) in ts.iter().zip(vs.iter()) {
1229            let ty = match t { Value::Str(s) => s.as_str(), _ => return Value::Null };
1230            let mut word = [0u8; 32];
1231            if ty == "address" {
1232                let b = to_bytes(v);
1233                let n = b.len().min(20);
1234                word[32 - n..].copy_from_slice(&b[b.len() - n..]);
1235            } else if ty.starts_with("bytes") && ty != "bytes" {
1236                // fixed bytesN — left-aligned
1237                let b = to_bytes(v);
1238                let n = b.len().min(32);
1239                word[..n].copy_from_slice(&b[..n]);
1240            } else if ty.starts_with("uint") || ty.starts_with("int") {
1241                // uintN/intN — validate the declared bit width, reject
1242                // negative-for-unsigned / overflow, then encode (review #15).
1243                word = crate::exchange::eip712_int_word(ty, &to_bigint(v));
1244            } else if ty == "bool" {
1245                if matches!(v, Value::Bool(true)) { word[31] = 1; }
1246            } else {
1247                return Value::Null; // unsupported (dynamic) type
1248            }
1249            out.extend_from_slice(&word);
1250        }
1251        Value::Array(out.into_iter().map(|b| Value::Int(b as i64)).collect())
1252    }
1253
1254    /// `setProperty(this, key, value)` — dynamic field setter. The typed
1255    /// `Exchange` struct has no Value-shaped dynamic field store, so this
1256    /// is currently a no-op (the receiver arg is dropped by the transpiler).
1257    pub fn set_property(&self, _property: Value, _optional_args: &[Value]) -> Value {
1258        Value::Null
1259    }
1260
1261    // ── exchange-specific signing helpers (above-the-marker base methods) ──
1262    // These wrap heavy crypto (curve25519, StarkNet, dydx protobuf, lighter
1263    // zk-proofs) that has not yet been ported to Rust. The terminal
1264    // signature-producing methods fail loudly with NotSupported rather than
1265    // returning a null/empty signature — an unsigned request silently sent to an
1266    // exchange is worse than an explicit error (review #4). The static request
1267    // fixtures mark the affected private cases `disabledRS`, as Go/Java do.
1268
1269    /// Fail loudly for an unported crypto/signing primitive. Diverges (`-> !`),
1270    /// so it satisfies any `-> Value` stub body.
1271    fn crypto_not_supported(&self, what: &str) -> ! {
1272        let id = match &self.id { Value::Str(s) => s.clone(), _ => String::new() };
1273        panic!("{}", crate::exchange_errors::not_supported(Value::Str(
1274            format!("{id} {what}() signing is not implemented in the Rust port yet"),
1275        )));
1276    }
1277
1278    /// `axolotl(payload, hexKey, ed25519)` — curve25519 signing (waves).
1279    pub fn axolotl(&self, _payload: Value, _hex_key: Value, _ed25519: Value) -> Value {
1280        self.crypto_not_supported("axolotl")
1281    }
1282
1283    /// `retrieveStarkAccount(signature, accountClassHash, accountProxyClassHash)`.
1284    pub fn retrieve_stark_account(
1285        &self,
1286        _signature: Value,
1287        _class_hash: Value,
1288        _proxy_hash: Value,
1289    ) -> Value {
1290        Value::Null
1291    }
1292
1293    /// `starknetEncodeStructuredData(domain, messageTypes, messageData, address)`.
1294    pub fn starknet_encode_structured_data(
1295        &self,
1296        _domain: Value,
1297        _types: Value,
1298        _data: Value,
1299        _address: Value,
1300    ) -> Value {
1301        Value::Null
1302    }
1303
1304    /// `starknetSign(msgHash, pri)`.
1305    pub fn starknet_sign(&self, _msg_hash: Value, _pri: Value) -> Value {
1306        self.crypto_not_supported("starknetSign")
1307    }
1308
1309    /// `extendedStarknetSign(msgHash, pri)` — starknet-curve signing for the
1310    /// `extended` exchange. Stub: starknet crypto (poseidon/stark-curve) is
1311    /// not ported to Rust yet, matching `starknet_sign` above.
1312    pub fn extended_starknet_sign(&self, _msg_hash: Value, _pri: Value) -> Value {
1313        self.crypto_not_supported("extendedStarknetSign")
1314    }
1315
1316    /// `extendedStarknetGetSelectorFromName(name)`.
1317    pub fn extended_starknet_get_selector_from_name(&self, _name: Value) -> Value {
1318        Value::Null
1319    }
1320
1321    /// `extendedStarknetComputePoseidonHashOnElements(data)`.
1322    pub fn extended_starknet_compute_poseidon_hash_on_elements(&self, _data: Value) -> Value {
1323        Value::Null
1324    }
1325
1326    /// `toDydxLong(numStr)`.
1327    pub fn to_dydx_long(&self, _num_str: Value) -> Value {
1328        Value::Null
1329    }
1330
1331    /// `retrieveDydxCredentials(entropy)`.
1332    pub fn retrieve_dydx_credentials(&self, _entropy: Value) -> Value {
1333        Value::Null
1334    }
1335
1336    /// `loadDydxProtos()`.
1337    pub async fn load_dydx_protos(&self) -> Value {
1338        Value::Null
1339    }
1340
1341    /// `encodeDydxTxRaw(signDoc, signature)`.
1342    pub fn encode_dydx_tx_raw(&self, _sign_doc: Value, _signature: Value) -> Value {
1343        self.crypto_not_supported("encodeDydxTxRaw")
1344    }
1345
1346    /// `encodeDydxTxForSimulation(message, memo, sequence, publicKey)`.
1347    pub fn encode_dydx_tx_for_simulation(
1348        &self,
1349        _message: Value,
1350        _memo: Value,
1351        _sequence: Value,
1352        _public_key: Value,
1353    ) -> Value {
1354        Value::Null
1355    }
1356
1357    /// `encodeDydxTxForSigning(message, memo, chainId, account, authenticators, fee?)`.
1358    pub fn encode_dydx_tx_for_signing(
1359        &self,
1360        _message: Value,
1361        _memo: Value,
1362        _chain_id: Value,
1363        _account: Value,
1364        _authenticators: Value,
1365        _optional_args: &[Value],
1366    ) -> Value {
1367        Value::Null
1368    }
1369
1370    /// `loadLighterLibrary(libraryPath, chainId, privateKey, apiKeyIndex, accountIndex, createClient?)`.
1371    pub async fn load_lighter_library(
1372        &self,
1373        _library_path: Value,
1374        _chain_id: Value,
1375        _private_key: Value,
1376        _api_key_index: Value,
1377        _account_index: Value,
1378        _optional_args: &[Value],
1379    ) -> Value {
1380        Value::Null
1381    }
1382
1383    /// `lighterCreateClient(signer, chainId, privateKey, apiKeyIndex, accountIndex)`.
1384    pub fn lighter_create_client(
1385        &self,
1386        _signer: Value,
1387        _chain_id: Value,
1388        _private_key: Value,
1389        _api_key_index: Value,
1390        _account_index: Value,
1391    ) -> Value {
1392        Value::Null
1393    }
1394
1395    /// `lighterGenerateApiKey(signer)`.
1396    pub fn lighter_generate_api_key(&self, _signer: Value) -> Value {
1397        self.crypto_not_supported("lighterGenerateApiKey")
1398    }
1399
1400    /// `getZKTransferSignatureObj(seeds, order)` — apex StarkEx signing.
1401    pub async fn get_zk_transfer_signature_obj(
1402        &self,
1403        _seeds: Value,
1404        _optional_args: &[Value],
1405    ) -> Value {
1406        self.crypto_not_supported("getZKTransferSignatureObj")
1407    }
1408
1409    /// `getZKContractSignatureObj(seeds, order)` — apex StarkEx signing.
1410    pub async fn get_zk_contract_signature_obj(
1411        &self,
1412        _seeds: Value,
1413        _optional_args: &[Value],
1414    ) -> Value {
1415        self.crypto_not_supported("getZKContractSignatureObj")
1416    }
1417
1418    /// `futuresTransfer(code, amount, type, params?)` — binance futures
1419    /// wallet transfer; inherited by binancecoinm / binanceusdm.
1420    pub async fn futures_transfer(
1421        &self,
1422        _code: Value,
1423        _amount: Value,
1424        _transfer_type: Value,
1425        _optional_args: &[Value],
1426    ) -> Value {
1427        Value::Null
1428    }
1429
1430    /// `lighterSign*(signer, request)` — lighter zk-proof signing helpers.
1431    pub fn lighter_sign_create_order(&self, _signer: Value, _request: Value) -> Value {
1432        self.crypto_not_supported("lighterSignCreateOrder")
1433    }
1434    pub fn lighter_sign_create_grouped_orders(&self, _signer: Value, _request: Value) -> Value {
1435        self.crypto_not_supported("lighterSignCreateGroupedOrders")
1436    }
1437    pub fn lighter_sign_cancel_order(&self, _signer: Value, _request: Value) -> Value {
1438        self.crypto_not_supported("lighterSignCancelOrder")
1439    }
1440    pub fn lighter_sign_cancel_all_orders(&self, _signer: Value, _request: Value) -> Value {
1441        self.crypto_not_supported("lighterSignCancelAllOrders")
1442    }
1443    pub fn lighter_sign_withdraw(&self, _signer: Value, _request: Value) -> Value {
1444        self.crypto_not_supported("lighterSignWithdraw")
1445    }
1446    pub fn lighter_sign_create_sub_account(&self, _signer: Value, _request: Value) -> Value {
1447        self.crypto_not_supported("lighterSignCreateSubAccount")
1448    }
1449    pub fn lighter_sign_modify_order(&self, _signer: Value, _request: Value) -> Value {
1450        self.crypto_not_supported("lighterSignModifyOrder")
1451    }
1452    pub fn lighter_sign_transfer(&self, _signer: Value, _request: Value) -> Value {
1453        self.crypto_not_supported("lighterSignTransfer")
1454    }
1455    pub fn lighter_sign_update_leverage(&self, _signer: Value, _request: Value) -> Value {
1456        self.crypto_not_supported("lighterSignUpdateLeverage")
1457    }
1458    pub fn lighter_sign_update_margin(&self, _signer: Value, _request: Value) -> Value {
1459        self.crypto_not_supported("lighterSignUpdateMargin")
1460    }
1461    pub fn lighter_sign_approve_integrator(&self, _signer: Value, _request: Value) -> Value {
1462        self.crypto_not_supported("lighterSignApproveIntegrator")
1463    }
1464    pub fn lighter_sign_change_pubkey(&self, _signer: Value, _request: Value) -> Value {
1465        self.crypto_not_supported("lighterSignChangePubkey")
1466    }
1467    pub fn lighter_create_auth_token(&self, _signer: Value, _request: Value) -> Value {
1468        self.crypto_not_supported("lighterCreateAuthToken")
1469    }
1470
1471    /// `urlencodeWithArrayRepeat(params)` — `qs.stringify(object, { arrayFormat: 'repeat' })`:
1472    /// array values repeat the key (`a=1&a=2`); scalars encode normally.
1473    pub fn urlencode_with_array_repeat(&self, params: Value) -> Value {
1474        let m = match &params {
1475            Value::Dict(m) => m,
1476            _ => return Value::Str(String::new()),
1477        };
1478        let mut pairs: Vec<String> = Vec::new();
1479        for (k, v) in m.iter() {
1480            let key = crate::exchange::url_pct(k);
1481            match v {
1482                Value::Arr(items) => {
1483                    for item in items.iter() {
1484                        pairs.push(format!(
1485                            "{}={}",
1486                            key,
1487                            crate::exchange::url_pct(&stringify_param(item))
1488                        ));
1489                    }
1490                }
1491                other => {
1492                    pairs.push(format!(
1493                        "{}={}",
1494                        key,
1495                        crate::exchange::url_pct(&stringify_param(other))
1496                    ));
1497                }
1498            }
1499        }
1500        Value::Str(pairs.join("&"))
1501    }
1502
1503    pub fn safe_integer(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
1504        let v = self.safe_value(obj, key, &[]);
1505        match v {
1506            Value::Int(_) => v,
1507            Value::Float(f) => Value::Int(f as i64),
1508            // CCXT `safeInteger` is parseInt-style: a decimal string like
1509            // "3.33" truncates to 3 (arkham leverage tiers), not null. Try
1510            // an exact i64 first, then fall back to f64 → truncate.
1511            Value::Str(s) => match s.parse::<i64>() {
1512                Ok(n) => Value::Int(n),
1513                Err(_) => match s.parse::<f64>() {
1514                    Ok(f) if f.is_finite() => Value::Int(f as i64),
1515                    _ => arg_default(optional_args),
1516                },
1517            },
1518            _ => arg_default(optional_args),
1519        }
1520    }
1521
1522    pub fn safe_integer2(
1523        &self,
1524        obj: Value,
1525        k1: Value,
1526        k2: Value,
1527        optional_args: &[Value],
1528    ) -> Value {
1529        let v = self.safe_integer(obj.clone(), k1, &[]);
1530        if !v.is_null() {
1531            return v;
1532        }
1533        let v = self.safe_integer(obj, k2, &[]);
1534        if !v.is_null() {
1535            v
1536        } else {
1537            arg_default(optional_args)
1538        }
1539    }
1540
1541    pub fn safe_integer_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
1542        if let Value::Arr(ks) = keys {
1543            for k in ks.iter().cloned() {
1544                let v = self.safe_integer(obj.clone(), k, &[]);
1545                if !v.is_null() {
1546                    return v;
1547                }
1548            }
1549        }
1550        arg_default(optional_args)
1551    }
1552
1553    /// Reads `obj[key]` as a number, multiplies by `factor`, and casts
1554    /// to i64. Used to convert seconds → milliseconds for timestamps.
1555    pub fn safe_integer_product(
1556        &self,
1557        obj: Value,
1558        key: Value,
1559        factor: Value,
1560        optional_args: &[Value],
1561    ) -> Value {
1562        let v = self.safe_value(obj, key, &[]);
1563        let n = match v {
1564            Value::Int(n) => Some(n as f64),
1565            Value::Float(f) => Some(f),
1566            Value::Str(s) => s.parse::<f64>().ok(),
1567            _ => None,
1568        };
1569        let f = match factor {
1570            Value::Int(n) => n as f64,
1571            Value::Float(f) => f,
1572            _ => return arg_default(optional_args),
1573        };
1574        match n {
1575            Some(x) => Value::Int((x * f) as i64),
1576            None => arg_default(optional_args),
1577        }
1578    }
1579
1580    pub fn safe_integer_product2(
1581        &self,
1582        obj: Value,
1583        k1: Value,
1584        k2: Value,
1585        factor: Value,
1586        optional_args: &[Value],
1587    ) -> Value {
1588        let v = self.safe_integer_product(obj.clone(), k1, factor.clone(), &[]);
1589        if !v.is_null() {
1590            return v;
1591        }
1592        let v = self.safe_integer_product(obj, k2, factor, &[]);
1593        if !v.is_null() {
1594            v
1595        } else {
1596            arg_default(optional_args)
1597        }
1598    }
1599
1600    pub fn safe_integer_product_n(
1601        &self,
1602        obj: Value,
1603        keys: Value,
1604        factor: Value,
1605        optional_args: &[Value],
1606    ) -> Value {
1607        if let Value::Arr(ks) = keys {
1608            for k in ks.iter().cloned() {
1609                let v = self.safe_integer_product(obj.clone(), k, factor.clone(), &[]);
1610                if !v.is_null() {
1611                    return v;
1612                }
1613            }
1614        }
1615        arg_default(optional_args)
1616    }
1617
1618    pub fn safe_timestamp2(
1619        &self,
1620        obj: Value,
1621        k1: Value,
1622        k2: Value,
1623        optional_args: &[Value],
1624    ) -> Value {
1625        self.safe_integer_product2(obj, k1, k2, Value::Int(1000), optional_args)
1626    }
1627
1628    pub fn safe_timestamp_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
1629        self.safe_integer_product_n(obj, keys, Value::Int(1000), optional_args)
1630    }
1631
1632    pub fn safe_float(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
1633        let v = self.safe_value(obj, key, &[]);
1634        match v {
1635            Value::Float(_) => v,
1636            Value::Int(n) => Value::Float(n as f64),
1637            Value::Str(s) => match s.parse::<f64>() {
1638                Ok(n) => Value::Float(n),
1639                Err(_) => arg_default(optional_args),
1640            },
1641            _ => arg_default(optional_args),
1642        }
1643    }
1644
1645    /// `safeTimestamp(o, k)` — `parseInt(asFloat(value) * 1000)`. The
1646    /// value is read as a float (seconds, possibly fractional) and
1647    /// converted to integer milliseconds.
1648    pub fn safe_timestamp(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
1649        match self.safe_float(obj, key, &[]) {
1650            Value::Float(f) => Value::Int((f * 1000.0) as i64),
1651            Value::Int(n) => Value::Int(n * 1000),
1652            _ => arg_default(optional_args),
1653        }
1654    }
1655
1656    /// `isEmpty(value)` — true when an array/dict is empty, or the
1657    /// value is null/undefined. Scalars (strings, numbers, bools) are
1658    /// never considered empty — mirrors `functions/generic.ts`.
1659    pub fn is_empty(&self, v: Value) -> Value {
1660        let empty = match &v {
1661            Value::Null => true,
1662            Value::Arr(a) => a.is_empty(),
1663            Value::Dict(m) => m.is_empty(),
1664            _ => false,
1665        };
1666        Value::Bool(empty)
1667    }
1668
1669    pub fn value_is_defined(&self, v: Value) -> Value {
1670        Value::Bool(!v.is_null())
1671    }
1672
1673    // ── extend / deep_extend / omit ─────────────────────────────────────────
1674
1675    pub fn extend(&self, a: Value, optional_args: &[Value]) -> Value {
1676        let mut out = match a {
1677            Value::Dict(m) => Arc::try_unwrap(m).unwrap_or_else(|x| (*x).clone()),
1678            _ => HashMap::new(),
1679        };
1680        let merge = |out: &mut HashMap<String, Value>, src: Value| {
1681            if let Value::Dict(m) = src {
1682                let m = Arc::try_unwrap(m).unwrap_or_else(|x| (*x).clone());
1683                for (k, v) in m {
1684                    out.insert(k, v);
1685                }
1686            }
1687        };
1688        for extra in optional_args {
1689            merge(&mut out, extra.clone());
1690        }
1691        Value::Map(out)
1692    }
1693
1694    pub fn deep_extend(&self, a: Value, optional_args: &[Value]) -> Value {
1695        let mut current = a;
1696        for extra in optional_args {
1697            current = crate::value::deep_extend(current, extra.clone());
1698        }
1699        current
1700    }
1701
1702    pub fn omit(&self, obj: Value, keys: Value, _optional_args: &[Value]) -> Value {
1703        match obj {
1704            Value::Dict(mut m) => {
1705                let mm = Arc::make_mut(&mut m);
1706                match keys {
1707                    Value::Arr(ks) => {
1708                        for k in ks.iter() {
1709                            if let Value::Str(s) = k {
1710                                mm.shift_remove(s);
1711                            }
1712                        }
1713                    }
1714                    Value::Str(s) => {
1715                        mm.shift_remove(&s);
1716                    }
1717                    _ => {}
1718                }
1719                Value::Dict(m)
1720            }
1721            other => other,
1722        }
1723    }
1724
1725    pub fn omit_zero(&self, v: Value) -> Value {
1726        // Mirrors TS `omitZero`: undefined/'' or any value that parses to
1727        // numeric 0 → undefined. The old `s == "0"` check missed "0.0",
1728        // "0.00", "0e0" etc. — e.g. gate echoes `gt_fee:"0.0"`, and
1729        // keeping it as a non-null fee left `safeTrade` with 3 fee
1730        // entries (so it couldn't collapse to a single `fee`).
1731        match &v {
1732            Value::Int(0) => Value::Null,
1733            Value::Float(f) if *f == 0.0 => Value::Null,
1734            Value::Str(s) => {
1735                if s.is_empty() {
1736                    return Value::Null;
1737                }
1738                match s.parse::<f64>() {
1739                    Ok(n) if n == 0.0 => Value::Null,
1740                    _ => v,
1741                }
1742            }
1743            _ => v,
1744        }
1745    }
1746
1747    // ── array / object utilities ────────────────────────────────────────────
1748
1749    pub fn to_array(&self, v: Value) -> Value {
1750        // A WS cache (ArrayCache / order-book cache) keeps its entries in `_data`
1751        // or the shared cache registry, not the dict's meta fields — surface
1752        // those, else `to_array` would leak `__cacheKind`/counters/flags as rows.
1753        if let Some(entries) = crate::value::cache_entries_as_value(&v) {
1754            return entries;
1755        }
1756        match v {
1757            Value::Arr(_) => v,
1758            Value::Dict(m) => Value::Array(m.values().cloned().collect()),
1759            Value::Null => Value::Array(vec![]),
1760            other => Value::Array(vec![other]),
1761        }
1762    }
1763
1764    pub fn array_concat(&self, a: Value, b: Value) -> Value {
1765        crate::runtime::concat_arrays(&a, &b)
1766    }
1767
1768    pub fn array_slice(&self, v: Value, start: Value, optional_args: &[Value]) -> Value {
1769        let Value::Arr(a) = v else {
1770            return Value::Array(vec![]);
1771        };
1772        let len = a.len() as i64;
1773        let s = match start {
1774            Value::Int(n) => n,
1775            _ => 0,
1776        };
1777        let s = if s < 0 {
1778            (len + s).max(0) as usize
1779        } else {
1780            (s as usize).min(a.len())
1781        };
1782        let e = match optional_args.get(0) {
1783            None | Some(Value::Null) => a.len(),
1784            Some(Value::Int(n)) => {
1785                if *n < 0 {
1786                    ((len) + n).max(0) as usize
1787                } else {
1788                    (*n as usize).min(a.len())
1789                }
1790            }
1791            _ => a.len(),
1792        };
1793        if s <= e {
1794            Value::Array(a[s..e].to_vec())
1795        } else {
1796            Value::Array(vec![])
1797        }
1798    }
1799
1800    pub fn in_array(&self, needle: Value, haystack: Value) -> Value {
1801        let hit = if let Value::Arr(a) = haystack {
1802            a.iter().any(|x| crate::runtime::is_equal(x, &needle))
1803        } else {
1804            false
1805        };
1806        Value::Bool(hit)
1807    }
1808
1809    pub fn unique(&self, v: Value) -> Value {
1810        if let Value::Arr(a) = v {
1811            let mut out: Vec<Value> = vec![];
1812            for item in a.iter().cloned() {
1813                if !out.iter().any(|x| crate::runtime::is_equal(x, &item)) {
1814                    out.push(item);
1815                }
1816            }
1817            Value::Array(out)
1818        } else {
1819            Value::Array(vec![])
1820        }
1821    }
1822
1823    pub fn index_by(&self, arr: Value, key: Value) -> Value {
1824        let k = key_str(&key);
1825        let mut out: HashMap<String, Value> = HashMap::new();
1826        // TS `indexBy` accepts an array OR an object — for an object it
1827        // iterates `Object.values`. okx's parseDepositAddress relies on
1828        // this: `indexBy(currency['networks'], 'id')` where `networks` is
1829        // a dict keyed by network code. Array-only would return {} and
1830        // collapse every parsed address to a null network.
1831        let items: Vec<Value> = match arr {
1832            Value::Arr(items) => Arc::try_unwrap(items).unwrap_or_else(|a| (*a).clone()),
1833            Value::Dict(m) => m.values().cloned().collect(),
1834            _ => return Value::Map(out),
1835        };
1836        for item in items {
1837            if let Some(kv) = crate::value::safe_string(&item, &k, None) {
1838                out.insert(kv, item);
1839            }
1840        }
1841        Value::Map(out)
1842    }
1843
1844    pub fn index_by_safe(&self, arr: Value, key: Value) -> Value {
1845        self.index_by(arr, key)
1846    }
1847
1848    pub fn group_by(&self, arr: Value, key: Value, _optional_args: &[Value]) -> Value {
1849        let k = key_str(&key);
1850        let mut out: HashMap<String, Vec<Value>> = HashMap::new();
1851        if let Value::Arr(items) = arr {
1852            for item in items.iter().cloned() {
1853                if let Some(kv) = crate::value::safe_string(&item, &k, None) {
1854                    out.entry(kv).or_default().push(item);
1855                }
1856            }
1857        }
1858        Value::Map(out.into_iter().map(|(k, v)| (k, Value::Array(v))).collect())
1859    }
1860
1861    pub fn filter_by(
1862        &self,
1863        arr: Value,
1864        key: Value,
1865        value: Value,
1866        _optional_args: &[Value],
1867    ) -> Value {
1868        let k = key_str(&key);
1869        if let Value::Arr(items) = arr {
1870            let items = Arc::try_unwrap(items).unwrap_or_else(|a| (*a).clone());
1871            let out: Vec<Value> = items
1872                .into_iter()
1873                .filter(|it| {
1874                    let v = crate::get_value(it, &Value::Str(k.clone()));
1875                    crate::runtime::is_equal(&v, &value)
1876                })
1877                .collect();
1878            Value::Array(out)
1879        } else {
1880            Value::Array(vec![])
1881        }
1882    }
1883
1884    /// `sortBy(array, key, descending=false)` — stable sort of an array
1885    /// of objects by `obj[key]`. Mirrors `functions/generic.ts`.
1886    pub fn sort_by(&self, arr: Value, key: Value, optional_args: &[Value]) -> Value {
1887        let mut items = match arr {
1888            Value::Arr(a) => Arc::try_unwrap(a).unwrap_or_else(|x| (*x).clone()),
1889            other => return other,
1890        };
1891        let descending = matches!(optional_args.get(0), Some(Value::Bool(true)));
1892        let key = Value::Str(stringify_param(&key));
1893        items.sort_by(|a, b| {
1894            let av = crate::get_value(a, &key);
1895            let bv = crate::get_value(b, &key);
1896            let ord = value_cmp(&av, &bv);
1897            if descending {
1898                ord.reverse()
1899            } else {
1900                ord
1901            }
1902        });
1903        Value::Array(items)
1904    }
1905
1906    /// `sortBy2(array, key1, key2, descending=false)` — sort by `key1`,
1907    /// then `key2` as a tiebreaker. Mirrors `functions/generic.ts`.
1908    pub fn sort_by2(&self, arr: Value, k1: Value, k2: Value, optional_args: &[Value]) -> Value {
1909        let mut items = match arr {
1910            Value::Arr(a) => Arc::try_unwrap(a).unwrap_or_else(|x| (*x).clone()),
1911            other => return other,
1912        };
1913        let descending = matches!(optional_args.get(0), Some(Value::Bool(true)));
1914        let k1 = Value::Str(stringify_param(&k1));
1915        let k2 = Value::Str(stringify_param(&k2));
1916        items.sort_by(|a, b| {
1917            let ord = value_cmp(&crate::get_value(a, &k1), &crate::get_value(b, &k1)).then(
1918                value_cmp(&crate::get_value(a, &k2), &crate::get_value(b, &k2)),
1919            );
1920            if descending {
1921                ord.reverse()
1922            } else {
1923                ord
1924            }
1925        });
1926        Value::Array(items)
1927    }
1928
1929    pub fn keysort(&self, obj: Value, _optional_args: &[Value]) -> Value {
1930        if let Value::Dict(m) = obj {
1931            let mut keys: Vec<&String> = m.keys().collect();
1932            keys.sort();
1933            let mut out = HashMap::new();
1934            for k in &keys {
1935                out.insert((*k).clone(), m[*k].clone());
1936            }
1937            Value::Map(out)
1938        } else {
1939            obj
1940        }
1941    }
1942
1943    /// `aggregate(bidasks)` — groups `[price, volume]` rows by price,
1944    /// summing volume and dropping zero-volume rows. Preserves the
1945    /// first-occurrence order of prices. Mirrors `functions/misc.ts`.
1946    pub fn aggregate(&self, arr: Value) -> Value {
1947        // An order-book side is a marker Dict backed by the shared side store,
1948        // not a plain array (in JS `OrderBookSide` extends Array). Snapshot its
1949        // `[[price, size], …]` rows so aggregate iterates the levels.
1950        let arr = crate::value::side_entries_as_value(&arr).unwrap_or(arr);
1951        let items = match arr {
1952            Value::Arr(a) => Arc::try_unwrap(a).unwrap_or_else(|x| (*x).clone()),
1953            _ => return Value::Array(vec![]),
1954        };
1955        let mut order: Vec<u64> = Vec::new();
1956        let mut buckets: HashMap<u64, (f64, f64)> = HashMap::new();
1957        for item in items {
1958            let row = match item {
1959                Value::Arr(r) => r,
1960                _ => continue,
1961            };
1962            let price = value_as_f64(row.get(0));
1963            let volume = value_as_f64(row.get(1));
1964            if volume > 0.0 {
1965                let bits = price.to_bits();
1966                let entry = buckets.entry(bits).or_insert_with(|| {
1967                    order.push(bits);
1968                    (price, 0.0)
1969                });
1970                entry.1 += volume;
1971            }
1972        }
1973        let out: Vec<Value> = order
1974            .iter()
1975            .map(|b| {
1976                let (p, v) = buckets[b];
1977                Value::Array(vec![Value::Float(p), Value::Float(v)])
1978            })
1979            .collect();
1980        Value::Array(out)
1981    }
1982    pub fn map_to_safe_map(&self, v: Value) -> Value {
1983        v
1984    }
1985    pub fn create_safe_dictionary(&self, _optional_args: &[Value]) -> Value {
1986        Value::Map(HashMap::new())
1987    }
1988
1989    /// `clone(value)` — CCXT's deep clone, distinct from Rust's `Clone` trait.
1990    /// We disambiguate by name; the transpiler emits `self.clone(x)`.
1991    pub fn clone_value(&self, v: Value) -> Value {
1992        v
1993    }
1994
1995    /// `sum(...)` — variadic numeric sum. Pure variadic (0 fixed
1996    /// args) so single-arg `sum(x)` (e.g. from test.sum) also works.
1997    pub fn sum(&self, optional_args: &[Value]) -> Value {
1998        let mut acc: Option<Value> = None;
1999        for x in optional_args {
2000            acc = Some(match acc {
2001                None => x.clone(),
2002                Some(a) => crate::runtime::add(&a, x),
2003            });
2004        }
2005        acc.unwrap_or(Value::Null)
2006    }
2007
2008    /// `parse_json(text)` — JSON parse. Mirrors CCXT `parseJson`, which
2009    /// runs `onJsonResponse` first: when `quoteJsonNumbers` is on
2010    /// (default), every object number VALUE is wrapped in quotes before
2011    /// parsing so big integer ids (e.g. bingx's 18-digit `orderId`) and
2012    /// precise decimals survive as strings instead of lossy f64/i64.
2013    pub fn parse_json_value(&self, v: Value) -> Value {
2014        match v {
2015            Value::Str(s) => {
2016                let prepared = crate::runtime::quote_json_numbers(&s);
2017                crate::runtime::json_parse(&Value::Str(prepared))
2018            }
2019            // Already a parsed object/array (some fixtures store the
2020            // response pre-parsed) — pass it through untouched.
2021            other => other,
2022        }
2023    }
2024
2025    // `yymmdd()` / `yyyymmdd()` — date formatters.
2026    // ── methods called by transpiled base tests ─────────────────────────────
2027
2028    /// Test helper: tests sometimes call `exchange.clone()` to deep-copy
2029    /// state. We don't implement structural clone (the trait pointer
2030    /// can't be cloned safely) — return a fresh empty Exchange so the
2031    /// call compiles and tests can move on.
2032    /// No-arg `exchange.clone()` form — a structural copy of every
2033    /// `Value` field. The copy gets a fresh `Internals` (no shared http
2034    /// client / derived pointers), which is all the transpiled tests need.
2035    pub fn clone_self(&self) -> Exchange {
2036        Clone::clone(self)
2037    }
2038
2039    /// `clone(v)` — deep-clone a Value. Matches TS `exchange.clone(x)`.
2040    /// Note: keep this name even though it shadows the (manual) `clone_self`,
2041    /// because the transpiled tests call `exchange.clone(value)`. Empty-arg
2042    /// calls `exchange.clone()` get post-processed to `clone_self()`.
2043    pub fn clone(&self, v: Value) -> Value {
2044        v
2045    }
2046
2047    /// Dynamic-property lookup for transpiled base tests. The TS code
2048    /// does `exchange['options']`, `exchange['markets']`, etc. — this
2049    /// reads from the unified `to_value()` view so both access paths
2050    /// (`exchange.prop(k)` and `testSharedMethods.exchangeProp`) agree.
2051    pub fn prop(&self, key: &Value) -> Value {
2052        crate::get_value(&self.to_value(), key)
2053    }
2054
2055    /// Full `Value::Map` snapshot of every transpiler-visible field —
2056    /// the Rust analogue of indexing a JS object by property name.
2057    /// Used by `prop()` and by the base-test `exchangeProp` shim.
2058    pub fn to_value(&self) -> Value {
2059        let mut m = indexmap::IndexMap::new();
2060        let mut put = |k: &str, v: &Value| {
2061            m.insert(k.to_string(), v.clone());
2062        };
2063        put("id", &self.id);
2064        put("name", &self.name);
2065        put("countries", &self.countries);
2066        put("version", &self.version);
2067        put("alias", &self.alias);
2068        put("certified", &self.certified);
2069        put("pro", &self.pro);
2070        put("hostname", &self.hostname);
2071        put("apiKey", &self.apiKey);
2072        put("secret", &self.secret);
2073        put("password", &self.password);
2074        put("uid", &self.uid);
2075        put("walletAddress", &self.walletAddress);
2076        put("privateKey", &self.privateKey);
2077        put("twofa", &self.twofa);
2078        put("token", &self.token);
2079        put("login", &self.login);
2080        put("accountId", &self.accountId);
2081        put("requiredCredentials", &self.requiredCredentials);
2082        put("timeout", &self.timeout);
2083        put("rateLimit", &self.rateLimit);
2084        put("enableRateLimit", &self.enableRateLimit);
2085        put("fetchHistoryCacheSize", &self.fetchHistoryCacheSize);
2086        put("rateLimiterAlgorithm", &self.rateLimiterAlgorithm);
2087        put("rollingWindowSize", &self.rollingWindowSize);
2088        put("tokenBucket", &self.tokenBucket);
2089        put("verbose", &self.verbose);
2090        put("isSandboxModeEnabled", &self.isSandboxModeEnabled);
2091        put("proxy", &self.proxy);
2092        put("proxyUrl", &self.proxyUrl);
2093        put("proxy_url", &self.proxy_url);
2094        put("proxyUrlCallback", &self.proxyUrlCallback);
2095        put("proxy_url_callback", &self.proxy_url_callback);
2096        put("httpProxy", &self.httpProxy);
2097        put("http_proxy", &self.http_proxy);
2098        put("httpProxyCallback", &self.httpProxyCallback);
2099        put("http_proxy_callback", &self.http_proxy_callback);
2100        put("httpsProxy", &self.httpsProxy);
2101        put("https_proxy", &self.https_proxy);
2102        put("httpsProxyCallback", &self.httpsProxyCallback);
2103        put("https_proxy_callback", &self.https_proxy_callback);
2104        put("socksProxy", &self.socksProxy);
2105        put("socks_proxy", &self.socks_proxy);
2106        put("socksProxyCallback", &self.socksProxyCallback);
2107        put("socks_proxy_callback", &self.socks_proxy_callback);
2108        put("wsProxy", &self.wsProxy);
2109        put("ws_proxy", &self.ws_proxy);
2110        put("wssProxy", &self.wssProxy);
2111        put("wss_proxy", &self.wss_proxy);
2112        put("wsSocksProxy", &self.wsSocksProxy);
2113        put("ws_socks_proxy", &self.ws_socks_proxy);
2114        put("markets", &self.markets);
2115        put("markets_by_id", &self.markets_by_id);
2116        put("currencies", &self.currencies);
2117        put("currencies_by_id", &self.currencies_by_id);
2118        put("commonCurrencies", &self.commonCurrencies);
2119        put("baseCurrencies", &self.baseCurrencies);
2120        put("quoteCurrencies", &self.quoteCurrencies);
2121        put("symbols", &self.symbols);
2122        put("ids", &self.ids);
2123        put("codes", &self.codes);
2124        put("timeframes", &self.timeframes);
2125        put("precision", &self.precision);
2126        put("limits", &self.limits);
2127        put("fees", &self.fees);
2128        put("features", &self.features);
2129        put("has", &self.has);
2130        put("exceptions", &self.exceptions);
2131        put("urls", &self.urls);
2132        put("api", &self.api);
2133        put("options", &self.options);
2134        put("headers", &self.headers);
2135        put("accounts", &self.accounts);
2136        put("accountsById", &self.accountsById);
2137        put("orderbooks", &self.orderbooks);
2138        put("orders", &self.orders);
2139        put("trades", &self.trades);
2140        put("myTrades", &self.myTrades);
2141        put("positions", &self.positions);
2142        put("tickers", &self.tickers);
2143        put("bidsasks", &self.bidsasks);
2144        put("ohlcvs", &self.ohlcvs);
2145        put("clients", &self.clients);
2146        put("balance", &self.balance);
2147        put("liquidations", &self.liquidations);
2148        put("myLiquidations", &self.myLiquidations);
2149        put("transactions", &self.transactions);
2150        put("reloadingMarkets", &self.reloadingMarkets);
2151        put("marketsLoading", &self.marketsLoading);
2152        put("last_request_url", &self.last_request_url);
2153        put("last_request_headers", &self.last_request_headers);
2154        put("last_request_body", &self.last_request_body);
2155        put("last_http_response", &self.last_http_response);
2156        put("last_response_headers", &self.last_response_headers);
2157        put("last_json_response", &self.last_json_response);
2158        put("lastRestRequestTimestamp", &self.lastRestRequestTimestamp);
2159        put("paddingMode", &self.paddingMode);
2160        put("precisionMode", &self.precisionMode);
2161        put(
2162            "substituteCommonCurrencyCodes",
2163            &self.substituteCommonCurrencyCodes,
2164        );
2165        put("reduceFees", &self.reduceFees);
2166        put("minFundingAddressLength", &self.minFundingAddressLength);
2167        put("MAX_VALUE", &self.MAX_VALUE);
2168        put("returnResponseHeaders", &self.returnResponseHeaders);
2169        put("httpExceptions", &self.httpExceptions);
2170        put("status", &self.status);
2171        put("userAgent", &self.userAgent);
2172        put("user_agent", &self.user_agent);
2173        put("userAgents", &self.userAgents);
2174        Value::Map(m)
2175    }
2176
2177    pub fn base16ToBinary(&self, hex: Value, optional_args: &[Value]) -> Value {
2178        self.base16_to_binary(hex, optional_args)
2179    }
2180    pub fn base58_to_binary(&self, s: Value, _optional_args: &[Value]) -> Value {
2181        match &s {
2182            Value::Str(s) => match base58_decode(s) {
2183                Some(b) => bytes_to_value(&b),
2184                None => Value::Null,
2185            },
2186            _ => Value::Null,
2187        }
2188    }
2189    pub fn binary_to_base58(&self, b: Value, _optional_args: &[Value]) -> Value {
2190        Value::Str(base58_encode(&crate::exchange::value_to_bytes(&b)))
2191    }
2192    pub fn binary_length(&self, b: Value, _optional_args: &[Value]) -> Value {
2193        match b {
2194            Value::Arr(a) => Value::Int(a.len() as i64),
2195            _ => Value::Int(0),
2196        }
2197    }
2198    /// `isBinaryMessage` — in this port a binary buffer is a
2199    /// `Value::Array` of byte-valued ints (see `base16_to_binary`,
2200    /// `string_to_binary`). `instanceof Uint8Array` can't transpile.
2201    pub fn is_binary_message(&self, v: Value, _optional_args: &[Value]) -> Value {
2202        Value::Bool(is_byte_array(&v))
2203    }
2204    /// `numberToBE(n, padding)` — big-endian byte array of width `padding`.
2205    pub fn number_to_be(&self, n: Value, optional_args: &[Value]) -> Value {
2206        let num: u64 = match &n {
2207            Value::Int(i) => (*i).max(0) as u64,
2208            Value::Float(f) => (*f).max(0.0) as u64,
2209            Value::Str(s) => s.parse().unwrap_or(0),
2210            _ => 0,
2211        };
2212        let padding: usize = match optional_args.get(0) {
2213            Some(Value::Int(i)) => (*i).max(0) as usize,
2214            Some(Value::Float(f)) => (*f).max(0.0) as usize,
2215            _ => 8,
2216        };
2217        let be = num.to_be_bytes(); // 8 bytes
2218        let mut out: Vec<u8> = Vec::with_capacity(padding);
2219        if padding >= be.len() {
2220            out.extend(std::iter::repeat(0u8).take(padding - be.len()));
2221            out.extend_from_slice(&be);
2222        } else {
2223            out.extend_from_slice(&be[be.len() - padding..]);
2224        }
2225        bytes_to_value(&out)
2226    }
2227    /// `parseDate(x)` — ports `functions/time.ts`. Parses an ISO-8601
2228    /// timestamp (with `T`/`Z` or a plain `YYYY-MM-DD HH:MM:SS` form,
2229    /// treated as UTC) into epoch milliseconds. Invalid → Null.
2230    pub fn parse_date(&self, s: Value, _optional_args: &[Value]) -> Value {
2231        let text = match &s {
2232            Value::Str(s) if !s.is_empty() => s.clone(),
2233            _ => return Value::Null,
2234        };
2235        // rfc3339 (handles the `T...Z` and offset forms)
2236        if let Ok(t) = chrono::DateTime::parse_from_rfc3339(&text) {
2237            return Value::Int(t.timestamp_millis());
2238        }
2239        // naive `YYYY-MM-DD HH:MM:SS[.fff]` — interpreted as UTC
2240        for fmt in [
2241            "%Y-%m-%d %H:%M:%S%.f",
2242            "%Y-%m-%d %H:%M:%S",
2243            "%Y-%m-%dT%H:%M:%S%.f",
2244            "%Y-%m-%dT%H:%M:%S",
2245        ] {
2246            if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(&text, fmt) {
2247                return Value::Int(ndt.and_utc().timestamp_millis());
2248            }
2249        }
2250        Value::Null
2251    }
2252    pub fn is_binary_message_var(&self, v: Value, _optional_args: &[Value]) -> Value {
2253        Value::Bool(is_byte_array(&v))
2254    }
2255    /// `ymd(timestamp, infix='')` — like `yyyymmdd` but the infix
2256    /// defaults to empty (TS `functions/time.ts`).
2257    pub fn ymd(&self, ts: Value, optional_args: &[Value]) -> Value {
2258        if optional_args.is_empty() {
2259            self.yyyymmdd(ts, &[Value::Str(String::new())])
2260        } else {
2261            self.yyyymmdd(ts, optional_args)
2262        }
2263    }
2264    pub fn safe_float_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
2265        if let Value::Arr(ks) = keys {
2266            for k in ks.iter().cloned() {
2267                let v = self.safe_float(obj.clone(), k, &[]);
2268                if !v.is_null() {
2269                    return v;
2270                }
2271            }
2272        }
2273        arg_default(optional_args)
2274    }
2275    pub fn safe_float2(&self, obj: Value, k1: Value, k2: Value, optional_args: &[Value]) -> Value {
2276        let v = self.safe_float(obj.clone(), k1, &[]);
2277        if !v.is_null() {
2278            return v;
2279        }
2280        let v = self.safe_float(obj, k2, &[]);
2281        if !v.is_null() {
2282            v
2283        } else {
2284            arg_default(optional_args)
2285        }
2286    }
2287    // The transpiler may emit camelCase callers (`safeString2`) directly
2288    // because the rust-port preserved the TS name. Alias to the
2289    // snake-cased one we already have.
2290    pub fn safeString2(&self, obj: Value, k1: Value, k2: Value, optional_args: &[Value]) -> Value {
2291        self.safe_string2(obj, k1, k2, optional_args)
2292    }
2293    /// `binaryConcat(a, b, ...)` — concatenates byte buffers. The
2294    /// variadic call-site wrap folds the tail args into `optional_args`.
2295    pub fn binary_concat(&self, first: Value, optional_args: &[Value]) -> Value {
2296        let mut out = crate::exchange::value_to_bytes(&first);
2297        for v in optional_args {
2298            out.extend(crate::exchange::value_to_bytes(v));
2299        }
2300        bytes_to_value(&out)
2301    }
2302    pub fn stringToBase64(&self, s: Value, optional_args: &[Value]) -> Value {
2303        self.string_to_base64(s, optional_args)
2304    }
2305    /// `binaryToString(buffer)` — decodes a byte buffer as UTF-8.
2306    pub fn binary_to_string(&self, b: Value, _optional_args: &[Value]) -> Value {
2307        let bytes = crate::exchange::value_to_bytes(&b);
2308        Value::Str(String::from_utf8_lossy(&bytes).into_owned())
2309    }
2310    pub fn string_to_binary(&self, s: Value, _optional_args: &[Value]) -> Value {
2311        match s {
2312            Value::Str(s) => Value::Array(s.bytes().map(|b| Value::Int(b as i64)).collect()),
2313            _ => Value::Array(vec![]),
2314        }
2315    }
2316    /// `urlencodeBase64(payload)` — url-safe base64 with `+/` → `-_`
2317    /// and trailing `=` padding stripped. Accepts a string or a byte
2318    /// buffer (`Value::Array`).
2319    pub fn urlencode_base64(&self, v: Value, _optional_args: &[Value]) -> Value {
2320        let bytes = match &v {
2321            Value::Str(s) => s.as_bytes().to_vec(),
2322            _ => crate::exchange::value_to_bytes(&v),
2323        };
2324        let encoded = match self.binary_to_base64(bytes_to_value(&bytes), &[]) {
2325            Value::Str(s) => s,
2326            _ => String::new(),
2327        };
2328        let trimmed = encoded.trim_end_matches('=');
2329        Value::Str(trimmed.replace('+', "-").replace('/', "_"))
2330    }
2331    /// `urlencodeNested(object)` — `qs.stringify(object, { encodeValuesOnly: true })`:
2332    /// nested maps → `parent[child]`, arrays → `parent[index]`, only
2333    /// values are percent-encoded.
2334    pub fn urlencode_nested(&self, v: Value, _optional_args: &[Value]) -> Value {
2335        let m = match &v {
2336            Value::Dict(m) => m,
2337            _ => return Value::Str(String::new()),
2338        };
2339        let mut pairs: Vec<String> = Vec::new();
2340        for (k, val) in m.iter() {
2341            urlencode_nested_walk(k, val, &mut pairs);
2342        }
2343        Value::Str(pairs.join("&"))
2344    }
2345    pub fn is_json_encoded_object(&self, optional_args: &[Value]) -> Value {
2346        match optional_args.get(0) {
2347            Some(Value::Str(s)) => Value::Bool(s.starts_with('{') || s.starts_with('[')),
2348            _ => Value::Bool(false),
2349        }
2350    }
2351    pub fn strip(&self, s: Value, _optional_args: &[Value]) -> Value {
2352        match s {
2353            Value::Str(s) => Value::Str(s.trim().to_string()),
2354            other => other,
2355        }
2356    }
2357    pub fn sort(&self, v: Value, _optional_args: &[Value]) -> Value {
2358        if let Value::Arr(a) = v {
2359            let mut a = Arc::try_unwrap(a).unwrap_or_else(|x| (*x).clone());
2360            a.sort_by(|x, y| {
2361                let xs = crate::runtime::stringify_param(x);
2362                let ys = crate::runtime::stringify_param(y);
2363                xs.cmp(&ys)
2364            });
2365            Value::Array(a)
2366        } else {
2367            v
2368        }
2369    }
2370    /// `roundTimeframe(timeframe, timestamp, direction)` — snap a
2371    /// timestamp to the timeframe boundary (down by default, up for
2372    /// `ROUND_UP`).
2373    pub fn round_timeframe(&self, tf: Value, ts: Value, direction: Value) -> Value {
2374        let secs = match self.parse_timeframe(tf) {
2375            Value::Int(s) => s,
2376            Value::Float(s) => s as i64,
2377            _ => return ts,
2378        };
2379        let ms = secs * 1000;
2380        let t = match &ts {
2381            Value::Int(i) => *i,
2382            Value::Float(f) => *f as i64,
2383            _ => return ts,
2384        };
2385        if ms == 0 {
2386            return ts;
2387        }
2388        let offset = t % ms;
2389        let is_up = matches!(&direction, Value::Int(d) if *d == crate::runtime::ROUND_UP);
2390        Value::Int(t - offset + if is_up { ms } else { 0 })
2391    }
2392    pub async fn sleep(&self, ms: Value) -> Value {
2393        if let Some(n) = match ms {
2394            Value::Int(n) => Some(n),
2395            Value::Float(f) => Some(f as i64),
2396            _ => None,
2397        } {
2398            if n > 0 {
2399                tokio::time::sleep(std::time::Duration::from_millis(n as u64)).await;
2400            }
2401        }
2402        Value::Null
2403    }
2404    /// `ethGetAddressFromPrivateKey(pk)` — derive the Ethereum address
2405    /// (keccak256 of the uncompressed secp256k1 public key, last 20 bytes).
2406    pub fn eth_get_address_from_private_key(&self, pk: Value, _optional_args: &[Value]) -> Value {
2407        use k256::ecdsa::SigningKey;
2408        let pk_s = match &pk {
2409            Value::Str(s) => s.trim_start_matches("0x").to_string(),
2410            _ => return Value::Str(String::new()),
2411        };
2412        let pk_bytes = match hex::decode(&pk_s) {
2413            Ok(b) => b,
2414            Err(_) => return Value::Str(String::new()),
2415        };
2416        let sk = match SigningKey::from_slice(&pk_bytes) {
2417            Ok(k) => k,
2418            Err(_) => return Value::Str(String::new()),
2419        };
2420        let point = sk.verifying_key().to_encoded_point(false); // 0x04 || X || Y
2421        let pubkey = &point.as_bytes()[1..]; // 64 bytes
2422        let hash = crate::exchange::hash_raw(pubkey, "keccak");
2423        Value::Str(format!("0x{}", hex::encode(&hash[12..32])))
2424    }
2425    pub fn exists_file(&self, p: Value) -> Value {
2426        match &p {
2427            Value::Str(path) => Value::Bool(std::path::Path::new(path).is_file()),
2428            _ => Value::Bool(false),
2429        }
2430    }
2431    pub fn read_file(&self, p: Value) -> Value {
2432        match &p {
2433            Value::Str(path) => match std::fs::read_to_string(path) {
2434                Ok(s) => Value::Str(s),
2435                Err(_) => Value::Null,
2436            },
2437            _ => Value::Null,
2438        }
2439    }
2440    pub fn write_file(&self, p: Value, content: Value) -> Value {
2441        let path = match &p {
2442            Value::Str(s) => s.clone(),
2443            _ => return Value::Bool(false),
2444        };
2445        let body = match &content {
2446            Value::Str(s) => s.clone(),
2447            other => stringify_param(other),
2448        };
2449        Value::Bool(std::fs::write(&path, body).is_ok())
2450    }
2451    pub fn get_temp_dir(&self) -> Value {
2452        Value::Str(format!(
2453            "{}/",
2454            std::env::temp_dir().to_string_lossy().trim_end_matches('/')
2455        ))
2456    }
2457    pub fn get_property(&self, obj: Value, key: Value) -> Value {
2458        crate::get_value(&obj, &Value::Str(stringify_param(&key)))
2459    }
2460
2461    pub fn yymmdd(&self, ts: Value, optional_args: &[Value]) -> Value {
2462        let infix = match optional_args.get(0) {
2463            Some(Value::Str(s)) => s.clone(),
2464            _ => String::new(),
2465        };
2466        let n = match ts {
2467            Value::Int(n) => n,
2468            _ => 0,
2469        };
2470        let dt = chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n);
2471        match dt {
2472            Some(t) => Value::Str(t.format(&format!("%y{i}%m{i}%d", i = infix)).to_string()),
2473            None => Value::Null,
2474        }
2475    }
2476    pub fn yyyymmdd(&self, ts: Value, optional_args: &[Value]) -> Value {
2477        // TS default infix for yyyymmdd is '-'.
2478        let infix = match optional_args.get(0) {
2479            Some(Value::Str(s)) => s.clone(),
2480            _ => "-".to_string(),
2481        };
2482        let n = match ts {
2483            Value::Int(n) => n,
2484            _ => 0,
2485        };
2486        let dt = chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n);
2487        match dt {
2488            Some(t) => Value::Str(t.format(&format!("%Y{i}%m{i}%d", i = infix)).to_string()),
2489            None => Value::Null,
2490        }
2491    }
2492    /// `ymdhms(timestamp, infix=' ')` — UTC `YYYY-MM-DD<infix>HH:MM:SS`.
2493    pub fn ymdhms(&self, ts: Value, optional_args: &[Value]) -> Value {
2494        let infix = match optional_args.get(0) {
2495            Some(Value::Str(s)) => s.clone(),
2496            _ => " ".to_string(),
2497        };
2498        let n = match ts {
2499            Value::Int(n) => n,
2500            Value::Float(f) => f as i64,
2501            _ => 0,
2502        };
2503        let dt = chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n);
2504        match dt {
2505            Some(t) => Value::Str(t.format(&format!("%Y-%m-%d{infix}%H:%M:%S")).to_string()),
2506            None => Value::Null,
2507        }
2508    }
2509
2510    /// `rawencode(params, [doSeq])` — URL-encode without sorting.
2511    /// `rawencode(object)` — `qs.stringify(object, { encode: false })`:
2512    /// flat `key=value` pairs with no percent-encoding.
2513    pub fn rawencode(&self, params: Value, _optional_args: &[Value]) -> Value {
2514        let m = match &params {
2515            Value::Dict(m) => m,
2516            _ => return Value::Str(String::new()),
2517        };
2518        let pairs: Vec<String> = m
2519            .iter()
2520            .map(|(k, v)| format!("{}={}", k, stringify_param(v)))
2521            .collect();
2522        Value::Str(pairs.join("&"))
2523    }
2524
2525    /// `intToBase16(n)` — int → lowercase hex string.
2526    pub fn int_to_base16(&self, n: Value, _optional_args: &[Value]) -> Value {
2527        let v = match n {
2528            Value::Int(n) => n as u64,
2529            Value::Float(f) => f as u64,
2530            Value::Str(s) => s.parse::<u64>().unwrap_or(0),
2531            _ => 0,
2532        };
2533        Value::Str(format!("{:x}", v))
2534    }
2535
2536    /// `packb(action)` — MessagePack pack stub. Hyperliquid signs the
2537    /// packed bytes of an action. Returning empty bytes here is enough
2538    /// to make the call compile; live signing won't be correct.
2539    /// `packb(value)` — MessagePack-encode a Value into a byte array.
2540    pub fn packb(&self, action: Value, _optional_args: &[Value]) -> Value {
2541        fn to_rmpv(v: &Value) -> rmpv::Value {
2542            match v {
2543                Value::Null => rmpv::Value::Nil,
2544                Value::Bool(b) => rmpv::Value::Boolean(*b),
2545                Value::Int(i) => rmpv::Value::Integer((*i).into()),
2546                Value::Float(f) => rmpv::Value::F64(*f),
2547                Value::Str(s) => rmpv::Value::String(s.clone().into()),
2548                Value::Arr(a) => rmpv::Value::Array(a.iter().map(to_rmpv).collect()),
2549                Value::Dict(m) => rmpv::Value::Map(
2550                    m.iter()
2551                        .map(|(k, v)| (rmpv::Value::String(k.clone().into()), to_rmpv(v)))
2552                        .collect(),
2553                ),
2554            }
2555        }
2556        let mut buf: Vec<u8> = Vec::new();
2557        match rmpv::encode::write_value(&mut buf, &to_rmpv(&action)) {
2558            Ok(_) => Value::Array(buf.iter().map(|b| Value::Int(*b as i64)).collect()),
2559            Err(_) => Value::Null,
2560        }
2561    }
2562
2563    /// `ethEncodeStructuredData(domain, types, message)` — EIP-712
2564    /// encoding: returns the `\x19\x01 || domainSeparator || structHash`
2565    /// preimage that the caller keccak-hashes before signing.
2566    pub fn eth_encode_structured_data(&self, domain: Value, types: Value, message: Value) -> Value {
2567        let bytes = crate::exchange::eip712_encode(&domain, &types, &message);
2568        Value::Array(bytes.iter().map(|b| Value::Int(*b as i64)).collect())
2569    }
2570
2571    /// `uuid22()` — pseudo-random 22-char hex id.
2572    pub fn uuid22(&self, _optional_args: &[Value]) -> Value {
2573        Value::Str(random_hex(22))
2574    }
2575    /// `uuid16()` — pseudo-random 16-char hex id.
2576    pub fn uuid16(&self, _optional_args: &[Value]) -> Value {
2577        Value::Str(random_hex(16))
2578    }
2579    /// `uuid()` — pseudo-random UUID v4: `xxxxxxxx-xxxx-4xxx-[89ab]xxx-xxxxxxxxxxxx`.
2580    pub fn uuid(&self, _optional_args: &[Value]) -> Value {
2581        let h = random_hex(32);
2582        let variant = ['8', '9', 'a', 'b'][(random_u64() % 4) as usize];
2583        let s = format!(
2584            "{}-{}-4{}-{}{}-{}",
2585            &h[0..8],
2586            &h[8..12],
2587            &h[13..16],
2588            variant,
2589            &h[17..20],
2590            &h[20..32],
2591        );
2592        Value::Str(s)
2593    }
2594
2595    /// `urlencode(params)` — wraps the typed `urlencode_kv` for Value args.
2596    pub fn urlencode(&self, params: Value, _optional_args: &[Value]) -> Value {
2597        Value::Str(self.urlencode_kv(&params))
2598    }
2599
2600    /// `json(value)` — JSON-stringify.
2601    pub fn json(&self, v: Value) -> Value {
2602        Value::Str(self.json_str(&v))
2603    }
2604
2605    /// `encode(s)` — UTF-8 encode string to bytes (as Value::Array of ints).
2606    pub fn encode(&self, s: Value) -> Value {
2607        match s {
2608            Value::Str(s) => Value::Array(s.bytes().map(|b| Value::Int(b as i64)).collect()),
2609            _ => Value::Array(vec![]),
2610        }
2611    }
2612
2613    /// `decode(bytes)` — decode bytes to a UTF-8 string.
2614    pub fn decode(&self, b: Value) -> Value {
2615        match b {
2616            Value::Str(s) => Value::Str(s),
2617            Value::Arr(a) => {
2618                let bytes: Vec<u8> = a
2619                    .iter()
2620                    .filter_map(|v| match v {
2621                        Value::Int(n) => Some(*n as u8),
2622                        _ => None,
2623                    })
2624                    .collect();
2625                Value::Str(String::from_utf8_lossy(&bytes).to_string())
2626            }
2627            _ => Value::Str(String::new()),
2628        }
2629    }
2630
2631    /// `log(msg)` — debug print.
2632    pub fn log(&self, msg: Value) {
2633        if matches!(self.verbose, Value::Bool(true)) {
2634            println!("[ccxt] {}", crate::runtime::stringify_param(&msg));
2635        }
2636    }
2637
2638    // Dynamic dispatch for the implicit API (`public_get_exchange_info`, …)
2639    // now lives in the `ExchangeRuntime::call_method` trait method (review #1),
2640    // routing through `implicit_api_call` → `request_typed` → `fetch_typed`.
2641
2642    // ── string / number formatting ──────────────────────────────────────────
2643
2644    pub fn number_to_string(&self, n: Value) -> Value {
2645        // TS `numberToString(undefined)` returns undefined — don't
2646        // stringify a missing value into the literal "null".
2647        if matches!(n, Value::Null) {
2648            return Value::Null;
2649        }
2650        Value::Str(stringify_param(&n))
2651    }
2652
2653    pub fn parse_number(&self, v: Value, optional_args: &[Value]) -> Value {
2654        match v {
2655            Value::Float(_) | Value::Int(_) => v,
2656            Value::Str(ref s) => match s.parse::<f64>() {
2657                Ok(n) => Value::Float(n),
2658                Err(_) => arg_default(optional_args),
2659            },
2660            _ => arg_default(optional_args),
2661        }
2662    }
2663
2664    pub fn parse_timeframe(&self, tf: Value) -> Value {
2665        let s = stringify_param(&tf);
2666        let last = s.chars().last().unwrap_or('m');
2667        let num: i64 = s[..s.len().saturating_sub(1)].parse().unwrap_or(0);
2668        Value::Int(match last {
2669            's' => num,
2670            'm' => num * 60,
2671            'h' => num * 3600,
2672            'd' => num * 86400,
2673            'w' => num * 604800,
2674            'M' => num * 2592000,
2675            'y' => num * 31536000,
2676            _ => 0,
2677        })
2678    }
2679
2680    /// `precisionFromString(str)` — ports `functions/number.ts`.
2681    /// Scientific notation (`1e-4` → 4, `1e4` → -4); otherwise the
2682    /// number of fractional digits after stripping trailing zeros.
2683    pub fn precision_from_string(&self, s: Value) -> Value {
2684        let s = stringify_param(&s);
2685        if let Some(idx) = s.find(['e', 'E']) {
2686            let exp: i64 = s[idx + 1..].parse().unwrap_or(0);
2687            return Value::Int(-exp);
2688        }
2689        let trimmed = s.trim_end_matches('0');
2690        match trimmed.split_once('.') {
2691            Some((_, frac)) => Value::Int(frac.len() as i64),
2692            None => Value::Int(0),
2693        }
2694    }
2695
2696    /// `decimalToPrecision(n, roundingMode, numPrecisionDigits, [countingMode], [paddingMode])`
2697    /// — faithful port of `_decimalToPrecision` from `functions/number.ts`.
2698    pub fn decimal_to_precision(
2699        &self,
2700        n: Value,
2701        rounding: Value,
2702        precision: Value,
2703        optional_args: &[Value],
2704    ) -> Value {
2705        let n_s = stringify_param(&n);
2706        let prec_f: f64 = match &precision {
2707            Value::Int(i) => *i as f64,
2708            Value::Float(f) => *f,
2709            Value::Str(s) => s.parse().unwrap_or(f64::NAN),
2710            _ => return Value::Str(n_s),
2711        };
2712        let counting: i64 = match optional_args.get(0) {
2713            Some(Value::Int(c)) => *c,
2714            _ => crate::runtime::DECIMAL_PLACES,
2715        };
2716        let padding: i64 = match optional_args.get(1) {
2717            Some(Value::Int(p)) => *p,
2718            _ => crate::runtime::NO_PADDING,
2719        };
2720        let rounding_mode: i64 = match &rounding {
2721            Value::Int(r) => *r,
2722            _ => crate::runtime::TRUNCATE,
2723        };
2724        Value::Str(decimal_to_precision_impl(
2725            &n_s,
2726            rounding_mode,
2727            prec_f,
2728            counting,
2729            padding,
2730        ))
2731    }
2732
2733    pub fn capitalize(&self, s: Value) -> Value {
2734        let s = stringify_param(&s);
2735        let mut c = s.chars();
2736        Value::Str(match c.next() {
2737            None => String::new(),
2738            Some(f) => f.to_uppercase().chain(c).collect(),
2739        })
2740    }
2741
2742    pub fn encode_uri_component(&self, s: Value) -> Value {
2743        let s = stringify_param(&s);
2744        Value::Str(
2745            s.bytes()
2746                .map(|b| match b {
2747                    b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
2748                        (b as char).to_string()
2749                    }
2750                    _ => format!("%{b:02X}"),
2751                })
2752                .collect(),
2753        )
2754    }
2755
2756    pub fn string_to_chars_array(&self, s: Value) -> Value {
2757        let s = stringify_param(&s);
2758        Value::Array(s.chars().map(|c| Value::Str(c.to_string())).collect())
2759    }
2760
2761    pub fn string_to_base64(&self, s: Value, _optional_args: &[Value]) -> Value {
2762        self.binary_to_base64(s, &[])
2763    }
2764
2765    /// `extract_params(path)` — pulls `{name}` placeholders from a URL
2766    /// template. Returns a Value::Array of names.
2767    pub fn extract_params(&self, path: Value) -> Value {
2768        let p = stringify_param(&path);
2769        let mut out: Vec<Value> = vec![];
2770        let mut chars = p.chars().peekable();
2771        while let Some(c) = chars.next() {
2772            if c == '{' {
2773                let mut name = String::new();
2774                while let Some(&nc) = chars.peek() {
2775                    if nc == '}' {
2776                        chars.next();
2777                        break;
2778                    }
2779                    name.push(nc);
2780                    chars.next();
2781                }
2782                if !name.is_empty() {
2783                    out.push(Value::Str(name));
2784                }
2785            }
2786        }
2787        Value::Array(out)
2788    }
2789
2790    // ── async lifecycle stubs ───────────────────────────────────────────────
2791
2792    // Minimal port of TS `loadMarketsHelper`:
2793    //   1. Return the cached `markets` if already populated and not
2794    //      forcing a reload.
2795    //   2. If `has.fetchCurrencies === true`, dispatch `fetch_currencies`
2796    //      first — passing the result into `set_markets` avoids the
2797    //      O(N²) "synthesize from markets" branch (cloning the
2798    //      grouped-by-code Map inside an outer loop).
2799    //   3. Dispatch `fetch_markets` to the derived exchange.
2800    //   4. `set_markets(markets, currencies)` populates `markets`,
2801    //      `markets_by_id`, `symbols`, `ids`, and merges currencies.
2802    // Returns cached markets on hit; otherwise fetches markets (and
2803    // currencies when supported) and pushes everything through
2804    // `set_markets`. The built-in synthesize branch of `set_markets` is
2805    // O(N) per code with full Map clones —
2806    // for binance (~4k markets, ~1k unique codes) that grew to minutes
2807    // and looked like a hang. `load_markets_fast_synthesize_currencies`
2808    // below short-circuits when currencies are empty by synthesizing
2809    // them here in idiomatic Rust (HashMap-direct, no Value cloning of
2810    // the whole grouped map per code).
2811
2812    // Proxy callback "methods" — the post-processor rewrites
2813    // `self.proxy_url_callback(args)` → `self.proxy_url_callback_fn(args)`
2814    // so the field `proxy_url_callback: Value` can coexist with this
2815    // method-form for the call sites.
2816    pub fn proxy_fn(&self, _url: Value, _method: Value, _headers: Value, _body: Value) -> Value {
2817        self.proxy.clone()
2818    }
2819    pub fn proxy_url_callback_fn(
2820        &self,
2821        _url: Value,
2822        _method: Value,
2823        _headers: Value,
2824        _body: Value,
2825    ) -> Value {
2826        self.proxy_url_callback.clone()
2827    }
2828    pub fn http_proxy_callback_fn(
2829        &self,
2830        _url: Value,
2831        _method: Value,
2832        _headers: Value,
2833        _body: Value,
2834    ) -> Value {
2835        self.http_proxy_callback.clone()
2836    }
2837    pub fn https_proxy_callback_fn(
2838        &self,
2839        _url: Value,
2840        _method: Value,
2841        _headers: Value,
2842        _body: Value,
2843    ) -> Value {
2844        self.https_proxy_callback.clone()
2845    }
2846    pub fn socks_proxy_callback_fn(
2847        &self,
2848        _url: Value,
2849        _method: Value,
2850        _headers: Value,
2851        _body: Value,
2852    ) -> Value {
2853        self.socks_proxy_callback.clone()
2854    }
2855    pub fn ws_proxy_callback_fn(
2856        &self,
2857        _url: Value,
2858        _method: Value,
2859        _headers: Value,
2860        _body: Value,
2861    ) -> Value {
2862        Value::Null
2863    }
2864    pub fn wss_proxy_callback_fn(
2865        &self,
2866        _url: Value,
2867        _method: Value,
2868        _headers: Value,
2869        _body: Value,
2870    ) -> Value {
2871        Value::Null
2872    }
2873    pub fn ws_socks_proxy_callback_fn(
2874        &self,
2875        _url: Value,
2876        _method: Value,
2877        _headers: Value,
2878        _body: Value,
2879    ) -> Value {
2880        Value::Null
2881    }
2882
2883    pub fn init_throttler(&mut self) { /* stub */
2884    }
2885    /// Leaky-bucket rate limiter, mirroring `ts/src/base/functions/throttle.ts`.
2886    /// `rateLimit` is milliseconds-per-token, so `refillRate = 1/rateLimit`
2887    /// tokens/ms; `tokens` may go negative (a request proceeds when `tokens >= 0`
2888    /// and then subtracts its cost), and the next request waits until the bucket
2889    /// refills back to zero. State lives in `internals.throttle` behind an async
2890    /// mutex, so concurrent calls on one instance serialize (the TS single queue).
2891    /// A no-op when `enableRateLimit` is false or the rate is effectively
2892    /// unlimited.
2893    pub async fn throttle(&self, cost: &[Value]) -> Value {
2894        if !matches!(self.enableRateLimit, Value::Bool(true)) {
2895            return Value::Null;
2896        }
2897        let tb = |key: &str| -> Option<f64> {
2898            crate::get_value(&self.tokenBucket, &Value::Str(key.to_string())).as_f64()
2899        };
2900        let rate_limit = self.rateLimit.as_f64().unwrap_or(0.0);
2901        let refill_rate = tb("refillRate")
2902            .unwrap_or_else(|| if rate_limit > 0.0 { 1.0 / rate_limit } else { f64::MAX });
2903        if !(refill_rate.is_finite() && refill_rate > 0.0) {
2904            return Value::Null; // effectively unlimited
2905        }
2906        let capacity = tb("capacity").unwrap_or(1.0);
2907        let delay_ms = tb("delay").unwrap_or(0.001) * 1000.0;
2908        let this_cost = cost.first().and_then(|v| v.as_f64())
2909            .unwrap_or_else(|| tb("cost").unwrap_or(1.0));
2910
2911        let now_ms = || std::time::SystemTime::now()
2912            .duration_since(std::time::UNIX_EPOCH)
2913            .map(|d| d.as_millis() as i64)
2914            .unwrap_or(0);
2915
2916        let mut guard = self.internals.throttle.lock().await;
2917        let (tokens, last_ms) = &mut *guard;
2918        if *last_ms == 0 {
2919            *last_ms = now_ms();
2920        }
2921        // Refill for the elapsed time (capped at capacity).
2922        let n = now_ms();
2923        *tokens = (*tokens + refill_rate * (n - *last_ms).max(0) as f64).min(capacity);
2924        *last_ms = n;
2925        // In deficit → wait until the bucket refills to zero, holding the lock so
2926        // requests stay serialized.
2927        if *tokens < 0.0 {
2928            let wait = ((-*tokens) / refill_rate).max(delay_ms);
2929            tokio::time::sleep(std::time::Duration::from_millis(wait.ceil() as u64)).await;
2930            let n2 = now_ms();
2931            *tokens = (*tokens + refill_rate * (n2 - *last_ms).max(0) as f64).min(capacity);
2932            *last_ms = n2;
2933        }
2934        *tokens -= this_cost;
2935        Value::Null
2936    }
2937
2938    pub fn resolve<T>(&self, v: T) -> T {
2939        v
2940    }
2941    pub fn reject(&self, err: ExchangeError) -> ExchangeError {
2942        err
2943    }
2944}
2945
2946/// Synthesizes a `code → currency` map from a list of markets, mirroring
2947/// what `Exchange::set_markets`' else-branch does in TS — but in straight
2948/// Rust without re-cloning the grouped Map per outer iteration. For
2949/// binance (~4k markets, ~1k codes) the transpiled path took minutes;
2950/// this version completes in milliseconds.
2951pub(crate) fn synthesize_currencies_from_markets(markets: &Value, precision_mode: &Value) -> Value {
2952    let market_list: Vec<&Value> = match markets {
2953        Value::Arr(a) => a.iter().collect(),
2954        Value::Dict(m) => m.values().collect(),
2955        _ => return Value::Map(HashMap::new()),
2956    };
2957    let is_tick_size = matches!(precision_mode, Value::Int(n) if *n == crate::runtime::TICK_SIZE);
2958    let default_precision = if is_tick_size {
2959        Value::Float(1e-8)
2960    } else {
2961        Value::Int(8)
2962    };
2963
2964    // Helper to compare precision: tick size → smaller is more precise;
2965    // decimal places → larger is more precise.
2966    let more_precise = |new: &Value, cur: &Value| -> bool {
2967        let to_f = |v: &Value| -> f64 {
2968            match v {
2969                Value::Int(n) => *n as f64,
2970                Value::Float(f) => *f,
2971                Value::Str(s) => s.parse().unwrap_or(f64::NAN),
2972                _ => f64::NAN,
2973            }
2974        };
2975        let n = to_f(new);
2976        let c = to_f(cur);
2977        if n.is_nan() {
2978            return false;
2979        }
2980        if c.is_nan() {
2981            return true;
2982        }
2983        if is_tick_size {
2984            n < c
2985        } else {
2986            n > c
2987        }
2988    };
2989
2990    // Pull out the "code", "id", "precision" triple for each side. We
2991    // dedupe by code, keeping the most-precise instance.
2992    let mut by_code: HashMap<String, HashMap<String, Value>> = HashMap::new();
2993    for market in market_list {
2994        let market_precision = crate::get_value(market, &Value::Str("precision".to_string()));
2995        // base side
2996        for (id_key, code_key, prec_keys) in [
2997            ("baseId", "base", ["base", "amount"]),
2998            ("quoteId", "quote", ["quote", "price"]),
2999        ] {
3000            let code = crate::get_value(market, &Value::Str(code_key.to_string()));
3001            let code_s = match &code {
3002                Value::Str(s) if !s.is_empty() => s.clone(),
3003                _ => continue,
3004            };
3005            let id = crate::get_value(market, &Value::Str(id_key.to_string()));
3006            let id_v = match &id {
3007                Value::Null => Value::Str(code_s.clone()),
3008                other => other.clone(),
3009            };
3010            let mut precision =
3011                crate::get_value(&market_precision, &Value::Str(prec_keys[0].to_string()));
3012            if matches!(precision, Value::Null) {
3013                precision =
3014                    crate::get_value(&market_precision, &Value::Str(prec_keys[1].to_string()));
3015            }
3016            if matches!(precision, Value::Null) {
3017                precision = default_precision.clone();
3018            }
3019            let entry = by_code.entry(code_s.clone()).or_insert_with(|| {
3020                let mut m = HashMap::new();
3021                m.insert("id".to_string(), id_v.clone());
3022                m.insert("numericId".to_string(), Value::Null);
3023                m.insert("code".to_string(), Value::Str(code_s.clone()));
3024                m.insert("precision".to_string(), precision.clone());
3025                m
3026            });
3027            let existing_precision = entry.get("precision").cloned().unwrap_or(Value::Null);
3028            if more_precise(&precision, &existing_precision) {
3029                entry.insert("precision".to_string(), precision.clone());
3030            }
3031        }
3032    }
3033    let result: HashMap<String, Value> = by_code
3034        .into_iter()
3035        .map(|(k, v)| (k, Value::Map(v)))
3036        .collect();
3037    Value::Map(result)
3038}
3039
3040#[cfg(test)]
3041mod spawn_queue_tests {
3042    use super::*;
3043
3044    // `delay(ms, method, …)` schedules a coroutine on a real deadline —
3045    // binance's `keepAliveListenKey` re-arms itself every 20 min this way.
3046    // Regression cover for the original stub, which elided `ms` entirely and
3047    // ran the coroutine on the next inbound frame instead.
3048    #[test]
3049    fn delayed_spawns_wait_for_their_deadline() {
3050        // Not yet due: held back, and reported as the next deadline.
3051        enqueue_spawn_after("keep_alive_listen_key", vec![], 10_000);
3052        assert!(drain_spawn_queue().is_empty(), "not due yet");
3053        let due_in = next_spawn_due().expect("a deadline is pending");
3054        assert!(due_in > std::time::Duration::from_secs(9));
3055
3056        // An undelayed spawn still runs on the next drain, and does not
3057        // disturb the queued deadline.
3058        enqueue_spawn("handle_order_book_snapshot", vec![]);
3059        let batch = drain_spawn_queue();
3060        assert_eq!(batch.len(), 1);
3061        assert_eq!(batch[0].0, "handle_order_book_snapshot");
3062        assert!(next_spawn_due().is_some(), "the delayed item is still queued");
3063    }
3064
3065    #[test]
3066    fn spawns_run_once_their_deadline_passes() {
3067        enqueue_spawn_after("keep_alive_listen_key", vec![], 1);
3068        std::thread::sleep(std::time::Duration::from_millis(5));
3069        assert_eq!(next_spawn_due(), Some(std::time::Duration::ZERO));
3070        let batch = drain_spawn_queue();
3071        assert_eq!(batch.len(), 1);
3072        assert_eq!(batch[0].0, "keep_alive_listen_key");
3073        assert!(next_spawn_due().is_none(), "queue drained");
3074    }
3075}