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