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 extend_exchange_options(&self, _args: &[Value]) -> Value {
1046        Value::Null
1047    }
1048    pub fn on_error(&self, _args: &[Value]) -> Value {
1049        Value::Null
1050    }
1051    pub fn on_close(&self, _args: &[Value]) -> Value {
1052        Value::Null
1053    }
1054    pub fn on_pong(&self, _args: &[Value]) -> Value {
1055        Value::Null
1056    }
1057    /// CRC-32 checksum — used by a few WS order-book reconcilers
1058    /// (bitget, bitfinex, independentreserve). Stub returns 0; will be
1059    /// replaced with the real algorithm when those order books need it.
1060    pub fn crc32(&self, args: &[Value]) -> Value {
1061        let payload = args.get(0).cloned().unwrap_or(Value::Str(String::new()));
1062        let signed = args.get(1).cloned().unwrap_or(Value::Bool(false));
1063        crate::runtime::crc32(payload, signed)
1064    }
1065    /// `decode_proto_msg(message)` — exchange-specific protobuf decoder
1066    /// (mexc). `message` is the binary frame carried as a byte array; decode
1067    /// it into mexc's `PushDataV3ApiWrapper` shape (matching protobufjs
1068    /// `.toJSON()`) so the ported handlers consume it unchanged.
1069    pub fn decode_proto_msg(&self, args: &[Value]) -> Value {
1070        match args.get(0) {
1071            Some(v) if is_byte_array(v) => {
1072                let bytes = crate::exchange::value_to_bytes(v);
1073                crate::runtime::decode_mexc_push_data(&bytes)
1074            }
1075            Some(v) => v.clone(),
1076            None => Value::Null,
1077        }
1078    }
1079    /// `loadOrderBook` — WS helper used by some bookkeeping methods.
1080    /// Stubbed identically to the unwatch flow.
1081    pub async fn load_order_book(&mut self, _args: &[Value]) -> Value {
1082        Value::Null
1083    }
1084
1085    // ── hand-written base helpers ──────────────────────────────────────────
1086    // These live above the `METHODS BELOW THIS LINE ARE TRANSPILED` marker in
1087    // ts/src/base/Exchange.ts, so they are language-specific hand-written code
1088    // rather than transpiled into exchange_generated.rs.
1089
1090    /// `remove0xPrefix(hexData)` — strips a leading `0x`/`0X` if present.
1091    pub fn remove0x_prefix(&self, hex_data: Value) -> Value {
1092        match &hex_data {
1093            Value::Str(s) if s.len() >= 2 && (&s[0..2] == "0x" || &s[0..2] == "0X") => {
1094                Value::Str(s[2..].to_string())
1095            }
1096            _ => hex_data,
1097        }
1098    }
1099
1100    /// `checkRequiredDependencies()` — a no-op in Rust; all crypto deps are
1101    /// compiled in.
1102    pub fn check_required_dependencies(&self) -> Value {
1103        Value::Null
1104    }
1105
1106    /// `randNumber(size)` — a random integer with `size` decimal digits.
1107    pub fn rand_number(&self, size: Value) -> Value {
1108        use rand::Rng;
1109        let n = size.as_i64().unwrap_or(0).max(0) as usize;
1110        let mut rng = rand::thread_rng();
1111        let mut s = String::new();
1112        for _ in 0..n {
1113            s.push(char::from(b'0' + rng.gen_range(0..10u8)));
1114        }
1115        Value::Int(s.parse::<i64>().unwrap_or(0))
1116    }
1117
1118    /// `randomBytes(length)` — `length` random bytes as a hex string.
1119    pub fn random_bytes(&self, length: Value) -> Value {
1120        use rand::Rng;
1121        let n = length.as_i64().unwrap_or(0).max(0) as usize;
1122        let mut rng = rand::thread_rng();
1123        let bytes: Vec<u8> = (0..n).map(|_| rng.gen()).collect();
1124        Value::Str(hex::encode(bytes))
1125    }
1126
1127    /// `convertToBigInt(value)` — the Value-bag has no distinct bigint type,
1128    /// so coerce to a 64-bit integer.
1129    pub fn convert_to_big_int(&self, value: Value) -> Value {
1130        match &value {
1131            Value::Int(_) => value,
1132            Value::Float(f) => Value::Int(*f as i64),
1133            Value::Str(s) => {
1134                let t = s.trim();
1135                // A uint256 (e.g. polymarket tokenId) overflows i64; keep the
1136                // decimal/0x-hex string so downstream big-int consumers
1137                // (eth_abi_encode) encode the full value instead of truncating.
1138                match t.parse::<i64>() {
1139                    Ok(n) => Value::Int(n),
1140                    Err(_) => Value::Str(t.to_string()),
1141                }
1142            }
1143            _ => Value::Int(0),
1144        }
1145    }
1146
1147    /// `fixStringifiedJsonMembers(content)` — un-escapes a JSON string whose
1148    /// members are themselves stringified JSON (used by bingx).
1149    pub fn fix_stringified_json_members(&self, content: Value) -> Value {
1150        match &content {
1151            Value::Str(s) => Value::Str(
1152                s.replace('\\', "")
1153                    .replace("\"{", "{")
1154                    .replace("}\"", "}")
1155                    .replace("\"[", "[")
1156                    .replace("]\"", "]"),
1157            ),
1158            _ => content,
1159        }
1160    }
1161
1162    /// `binaryConcatArray(arrayOfChunks)` — concatenates hex-string chunks.
1163    pub fn binary_concat_array(&self, arr: Value) -> Value {
1164        let mut out = String::new();
1165        if let Value::Arr(items) = &arr {
1166            for it in items.iter() {
1167                if let Value::Str(s) = it {
1168                    out.push_str(s);
1169                }
1170            }
1171        }
1172        Value::Str(out)
1173    }
1174
1175    /// `uuid5(namespace, name)` — RFC-4122 v5 (SHA-1 based) UUID.
1176    pub fn uuid5(&self, namespace: Value, name: Value) -> Value {
1177        use sha1::{Digest, Sha1};
1178        let ns = namespace.as_str().unwrap_or("").replace('-', "");
1179        let mut data: Vec<u8> = Vec::new();
1180        let mut i = 0;
1181        while i + 1 < ns.len() {
1182            if let Ok(b) = u8::from_str_radix(&ns[i..i + 2], 16) {
1183                data.push(b);
1184            }
1185            i += 2;
1186        }
1187        data.extend_from_slice(name.as_str().unwrap_or("").as_bytes());
1188        let mut hasher = Sha1::new();
1189        hasher.update(&data);
1190        let mut hash = hasher.finalize().to_vec();
1191        hash[6] = (hash[6] & 0x0f) | 0x50;
1192        hash[8] = (hash[8] & 0x3f) | 0x80;
1193        let h = hex::encode(&hash[0..16]);
1194        Value::Str(format!(
1195            "{}-{}-{}-{}-{}",
1196            &h[0..8],
1197            &h[8..12],
1198            &h[12..16],
1199            &h[16..20],
1200            &h[20..32]
1201        ))
1202    }
1203
1204    /// `ethAbiEncode(types, values)` — Solidity `abi.encode` of a head-only
1205    /// (all-static) tuple: every element becomes one 32-byte word. Supports the
1206    /// static types the callers use (address, bytesN, uint*/int*, bool). Dynamic
1207    /// types (`bytes`, `string`, arrays) are not needed (polymarket ERC-7739) and
1208    /// return Null. Values arrive as: bytesN → binary `Value::Arr` (or 0x-hex
1209    /// string); uint/int → `Value::Int` or a decimal/0x-hex string (big uint256
1210    /// like tokenId exceed i64, so string form is preserved by convert_to_big_int);
1211    /// address → 0x-hex string. Result is a binary `Value::Arr` that `hash(...)`
1212    /// consumes via value_to_bytes.
1213    pub fn eth_abi_encode(&self, types: Value, values: Value) -> Value {
1214        use num_bigint::BigInt;
1215        let ts: Vec<Value> = match &types {
1216            Value::Arr(a) => (**a).clone(),
1217            _ => return Value::Null,
1218        };
1219        let vs: Vec<Value> = match &values {
1220            Value::Arr(a) => (**a).clone(),
1221            _ => return Value::Null,
1222        };
1223        let to_bytes = |v: &Value| -> Vec<u8> {
1224            match v {
1225                Value::Arr(a) => a
1226                    .iter()
1227                    .filter_map(|x| {
1228                        if let Value::Int(n) = x {
1229                            Some(*n as u8)
1230                        } else {
1231                            None
1232                        }
1233                    })
1234                    .collect(),
1235                Value::Str(s) => hex::decode(s.trim_start_matches("0x")).unwrap_or_default(),
1236                _ => Vec::new(),
1237            }
1238        };
1239        let to_bigint = |v: &Value| -> BigInt {
1240            match v {
1241                Value::Int(n) => BigInt::from(*n),
1242                Value::Float(f) => BigInt::from(*f as i64),
1243                Value::Str(s) => {
1244                    let t = s.trim();
1245                    if let Some(h) = t.strip_prefix("0x") {
1246                        BigInt::parse_bytes(h.as_bytes(), 16).unwrap_or_default()
1247                    } else {
1248                        BigInt::parse_bytes(t.as_bytes(), 10).unwrap_or_default()
1249                    }
1250                }
1251                _ => BigInt::from(0),
1252            }
1253        };
1254        let mut out: Vec<u8> = Vec::new();
1255        for (t, v) in ts.iter().zip(vs.iter()) {
1256            let ty = match t {
1257                Value::Str(s) => s.as_str(),
1258                _ => return Value::Null,
1259            };
1260            let mut word = [0u8; 32];
1261            if ty == "address" {
1262                let b = to_bytes(v);
1263                let n = b.len().min(20);
1264                word[32 - n..].copy_from_slice(&b[b.len() - n..]);
1265            } else if ty.starts_with("bytes") && ty != "bytes" {
1266                // fixed bytesN — left-aligned
1267                let b = to_bytes(v);
1268                let n = b.len().min(32);
1269                word[..n].copy_from_slice(&b[..n]);
1270            } else if ty.starts_with("uint") || ty.starts_with("int") {
1271                // uintN/intN — validate the declared bit width, reject
1272                // negative-for-unsigned / overflow, then encode (review #15).
1273                word = crate::exchange::eip712_int_word(ty, &to_bigint(v));
1274            } else if ty == "bool" {
1275                if matches!(v, Value::Bool(true)) {
1276                    word[31] = 1;
1277                }
1278            } else {
1279                return Value::Null; // unsupported (dynamic) type
1280            }
1281            out.extend_from_slice(&word);
1282        }
1283        Value::Array(out.into_iter().map(|b| Value::Int(b as i64)).collect())
1284    }
1285
1286    /// `setProperty(this, key, value)` — dynamic field setter. The typed
1287    /// `Exchange` struct has no Value-shaped dynamic field store, so this
1288    /// is currently a no-op (the receiver arg is dropped by the transpiler).
1289    pub fn set_property(&self, _property: Value, _optional_args: &[Value]) -> Value {
1290        Value::Null
1291    }
1292
1293    // ── exchange-specific signing helpers (above-the-marker base methods) ──
1294    // These wrap heavy crypto (curve25519, StarkNet, dydx protobuf, lighter
1295    // zk-proofs) that has not yet been ported to Rust. The terminal
1296    // signature-producing methods fail loudly with NotSupported rather than
1297    // returning a null/empty signature — an unsigned request silently sent to an
1298    // exchange is worse than an explicit error (review #4). The static request
1299    // fixtures mark the affected private cases `disabledRS`, as Go/Java do.
1300
1301    /// Fail loudly for an unported crypto/signing primitive. Diverges (`-> !`),
1302    /// so it satisfies any `-> Value` stub body.
1303    fn crypto_not_supported(&self, what: &str) -> ! {
1304        let id = match &self.id {
1305            Value::Str(s) => s.clone(),
1306            _ => String::new(),
1307        };
1308        panic!(
1309            "{}",
1310            crate::exchange_errors::not_supported(Value::Str(format!(
1311                "{id} {what}() signing is not implemented in the Rust port yet"
1312            ),))
1313        );
1314    }
1315
1316    /// `axolotl(payload, hexKey, ed25519)` — curve25519 signing (waves).
1317    pub fn axolotl(&self, _payload: Value, _hex_key: Value, _ed25519: Value) -> Value {
1318        self.crypto_not_supported("axolotl")
1319    }
1320
1321    /// `retrieveStarkAccount(signature, accountClassHash, accountProxyClassHash)`.
1322    pub fn retrieve_stark_account(
1323        &self,
1324        _signature: Value,
1325        _class_hash: Value,
1326        _proxy_hash: Value,
1327    ) -> Value {
1328        Value::Null
1329    }
1330
1331    /// `starknetEncodeStructuredData(domain, messageTypes, messageData, address)`.
1332    pub fn starknet_encode_structured_data(
1333        &self,
1334        _domain: Value,
1335        _types: Value,
1336        _data: Value,
1337        _address: Value,
1338    ) -> Value {
1339        Value::Null
1340    }
1341
1342    /// `starknetSign(msgHash, pri)`.
1343    pub fn starknet_sign(&self, _msg_hash: Value, _pri: Value) -> Value {
1344        self.crypto_not_supported("starknetSign")
1345    }
1346
1347    /// `extendedStarknetSign(msgHash, pri)` — starknet-curve signing for the
1348    /// `extended` exchange. Stub: starknet crypto (poseidon/stark-curve) is
1349    /// not ported to Rust yet, matching `starknet_sign` above.
1350    pub fn extended_starknet_sign(&self, _msg_hash: Value, _pri: Value) -> Value {
1351        self.crypto_not_supported("extendedStarknetSign")
1352    }
1353
1354    /// `extendedStarknetGetSelectorFromName(name)`.
1355    pub fn extended_starknet_get_selector_from_name(&self, _name: Value) -> Value {
1356        Value::Null
1357    }
1358
1359    /// `extendedStarknetComputePoseidonHashOnElements(data)`.
1360    pub fn extended_starknet_compute_poseidon_hash_on_elements(&self, _data: Value) -> Value {
1361        Value::Null
1362    }
1363
1364    /// `toDydxLong(numStr)`.
1365    pub fn to_dydx_long(&self, _num_str: Value) -> Value {
1366        Value::Null
1367    }
1368
1369    /// `retrieveDydxCredentials(entropy)`.
1370    pub fn retrieve_dydx_credentials(&self, _entropy: Value) -> Value {
1371        Value::Null
1372    }
1373
1374    /// `loadDydxProtos()`.
1375    pub async fn load_dydx_protos(&self) -> Value {
1376        Value::Null
1377    }
1378
1379    /// `encodeDydxTxRaw(signDoc, signature)`.
1380    pub fn encode_dydx_tx_raw(&self, _sign_doc: Value, _signature: Value) -> Value {
1381        self.crypto_not_supported("encodeDydxTxRaw")
1382    }
1383
1384    /// `encodeDydxTxForSimulation(message, memo, sequence, publicKey)`.
1385    pub fn encode_dydx_tx_for_simulation(
1386        &self,
1387        _message: Value,
1388        _memo: Value,
1389        _sequence: Value,
1390        _public_key: Value,
1391    ) -> Value {
1392        Value::Null
1393    }
1394
1395    /// `encodeDydxTxForSigning(message, memo, chainId, account, authenticators, fee?)`.
1396    pub fn encode_dydx_tx_for_signing(
1397        &self,
1398        _message: Value,
1399        _memo: Value,
1400        _chain_id: Value,
1401        _account: Value,
1402        _authenticators: Value,
1403        _optional_args: &[Value],
1404    ) -> Value {
1405        Value::Null
1406    }
1407
1408    /// `loadLighterLibrary(libraryPath, chainId, privateKey, apiKeyIndex, accountIndex, createClient?)`.
1409    pub async fn load_lighter_library(
1410        &self,
1411        _library_path: Value,
1412        _chain_id: Value,
1413        _private_key: Value,
1414        _api_key_index: Value,
1415        _account_index: Value,
1416        _optional_args: &[Value],
1417    ) -> Value {
1418        Value::Null
1419    }
1420
1421    /// `lighterCreateClient(signer, chainId, privateKey, apiKeyIndex, accountIndex)`.
1422    pub fn lighter_create_client(
1423        &self,
1424        _signer: Value,
1425        _chain_id: Value,
1426        _private_key: Value,
1427        _api_key_index: Value,
1428        _account_index: Value,
1429    ) -> Value {
1430        Value::Null
1431    }
1432
1433    /// `lighterGenerateApiKey(signer)`.
1434    pub fn lighter_generate_api_key(&self, _signer: Value) -> Value {
1435        self.crypto_not_supported("lighterGenerateApiKey")
1436    }
1437
1438    /// `getZKTransferSignatureObj(seeds, order)` — apex StarkEx signing.
1439    pub async fn get_zk_transfer_signature_obj(
1440        &self,
1441        _seeds: Value,
1442        _optional_args: &[Value],
1443    ) -> Value {
1444        self.crypto_not_supported("getZKTransferSignatureObj")
1445    }
1446
1447    /// `getZKContractSignatureObj(seeds, order)` — apex StarkEx signing.
1448    pub async fn get_zk_contract_signature_obj(
1449        &self,
1450        _seeds: Value,
1451        _optional_args: &[Value],
1452    ) -> Value {
1453        self.crypto_not_supported("getZKContractSignatureObj")
1454    }
1455
1456    /// `futuresTransfer(code, amount, type, params?)` — binance futures
1457    /// wallet transfer; inherited by binancecoinm / binanceusdm.
1458    pub async fn futures_transfer(
1459        &self,
1460        _code: Value,
1461        _amount: Value,
1462        _transfer_type: Value,
1463        _optional_args: &[Value],
1464    ) -> Value {
1465        Value::Null
1466    }
1467
1468    /// `lighterSign*(signer, request)` — lighter zk-proof signing helpers.
1469    pub fn lighter_sign_create_order(&self, _signer: Value, _request: Value) -> Value {
1470        self.crypto_not_supported("lighterSignCreateOrder")
1471    }
1472    pub fn lighter_sign_create_grouped_orders(&self, _signer: Value, _request: Value) -> Value {
1473        self.crypto_not_supported("lighterSignCreateGroupedOrders")
1474    }
1475    pub fn lighter_sign_cancel_order(&self, _signer: Value, _request: Value) -> Value {
1476        self.crypto_not_supported("lighterSignCancelOrder")
1477    }
1478    pub fn lighter_sign_cancel_all_orders(&self, _signer: Value, _request: Value) -> Value {
1479        self.crypto_not_supported("lighterSignCancelAllOrders")
1480    }
1481    pub fn lighter_sign_withdraw(&self, _signer: Value, _request: Value) -> Value {
1482        self.crypto_not_supported("lighterSignWithdraw")
1483    }
1484    pub fn lighter_sign_create_sub_account(&self, _signer: Value, _request: Value) -> Value {
1485        self.crypto_not_supported("lighterSignCreateSubAccount")
1486    }
1487    pub fn lighter_sign_modify_order(&self, _signer: Value, _request: Value) -> Value {
1488        self.crypto_not_supported("lighterSignModifyOrder")
1489    }
1490    pub fn lighter_sign_transfer(&self, _signer: Value, _request: Value) -> Value {
1491        self.crypto_not_supported("lighterSignTransfer")
1492    }
1493    pub fn lighter_sign_update_leverage(&self, _signer: Value, _request: Value) -> Value {
1494        self.crypto_not_supported("lighterSignUpdateLeverage")
1495    }
1496    pub fn lighter_sign_update_margin(&self, _signer: Value, _request: Value) -> Value {
1497        self.crypto_not_supported("lighterSignUpdateMargin")
1498    }
1499    pub fn lighter_sign_approve_integrator(&self, _signer: Value, _request: Value) -> Value {
1500        self.crypto_not_supported("lighterSignApproveIntegrator")
1501    }
1502    pub fn lighter_sign_change_pubkey(&self, _signer: Value, _request: Value) -> Value {
1503        self.crypto_not_supported("lighterSignChangePubkey")
1504    }
1505    pub fn lighter_create_auth_token(&self, _signer: Value, _request: Value) -> Value {
1506        self.crypto_not_supported("lighterCreateAuthToken")
1507    }
1508
1509    /// `urlencodeWithArrayRepeat(params)` — `qs.stringify(object, { arrayFormat: 'repeat' })`:
1510    /// array values repeat the key (`a=1&a=2`); scalars encode normally.
1511    pub fn urlencode_with_array_repeat(&self, params: Value) -> Value {
1512        let m = match &params {
1513            Value::Dict(m) => m,
1514            _ => return Value::Str(String::new()),
1515        };
1516        let mut pairs: Vec<String> = Vec::new();
1517        for (k, v) in m.iter() {
1518            let key = crate::exchange::url_pct(k);
1519            match v {
1520                Value::Arr(items) => {
1521                    for item in items.iter() {
1522                        pairs.push(format!(
1523                            "{}={}",
1524                            key,
1525                            crate::exchange::url_pct(&stringify_param(item))
1526                        ));
1527                    }
1528                }
1529                other => {
1530                    pairs.push(format!(
1531                        "{}={}",
1532                        key,
1533                        crate::exchange::url_pct(&stringify_param(other))
1534                    ));
1535                }
1536            }
1537        }
1538        Value::Str(pairs.join("&"))
1539    }
1540
1541    pub fn safe_integer(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
1542        let v = self.safe_value(obj, key, &[]);
1543        match v {
1544            Value::Int(_) => v,
1545            Value::Float(f) => Value::Int(f as i64),
1546            // CCXT `safeInteger` is parseInt-style: a decimal string like
1547            // "3.33" truncates to 3 (arkham leverage tiers), not null. Try
1548            // an exact i64 first, then fall back to f64 → truncate.
1549            Value::Str(s) => match s.parse::<i64>() {
1550                Ok(n) => Value::Int(n),
1551                Err(_) => match s.parse::<f64>() {
1552                    Ok(f) if f.is_finite() => Value::Int(f as i64),
1553                    _ => arg_default(optional_args),
1554                },
1555            },
1556            _ => arg_default(optional_args),
1557        }
1558    }
1559
1560    pub fn safe_integer2(
1561        &self,
1562        obj: Value,
1563        k1: Value,
1564        k2: Value,
1565        optional_args: &[Value],
1566    ) -> Value {
1567        let v = self.safe_integer(obj.clone(), k1, &[]);
1568        if !v.is_null() {
1569            return v;
1570        }
1571        let v = self.safe_integer(obj, k2, &[]);
1572        if !v.is_null() {
1573            v
1574        } else {
1575            arg_default(optional_args)
1576        }
1577    }
1578
1579    pub fn safe_integer_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
1580        if let Value::Arr(ks) = keys {
1581            for k in ks.iter().cloned() {
1582                let v = self.safe_integer(obj.clone(), k, &[]);
1583                if !v.is_null() {
1584                    return v;
1585                }
1586            }
1587        }
1588        arg_default(optional_args)
1589    }
1590
1591    /// Reads `obj[key]` as a number, multiplies by `factor`, and casts
1592    /// to i64. Used to convert seconds → milliseconds for timestamps.
1593    pub fn safe_integer_product(
1594        &self,
1595        obj: Value,
1596        key: Value,
1597        factor: Value,
1598        optional_args: &[Value],
1599    ) -> Value {
1600        let v = self.safe_value(obj, key, &[]);
1601        let n = match v {
1602            Value::Int(n) => Some(n as f64),
1603            Value::Float(f) => Some(f),
1604            Value::Str(s) => s.parse::<f64>().ok(),
1605            _ => None,
1606        };
1607        let f = match factor {
1608            Value::Int(n) => n as f64,
1609            Value::Float(f) => f,
1610            _ => return arg_default(optional_args),
1611        };
1612        match n {
1613            Some(x) => Value::Int((x * f) as i64),
1614            None => arg_default(optional_args),
1615        }
1616    }
1617
1618    pub fn safe_integer_product2(
1619        &self,
1620        obj: Value,
1621        k1: Value,
1622        k2: Value,
1623        factor: Value,
1624        optional_args: &[Value],
1625    ) -> Value {
1626        let v = self.safe_integer_product(obj.clone(), k1, factor.clone(), &[]);
1627        if !v.is_null() {
1628            return v;
1629        }
1630        let v = self.safe_integer_product(obj, k2, factor, &[]);
1631        if !v.is_null() {
1632            v
1633        } else {
1634            arg_default(optional_args)
1635        }
1636    }
1637
1638    pub fn safe_integer_product_n(
1639        &self,
1640        obj: Value,
1641        keys: Value,
1642        factor: Value,
1643        optional_args: &[Value],
1644    ) -> Value {
1645        if let Value::Arr(ks) = keys {
1646            for k in ks.iter().cloned() {
1647                let v = self.safe_integer_product(obj.clone(), k, factor.clone(), &[]);
1648                if !v.is_null() {
1649                    return v;
1650                }
1651            }
1652        }
1653        arg_default(optional_args)
1654    }
1655
1656    pub fn safe_timestamp2(
1657        &self,
1658        obj: Value,
1659        k1: Value,
1660        k2: Value,
1661        optional_args: &[Value],
1662    ) -> Value {
1663        self.safe_integer_product2(obj, k1, k2, Value::Int(1000), optional_args)
1664    }
1665
1666    pub fn safe_timestamp_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
1667        self.safe_integer_product_n(obj, keys, Value::Int(1000), optional_args)
1668    }
1669
1670    pub fn safe_float(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
1671        let v = self.safe_value(obj, key, &[]);
1672        match v {
1673            Value::Float(_) => v,
1674            Value::Int(n) => Value::Float(n as f64),
1675            Value::Str(s) => match s.parse::<f64>() {
1676                Ok(n) => Value::Float(n),
1677                Err(_) => arg_default(optional_args),
1678            },
1679            _ => arg_default(optional_args),
1680        }
1681    }
1682
1683    /// `safeTimestamp(o, k)` — `parseInt(asFloat(value) * 1000)`. The
1684    /// value is read as a float (seconds, possibly fractional) and
1685    /// converted to integer milliseconds.
1686    pub fn safe_timestamp(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
1687        match self.safe_float(obj, key, &[]) {
1688            Value::Float(f) => Value::Int((f * 1000.0) as i64),
1689            Value::Int(n) => Value::Int(n * 1000),
1690            _ => arg_default(optional_args),
1691        }
1692    }
1693
1694    /// `isEmpty(value)` — true when an array/dict is empty, or the
1695    /// value is null/undefined. Scalars (strings, numbers, bools) are
1696    /// never considered empty — mirrors `functions/generic.ts`.
1697    pub fn is_empty(&self, v: Value) -> Value {
1698        let empty = match &v {
1699            Value::Null => true,
1700            Value::Arr(a) => a.is_empty(),
1701            Value::Dict(m) => m.is_empty(),
1702            _ => false,
1703        };
1704        Value::Bool(empty)
1705    }
1706
1707    pub fn value_is_defined(&self, v: Value) -> Value {
1708        Value::Bool(!v.is_null())
1709    }
1710
1711    // ── extend / deep_extend / omit ─────────────────────────────────────────
1712
1713    pub fn extend(&self, a: Value, optional_args: &[Value]) -> Value {
1714        let mut out = match a {
1715            Value::Dict(m) => Arc::try_unwrap(m).unwrap_or_else(|x| (*x).clone()),
1716            _ => HashMap::new(),
1717        };
1718        let merge = |out: &mut HashMap<String, Value>, src: Value| {
1719            if let Value::Dict(m) = src {
1720                let m = Arc::try_unwrap(m).unwrap_or_else(|x| (*x).clone());
1721                for (k, v) in m {
1722                    out.insert(k, v);
1723                }
1724            }
1725        };
1726        for extra in optional_args {
1727            merge(&mut out, extra.clone());
1728        }
1729        Value::Map(out)
1730    }
1731
1732    pub fn deep_extend(&self, a: Value, optional_args: &[Value]) -> Value {
1733        let mut current = a;
1734        for extra in optional_args {
1735            current = crate::value::deep_extend(current, extra.clone());
1736        }
1737        current
1738    }
1739
1740    pub fn omit(&self, obj: Value, keys: Value, _optional_args: &[Value]) -> Value {
1741        match obj {
1742            Value::Dict(mut m) => {
1743                let mm = Arc::make_mut(&mut m);
1744                match keys {
1745                    Value::Arr(ks) => {
1746                        for k in ks.iter() {
1747                            if let Value::Str(s) = k {
1748                                mm.shift_remove(s);
1749                            }
1750                        }
1751                    }
1752                    Value::Str(s) => {
1753                        mm.shift_remove(&s);
1754                    }
1755                    _ => {}
1756                }
1757                Value::Dict(m)
1758            }
1759            other => other,
1760        }
1761    }
1762
1763    pub fn omit_zero(&self, v: Value) -> Value {
1764        // Mirrors TS `omitZero`: undefined/'' or any value that parses to
1765        // numeric 0 → undefined. The old `s == "0"` check missed "0.0",
1766        // "0.00", "0e0" etc. — e.g. gate echoes `gt_fee:"0.0"`, and
1767        // keeping it as a non-null fee left `safeTrade` with 3 fee
1768        // entries (so it couldn't collapse to a single `fee`).
1769        match &v {
1770            Value::Int(0) => Value::Null,
1771            Value::Float(f) if *f == 0.0 => Value::Null,
1772            Value::Str(s) => {
1773                if s.is_empty() {
1774                    return Value::Null;
1775                }
1776                match s.parse::<f64>() {
1777                    Ok(n) if n == 0.0 => Value::Null,
1778                    _ => v,
1779                }
1780            }
1781            _ => v,
1782        }
1783    }
1784
1785    // ── array / object utilities ────────────────────────────────────────────
1786
1787    pub fn to_array(&self, v: Value) -> Value {
1788        // A WS cache (ArrayCache / order-book cache) keeps its entries in `_data`
1789        // or the shared cache registry, not the dict's meta fields — surface
1790        // those, else `to_array` would leak `__cacheKind`/counters/flags as rows.
1791        if let Some(entries) = crate::value::cache_entries_as_value(&v) {
1792            return entries;
1793        }
1794        match v {
1795            Value::Arr(_) => v,
1796            Value::Dict(m) => Value::Array(m.values().cloned().collect()),
1797            Value::Null => Value::Array(vec![]),
1798            other => Value::Array(vec![other]),
1799        }
1800    }
1801
1802    pub fn array_concat(&self, a: Value, b: Value) -> Value {
1803        crate::runtime::concat_arrays(&a, &b)
1804    }
1805
1806    pub fn array_slice(&self, v: Value, start: Value, optional_args: &[Value]) -> Value {
1807        let Value::Arr(a) = v else {
1808            return Value::Array(vec![]);
1809        };
1810        let len = a.len() as i64;
1811        let s = match start {
1812            Value::Int(n) => n,
1813            _ => 0,
1814        };
1815        let s = if s < 0 {
1816            (len + s).max(0) as usize
1817        } else {
1818            (s as usize).min(a.len())
1819        };
1820        let e = match optional_args.get(0) {
1821            None | Some(Value::Null) => a.len(),
1822            Some(Value::Int(n)) => {
1823                if *n < 0 {
1824                    ((len) + n).max(0) as usize
1825                } else {
1826                    (*n as usize).min(a.len())
1827                }
1828            }
1829            _ => a.len(),
1830        };
1831        if s <= e {
1832            Value::Array(a[s..e].to_vec())
1833        } else {
1834            Value::Array(vec![])
1835        }
1836    }
1837
1838    pub fn in_array(&self, needle: Value, haystack: Value) -> Value {
1839        let hit = if let Value::Arr(a) = haystack {
1840            a.iter().any(|x| crate::runtime::is_equal(x, &needle))
1841        } else {
1842            false
1843        };
1844        Value::Bool(hit)
1845    }
1846
1847    pub fn unique(&self, v: Value) -> Value {
1848        if let Value::Arr(a) = v {
1849            let mut out: Vec<Value> = vec![];
1850            for item in a.iter().cloned() {
1851                if !out.iter().any(|x| crate::runtime::is_equal(x, &item)) {
1852                    out.push(item);
1853                }
1854            }
1855            Value::Array(out)
1856        } else {
1857            Value::Array(vec![])
1858        }
1859    }
1860
1861    pub fn index_by(&self, arr: Value, key: Value) -> Value {
1862        let k = key_str(&key);
1863        let mut out: HashMap<String, Value> = HashMap::new();
1864        // TS `indexBy` accepts an array OR an object — for an object it
1865        // iterates `Object.values`. okx's parseDepositAddress relies on
1866        // this: `indexBy(currency['networks'], 'id')` where `networks` is
1867        // a dict keyed by network code. Array-only would return {} and
1868        // collapse every parsed address to a null network.
1869        let items: Vec<Value> = match arr {
1870            Value::Arr(items) => Arc::try_unwrap(items).unwrap_or_else(|a| (*a).clone()),
1871            Value::Dict(m) => m.values().cloned().collect(),
1872            _ => return Value::Map(out),
1873        };
1874        for item in items {
1875            if let Some(kv) = crate::value::safe_string(&item, &k, None) {
1876                out.insert(kv, item);
1877            }
1878        }
1879        Value::Map(out)
1880    }
1881
1882    pub fn index_by_safe(&self, arr: Value, key: Value) -> Value {
1883        self.index_by(arr, key)
1884    }
1885
1886    pub fn group_by(&self, arr: Value, key: Value, _optional_args: &[Value]) -> Value {
1887        let k = key_str(&key);
1888        let mut out: HashMap<String, Vec<Value>> = HashMap::new();
1889        if let Value::Arr(items) = arr {
1890            for item in items.iter().cloned() {
1891                if let Some(kv) = crate::value::safe_string(&item, &k, None) {
1892                    out.entry(kv).or_default().push(item);
1893                }
1894            }
1895        }
1896        Value::Map(out.into_iter().map(|(k, v)| (k, Value::Array(v))).collect())
1897    }
1898
1899    pub fn filter_by(
1900        &self,
1901        arr: Value,
1902        key: Value,
1903        value: Value,
1904        _optional_args: &[Value],
1905    ) -> Value {
1906        let k = key_str(&key);
1907        if let Value::Arr(items) = arr {
1908            let items = Arc::try_unwrap(items).unwrap_or_else(|a| (*a).clone());
1909            let out: Vec<Value> = items
1910                .into_iter()
1911                .filter(|it| {
1912                    let v = crate::get_value(it, &Value::Str(k.clone()));
1913                    crate::runtime::is_equal(&v, &value)
1914                })
1915                .collect();
1916            Value::Array(out)
1917        } else {
1918            Value::Array(vec![])
1919        }
1920    }
1921
1922    /// `sortBy(array, key, descending=false)` — stable sort of an array
1923    /// of objects by `obj[key]`. Mirrors `functions/generic.ts`.
1924    pub fn sort_by(&self, arr: Value, key: Value, optional_args: &[Value]) -> Value {
1925        let mut items = match arr {
1926            Value::Arr(a) => Arc::try_unwrap(a).unwrap_or_else(|x| (*x).clone()),
1927            other => return other,
1928        };
1929        let descending = matches!(optional_args.get(0), Some(Value::Bool(true)));
1930        let key = Value::Str(stringify_param(&key));
1931        items.sort_by(|a, b| {
1932            let av = crate::get_value(a, &key);
1933            let bv = crate::get_value(b, &key);
1934            let ord = value_cmp(&av, &bv);
1935            if descending {
1936                ord.reverse()
1937            } else {
1938                ord
1939            }
1940        });
1941        Value::Array(items)
1942    }
1943
1944    /// `sortBy2(array, key1, key2, descending=false)` — sort by `key1`,
1945    /// then `key2` as a tiebreaker. Mirrors `functions/generic.ts`.
1946    pub fn sort_by2(&self, arr: Value, k1: Value, k2: Value, optional_args: &[Value]) -> Value {
1947        let mut items = match arr {
1948            Value::Arr(a) => Arc::try_unwrap(a).unwrap_or_else(|x| (*x).clone()),
1949            other => return other,
1950        };
1951        let descending = matches!(optional_args.get(0), Some(Value::Bool(true)));
1952        let k1 = Value::Str(stringify_param(&k1));
1953        let k2 = Value::Str(stringify_param(&k2));
1954        items.sort_by(|a, b| {
1955            let ord = value_cmp(&crate::get_value(a, &k1), &crate::get_value(b, &k1)).then(
1956                value_cmp(&crate::get_value(a, &k2), &crate::get_value(b, &k2)),
1957            );
1958            if descending {
1959                ord.reverse()
1960            } else {
1961                ord
1962            }
1963        });
1964        Value::Array(items)
1965    }
1966
1967    pub fn keysort(&self, obj: Value, _optional_args: &[Value]) -> Value {
1968        if let Value::Dict(m) = obj {
1969            let mut keys: Vec<&String> = m.keys().collect();
1970            keys.sort();
1971            let mut out = HashMap::new();
1972            for k in &keys {
1973                out.insert((*k).clone(), m[*k].clone());
1974            }
1975            Value::Map(out)
1976        } else {
1977            obj
1978        }
1979    }
1980
1981    /// `aggregate(bidasks)` — groups `[price, volume]` rows by price,
1982    /// summing volume and dropping zero-volume rows. Preserves the
1983    /// first-occurrence order of prices. Mirrors `functions/misc.ts`.
1984    pub fn aggregate(&self, arr: Value) -> Value {
1985        // An order-book side is a marker Dict backed by the shared side store,
1986        // not a plain array (in JS `OrderBookSide` extends Array). Snapshot its
1987        // `[[price, size], …]` rows so aggregate iterates the levels.
1988        let arr = crate::value::side_entries_as_value(&arr).unwrap_or(arr);
1989        let items = match arr {
1990            Value::Arr(a) => Arc::try_unwrap(a).unwrap_or_else(|x| (*x).clone()),
1991            _ => return Value::Array(vec![]),
1992        };
1993        let mut order: Vec<u64> = Vec::new();
1994        let mut buckets: HashMap<u64, (f64, f64)> = HashMap::new();
1995        for item in items {
1996            let row = match item {
1997                Value::Arr(r) => r,
1998                _ => continue,
1999            };
2000            let price = value_as_f64(row.get(0));
2001            let volume = value_as_f64(row.get(1));
2002            if volume > 0.0 {
2003                let bits = price.to_bits();
2004                let entry = buckets.entry(bits).or_insert_with(|| {
2005                    order.push(bits);
2006                    (price, 0.0)
2007                });
2008                entry.1 += volume;
2009            }
2010        }
2011        let out: Vec<Value> = order
2012            .iter()
2013            .map(|b| {
2014                let (p, v) = buckets[b];
2015                Value::Array(vec![Value::Float(p), Value::Float(v)])
2016            })
2017            .collect();
2018        Value::Array(out)
2019    }
2020    pub fn map_to_safe_map(&self, v: Value) -> Value {
2021        v
2022    }
2023    pub fn create_safe_dictionary(&self, _optional_args: &[Value]) -> Value {
2024        Value::Map(HashMap::new())
2025    }
2026
2027    /// `clone(value)` — CCXT's deep clone, distinct from Rust's `Clone` trait.
2028    /// We disambiguate by name; the transpiler emits `self.clone(x)`.
2029    pub fn clone_value(&self, v: Value) -> Value {
2030        v
2031    }
2032
2033    /// `sum(...)` — variadic numeric sum. Pure variadic (0 fixed
2034    /// args) so single-arg `sum(x)` (e.g. from test.sum) also works.
2035    pub fn sum(&self, optional_args: &[Value]) -> Value {
2036        let mut acc: Option<Value> = None;
2037        for x in optional_args {
2038            acc = Some(match acc {
2039                None => x.clone(),
2040                Some(a) => crate::runtime::add(&a, x),
2041            });
2042        }
2043        acc.unwrap_or(Value::Null)
2044    }
2045
2046    /// `parse_json(text)` — JSON parse. Mirrors CCXT `parseJson`, which
2047    /// runs `onJsonResponse` first: when `quoteJsonNumbers` is on
2048    /// (default), every object number VALUE is wrapped in quotes before
2049    /// parsing so big integer ids (e.g. bingx's 18-digit `orderId`) and
2050    /// precise decimals survive as strings instead of lossy f64/i64.
2051    pub fn parse_json_value(&self, v: Value) -> Value {
2052        match v {
2053            Value::Str(s) => {
2054                let prepared = crate::runtime::quote_json_numbers(&s);
2055                crate::runtime::json_parse(&Value::Str(prepared))
2056            }
2057            // Already a parsed object/array (some fixtures store the
2058            // response pre-parsed) — pass it through untouched.
2059            other => other,
2060        }
2061    }
2062
2063    // `yymmdd()` / `yyyymmdd()` — date formatters.
2064    // ── methods called by transpiled base tests ─────────────────────────────
2065
2066    /// Test helper: tests sometimes call `exchange.clone()` to deep-copy
2067    /// state. We don't implement structural clone (the trait pointer
2068    /// can't be cloned safely) — return a fresh empty Exchange so the
2069    /// call compiles and tests can move on.
2070    /// No-arg `exchange.clone()` form — a structural copy of every
2071    /// `Value` field. The copy gets a fresh `Internals` (no shared http
2072    /// client / derived pointers), which is all the transpiled tests need.
2073    pub fn clone_self(&self) -> Exchange {
2074        Clone::clone(self)
2075    }
2076
2077    /// `clone(v)` — deep-clone a Value. Matches TS `exchange.clone(x)`.
2078    /// Note: keep this name even though it shadows the (manual) `clone_self`,
2079    /// because the transpiled tests call `exchange.clone(value)`. Empty-arg
2080    /// calls `exchange.clone()` get post-processed to `clone_self()`.
2081    pub fn clone(&self, v: Value) -> Value {
2082        v
2083    }
2084
2085    /// Dynamic-property lookup for transpiled base tests. The TS code
2086    /// does `exchange['options']`, `exchange['markets']`, etc. — this
2087    /// reads from the unified `to_value()` view so both access paths
2088    /// (`exchange.prop(k)` and `testSharedMethods.exchangeProp`) agree.
2089    pub fn prop(&self, key: &Value) -> Value {
2090        crate::get_value(&self.to_value(), key)
2091    }
2092
2093    /// Full `Value::Map` snapshot of every transpiler-visible field —
2094    /// the Rust analogue of indexing a JS object by property name.
2095    /// Used by `prop()` and by the base-test `exchangeProp` shim.
2096    pub fn to_value(&self) -> Value {
2097        let mut m = indexmap::IndexMap::new();
2098        let mut put = |k: &str, v: &Value| {
2099            m.insert(k.to_string(), v.clone());
2100        };
2101        put("id", &self.id);
2102        put("name", &self.name);
2103        put("countries", &self.countries);
2104        put("version", &self.version);
2105        put("alias", &self.alias);
2106        put("certified", &self.certified);
2107        put("pro", &self.pro);
2108        put("hostname", &self.hostname);
2109        put("apiKey", &self.apiKey);
2110        put("secret", &self.secret);
2111        put("password", &self.password);
2112        put("uid", &self.uid);
2113        put("walletAddress", &self.walletAddress);
2114        put("privateKey", &self.privateKey);
2115        put("twofa", &self.twofa);
2116        put("token", &self.token);
2117        put("login", &self.login);
2118        put("accountId", &self.accountId);
2119        put("requiredCredentials", &self.requiredCredentials);
2120        put("timeout", &self.timeout);
2121        put("rateLimit", &self.rateLimit);
2122        put("enableRateLimit", &self.enableRateLimit);
2123        put("fetchHistoryCacheSize", &self.fetchHistoryCacheSize);
2124        put("rateLimiterAlgorithm", &self.rateLimiterAlgorithm);
2125        put("rollingWindowSize", &self.rollingWindowSize);
2126        put("tokenBucket", &self.tokenBucket);
2127        put("verbose", &self.verbose);
2128        put("isSandboxModeEnabled", &self.isSandboxModeEnabled);
2129        put("proxy", &self.proxy);
2130        put("proxyUrl", &self.proxyUrl);
2131        put("proxy_url", &self.proxy_url);
2132        put("proxyUrlCallback", &self.proxyUrlCallback);
2133        put("proxy_url_callback", &self.proxy_url_callback);
2134        put("httpProxy", &self.httpProxy);
2135        put("http_proxy", &self.http_proxy);
2136        put("httpProxyCallback", &self.httpProxyCallback);
2137        put("http_proxy_callback", &self.http_proxy_callback);
2138        put("httpsProxy", &self.httpsProxy);
2139        put("https_proxy", &self.https_proxy);
2140        put("httpsProxyCallback", &self.httpsProxyCallback);
2141        put("https_proxy_callback", &self.https_proxy_callback);
2142        put("socksProxy", &self.socksProxy);
2143        put("socks_proxy", &self.socks_proxy);
2144        put("socksProxyCallback", &self.socksProxyCallback);
2145        put("socks_proxy_callback", &self.socks_proxy_callback);
2146        put("wsProxy", &self.wsProxy);
2147        put("ws_proxy", &self.ws_proxy);
2148        put("wssProxy", &self.wssProxy);
2149        put("wss_proxy", &self.wss_proxy);
2150        put("wsSocksProxy", &self.wsSocksProxy);
2151        put("ws_socks_proxy", &self.ws_socks_proxy);
2152        put("markets", &self.markets);
2153        put("markets_by_id", &self.markets_by_id);
2154        put("currencies", &self.currencies);
2155        put("currencies_by_id", &self.currencies_by_id);
2156        put("commonCurrencies", &self.commonCurrencies);
2157        put("baseCurrencies", &self.baseCurrencies);
2158        put("quoteCurrencies", &self.quoteCurrencies);
2159        put("symbols", &self.symbols);
2160        put("ids", &self.ids);
2161        put("codes", &self.codes);
2162        put("timeframes", &self.timeframes);
2163        put("precision", &self.precision);
2164        put("limits", &self.limits);
2165        put("fees", &self.fees);
2166        put("features", &self.features);
2167        put("has", &self.has);
2168        put("exceptions", &self.exceptions);
2169        put("urls", &self.urls);
2170        put("api", &self.api);
2171        put("options", &self.options);
2172        put("headers", &self.headers);
2173        put("accounts", &self.accounts);
2174        put("accountsById", &self.accountsById);
2175        put("orderbooks", &self.orderbooks);
2176        put("orders", &self.orders);
2177        put("trades", &self.trades);
2178        put("myTrades", &self.myTrades);
2179        put("positions", &self.positions);
2180        put("tickers", &self.tickers);
2181        put("bidsasks", &self.bidsasks);
2182        put("ohlcvs", &self.ohlcvs);
2183        put("clients", &self.clients);
2184        put("balance", &self.balance);
2185        put("liquidations", &self.liquidations);
2186        put("myLiquidations", &self.myLiquidations);
2187        put("transactions", &self.transactions);
2188        put("reloadingMarkets", &self.reloadingMarkets);
2189        put("marketsLoading", &self.marketsLoading);
2190        put("last_request_url", &self.last_request_url);
2191        put("last_request_headers", &self.last_request_headers);
2192        put("last_request_body", &self.last_request_body);
2193        put("last_http_response", &self.last_http_response);
2194        put("last_response_headers", &self.last_response_headers);
2195        put("last_json_response", &self.last_json_response);
2196        put("lastRestRequestTimestamp", &self.lastRestRequestTimestamp);
2197        put("paddingMode", &self.paddingMode);
2198        put("precisionMode", &self.precisionMode);
2199        put(
2200            "substituteCommonCurrencyCodes",
2201            &self.substituteCommonCurrencyCodes,
2202        );
2203        put("reduceFees", &self.reduceFees);
2204        put("minFundingAddressLength", &self.minFundingAddressLength);
2205        put("MAX_VALUE", &self.MAX_VALUE);
2206        put("returnResponseHeaders", &self.returnResponseHeaders);
2207        put("httpExceptions", &self.httpExceptions);
2208        put("status", &self.status);
2209        put("userAgent", &self.userAgent);
2210        put("user_agent", &self.user_agent);
2211        put("userAgents", &self.userAgents);
2212        Value::Map(m)
2213    }
2214
2215    pub fn base16ToBinary(&self, hex: Value, optional_args: &[Value]) -> Value {
2216        self.base16_to_binary(hex, optional_args)
2217    }
2218    pub fn base58_to_binary(&self, s: Value, _optional_args: &[Value]) -> Value {
2219        match &s {
2220            Value::Str(s) => match base58_decode(s) {
2221                Some(b) => bytes_to_value(&b),
2222                None => Value::Null,
2223            },
2224            _ => Value::Null,
2225        }
2226    }
2227    pub fn binary_to_base58(&self, b: Value, _optional_args: &[Value]) -> Value {
2228        Value::Str(base58_encode(&crate::exchange::value_to_bytes(&b)))
2229    }
2230    pub fn binary_length(&self, b: Value, _optional_args: &[Value]) -> Value {
2231        match b {
2232            Value::Arr(a) => Value::Int(a.len() as i64),
2233            _ => Value::Int(0),
2234        }
2235    }
2236    /// `isBinaryMessage` — in this port a binary buffer is a
2237    /// `Value::Array` of byte-valued ints (see `base16_to_binary`,
2238    /// `string_to_binary`). `instanceof Uint8Array` can't transpile.
2239    pub fn is_binary_message(&self, v: Value, _optional_args: &[Value]) -> Value {
2240        Value::Bool(is_byte_array(&v))
2241    }
2242    /// `numberToBE(n, padding)` — big-endian byte array of width `padding`.
2243    pub fn number_to_be(&self, n: Value, optional_args: &[Value]) -> Value {
2244        let num: u64 = match &n {
2245            Value::Int(i) => (*i).max(0) as u64,
2246            Value::Float(f) => (*f).max(0.0) as u64,
2247            Value::Str(s) => s.parse().unwrap_or(0),
2248            _ => 0,
2249        };
2250        let padding: usize = match optional_args.get(0) {
2251            Some(Value::Int(i)) => (*i).max(0) as usize,
2252            Some(Value::Float(f)) => (*f).max(0.0) as usize,
2253            _ => 8,
2254        };
2255        let be = num.to_be_bytes(); // 8 bytes
2256        let mut out: Vec<u8> = Vec::with_capacity(padding);
2257        if padding >= be.len() {
2258            out.extend(std::iter::repeat(0u8).take(padding - be.len()));
2259            out.extend_from_slice(&be);
2260        } else {
2261            out.extend_from_slice(&be[be.len() - padding..]);
2262        }
2263        bytes_to_value(&out)
2264    }
2265    /// `parseDate(x)` — ports `functions/time.ts`. Parses an ISO-8601
2266    /// timestamp (with `T`/`Z` or a plain `YYYY-MM-DD HH:MM:SS` form,
2267    /// treated as UTC) into epoch milliseconds. Invalid → Null.
2268    pub fn parse_date(&self, s: Value, _optional_args: &[Value]) -> Value {
2269        let text = match &s {
2270            Value::Str(s) if !s.is_empty() => s.clone(),
2271            _ => return Value::Null,
2272        };
2273        // rfc3339 (handles the `T...Z` and offset forms)
2274        if let Ok(t) = chrono::DateTime::parse_from_rfc3339(&text) {
2275            return Value::Int(t.timestamp_millis());
2276        }
2277        // naive `YYYY-MM-DD HH:MM:SS[.fff]` — interpreted as UTC
2278        for fmt in [
2279            "%Y-%m-%d %H:%M:%S%.f",
2280            "%Y-%m-%d %H:%M:%S",
2281            "%Y-%m-%dT%H:%M:%S%.f",
2282            "%Y-%m-%dT%H:%M:%S",
2283        ] {
2284            if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(&text, fmt) {
2285                return Value::Int(ndt.and_utc().timestamp_millis());
2286            }
2287        }
2288        Value::Null
2289    }
2290    pub fn is_binary_message_var(&self, v: Value, _optional_args: &[Value]) -> Value {
2291        Value::Bool(is_byte_array(&v))
2292    }
2293    /// `ymd(timestamp, infix='')` — like `yyyymmdd` but the infix
2294    /// defaults to empty (TS `functions/time.ts`).
2295    pub fn ymd(&self, ts: Value, optional_args: &[Value]) -> Value {
2296        if optional_args.is_empty() {
2297            self.yyyymmdd(ts, &[Value::Str(String::new())])
2298        } else {
2299            self.yyyymmdd(ts, optional_args)
2300        }
2301    }
2302    pub fn safe_float_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
2303        if let Value::Arr(ks) = keys {
2304            for k in ks.iter().cloned() {
2305                let v = self.safe_float(obj.clone(), k, &[]);
2306                if !v.is_null() {
2307                    return v;
2308                }
2309            }
2310        }
2311        arg_default(optional_args)
2312    }
2313    pub fn safe_float2(&self, obj: Value, k1: Value, k2: Value, optional_args: &[Value]) -> Value {
2314        let v = self.safe_float(obj.clone(), k1, &[]);
2315        if !v.is_null() {
2316            return v;
2317        }
2318        let v = self.safe_float(obj, k2, &[]);
2319        if !v.is_null() {
2320            v
2321        } else {
2322            arg_default(optional_args)
2323        }
2324    }
2325    // The transpiler may emit camelCase callers (`safeString2`) directly
2326    // because the rust-port preserved the TS name. Alias to the
2327    // snake-cased one we already have.
2328    pub fn safeString2(&self, obj: Value, k1: Value, k2: Value, optional_args: &[Value]) -> Value {
2329        self.safe_string2(obj, k1, k2, optional_args)
2330    }
2331    /// `binaryConcat(a, b, ...)` — concatenates byte buffers. The
2332    /// variadic call-site wrap folds the tail args into `optional_args`.
2333    pub fn binary_concat(&self, first: Value, optional_args: &[Value]) -> Value {
2334        let mut out = crate::exchange::value_to_bytes(&first);
2335        for v in optional_args {
2336            out.extend(crate::exchange::value_to_bytes(v));
2337        }
2338        bytes_to_value(&out)
2339    }
2340    pub fn stringToBase64(&self, s: Value, optional_args: &[Value]) -> Value {
2341        self.string_to_base64(s, optional_args)
2342    }
2343    /// `binaryToString(buffer)` — decodes a byte buffer as UTF-8.
2344    pub fn binary_to_string(&self, b: Value, _optional_args: &[Value]) -> Value {
2345        let bytes = crate::exchange::value_to_bytes(&b);
2346        Value::Str(String::from_utf8_lossy(&bytes).into_owned())
2347    }
2348    pub fn string_to_binary(&self, s: Value, _optional_args: &[Value]) -> Value {
2349        match s {
2350            Value::Str(s) => Value::Array(s.bytes().map(|b| Value::Int(b as i64)).collect()),
2351            _ => Value::Array(vec![]),
2352        }
2353    }
2354    /// `urlencodeBase64(payload)` — url-safe base64 with `+/` → `-_`
2355    /// and trailing `=` padding stripped. Accepts a string or a byte
2356    /// buffer (`Value::Array`).
2357    pub fn urlencode_base64(&self, v: Value, _optional_args: &[Value]) -> Value {
2358        let bytes = match &v {
2359            Value::Str(s) => s.as_bytes().to_vec(),
2360            _ => crate::exchange::value_to_bytes(&v),
2361        };
2362        let encoded = match self.binary_to_base64(bytes_to_value(&bytes), &[]) {
2363            Value::Str(s) => s,
2364            _ => String::new(),
2365        };
2366        let trimmed = encoded.trim_end_matches('=');
2367        Value::Str(trimmed.replace('+', "-").replace('/', "_"))
2368    }
2369    /// `urlencodeNested(object)` — `qs.stringify(object, { encodeValuesOnly: true })`:
2370    /// nested maps → `parent[child]`, arrays → `parent[index]`, only
2371    /// values are percent-encoded.
2372    pub fn urlencode_nested(&self, v: Value, _optional_args: &[Value]) -> Value {
2373        let m = match &v {
2374            Value::Dict(m) => m,
2375            _ => return Value::Str(String::new()),
2376        };
2377        let mut pairs: Vec<String> = Vec::new();
2378        for (k, val) in m.iter() {
2379            urlencode_nested_walk(k, val, &mut pairs);
2380        }
2381        Value::Str(pairs.join("&"))
2382    }
2383    pub fn is_json_encoded_object(&self, optional_args: &[Value]) -> Value {
2384        match optional_args.get(0) {
2385            Some(Value::Str(s)) => Value::Bool(s.starts_with('{') || s.starts_with('[')),
2386            _ => Value::Bool(false),
2387        }
2388    }
2389    pub fn strip(&self, s: Value, _optional_args: &[Value]) -> Value {
2390        match s {
2391            Value::Str(s) => Value::Str(s.trim().to_string()),
2392            other => other,
2393        }
2394    }
2395    pub fn sort(&self, v: Value, _optional_args: &[Value]) -> Value {
2396        if let Value::Arr(a) = v {
2397            let mut a = Arc::try_unwrap(a).unwrap_or_else(|x| (*x).clone());
2398            a.sort_by(|x, y| {
2399                let xs = crate::runtime::stringify_param(x);
2400                let ys = crate::runtime::stringify_param(y);
2401                xs.cmp(&ys)
2402            });
2403            Value::Array(a)
2404        } else {
2405            v
2406        }
2407    }
2408    /// `roundTimeframe(timeframe, timestamp, direction)` — snap a
2409    /// timestamp to the timeframe boundary (down by default, up for
2410    /// `ROUND_UP`).
2411    pub fn round_timeframe(&self, tf: Value, ts: Value, direction: Value) -> Value {
2412        let timeframe = match &tf {
2413            Value::Str(timeframe) => timeframe.as_str(),
2414            _ => "",
2415        };
2416        let unit = timeframe.chars().last().unwrap_or(' ');
2417        let amount = timeframe[..timeframe.len().saturating_sub(1)]
2418            .parse::<i64>()
2419            .unwrap_or(0);
2420        let secs = match self.parse_timeframe(tf) {
2421            Value::Int(s) => s,
2422            Value::Float(s) => s as i64,
2423            _ => return ts,
2424        };
2425        let ms = secs * 1000;
2426        let t = match &ts {
2427            Value::Int(i) => *i,
2428            Value::Float(f) => *f as i64,
2429            _ => return ts,
2430        };
2431        if ms == 0 {
2432            return ts;
2433        }
2434        if ((unit == 'w') || (unit == 'M') || (unit == 'y')) && (amount >= 1) {
2435            let date = match Utc.timestamp_millis_opt(t).single() {
2436                Some(date) => date,
2437                None => return ts,
2438            };
2439            let mut rounded = date.date_naive().and_hms_opt(0, 0, 0).unwrap().and_utc();
2440            if unit == 'w' {
2441                let days_since_monday = date.weekday().num_days_from_monday() as i64;
2442                let monday = rounded - chrono::Duration::days(days_since_monday);
2443                let epoch_monday = Utc.with_ymd_and_hms(1970, 1, 5, 0, 0, 0).unwrap();
2444                let weeks_since_epoch_monday = (monday - epoch_monday).num_days() / 7;
2445                rounded = epoch_monday
2446                    + chrono::Duration::days(
2447                        weeks_since_epoch_monday.div_euclid(amount) * amount * 7,
2448                    );
2449                if matches!(&direction, Value::Int(d) if *d == crate::runtime::ROUND_UP) {
2450                    rounded = rounded + chrono::Duration::days(amount * 7);
2451                }
2452            } else if unit == 'M' {
2453                let months_since_year_zero = date.year() as i64 * 12 + date.month0() as i64;
2454                let rounded_months = months_since_year_zero.div_euclid(amount) * amount;
2455                let year = rounded_months.div_euclid(12) as i32;
2456                let month = (rounded_months.rem_euclid(12) + 1) as u32;
2457                rounded = Utc.with_ymd_and_hms(year, month, 1, 0, 0, 0).unwrap();
2458                if matches!(&direction, Value::Int(d) if *d == crate::runtime::ROUND_UP) {
2459                    rounded = rounded + chrono::Months::new(amount as u32);
2460                }
2461            } else {
2462                let year = (date.year() as i64).div_euclid(amount) * amount;
2463                rounded = Utc.with_ymd_and_hms(year as i32, 1, 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 * 12) as u32);
2466                }
2467            }
2468            return Value::Int(rounded.timestamp_millis());
2469        }
2470        let offset = t % ms;
2471        let is_up = matches!(&direction, Value::Int(d) if *d == crate::runtime::ROUND_UP);
2472        Value::Int(t - offset + if is_up { ms } else { 0 })
2473    }
2474    pub async fn sleep(&self, ms: Value) -> Value {
2475        if let Some(n) = match ms {
2476            Value::Int(n) => Some(n),
2477            Value::Float(f) => Some(f as i64),
2478            _ => None,
2479        } {
2480            if n > 0 {
2481                tokio::time::sleep(std::time::Duration::from_millis(n as u64)).await;
2482            }
2483        }
2484        Value::Null
2485    }
2486    /// `ethGetAddressFromPrivateKey(pk)` — derive the Ethereum address
2487    /// (keccak256 of the uncompressed secp256k1 public key, last 20 bytes).
2488    pub fn eth_get_address_from_private_key(&self, pk: Value, _optional_args: &[Value]) -> Value {
2489        use k256::ecdsa::SigningKey;
2490        let pk_s = match &pk {
2491            Value::Str(s) => s.trim_start_matches("0x").to_string(),
2492            _ => return Value::Str(String::new()),
2493        };
2494        let pk_bytes = match hex::decode(&pk_s) {
2495            Ok(b) => b,
2496            Err(_) => return Value::Str(String::new()),
2497        };
2498        let sk = match SigningKey::from_slice(&pk_bytes) {
2499            Ok(k) => k,
2500            Err(_) => return Value::Str(String::new()),
2501        };
2502        let point = sk.verifying_key().to_encoded_point(false); // 0x04 || X || Y
2503        let pubkey = &point.as_bytes()[1..]; // 64 bytes
2504        let hash = crate::exchange::hash_raw(pubkey, "keccak");
2505        Value::Str(format!("0x{}", hex::encode(&hash[12..32])))
2506    }
2507    pub fn exists_file(&self, p: Value) -> Value {
2508        match &p {
2509            Value::Str(path) => Value::Bool(std::path::Path::new(path).is_file()),
2510            _ => Value::Bool(false),
2511        }
2512    }
2513    pub fn read_file(&self, p: Value) -> Value {
2514        match &p {
2515            Value::Str(path) => match std::fs::read_to_string(path) {
2516                Ok(s) => Value::Str(s),
2517                Err(_) => Value::Null,
2518            },
2519            _ => Value::Null,
2520        }
2521    }
2522    pub fn write_file(&self, p: Value, content: Value) -> Value {
2523        let path = match &p {
2524            Value::Str(s) => s.clone(),
2525            _ => return Value::Bool(false),
2526        };
2527        let body = match &content {
2528            Value::Str(s) => s.clone(),
2529            other => stringify_param(other),
2530        };
2531        Value::Bool(std::fs::write(&path, body).is_ok())
2532    }
2533    pub fn get_temp_dir(&self) -> Value {
2534        Value::Str(format!(
2535            "{}/",
2536            std::env::temp_dir().to_string_lossy().trim_end_matches('/')
2537        ))
2538    }
2539    pub fn get_property(&self, obj: Value, key: Value) -> Value {
2540        crate::get_value(&obj, &Value::Str(stringify_param(&key)))
2541    }
2542
2543    pub fn yymmdd(&self, ts: Value, optional_args: &[Value]) -> Value {
2544        let infix = match optional_args.get(0) {
2545            Some(Value::Str(s)) => s.clone(),
2546            _ => String::new(),
2547        };
2548        let n = match ts {
2549            Value::Int(n) => n,
2550            _ => 0,
2551        };
2552        let dt = chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n);
2553        match dt {
2554            Some(t) => Value::Str(t.format(&format!("%y{i}%m{i}%d", i = infix)).to_string()),
2555            None => Value::Null,
2556        }
2557    }
2558    pub fn yyyymmdd(&self, ts: Value, optional_args: &[Value]) -> Value {
2559        // TS default infix for yyyymmdd is '-'.
2560        let infix = match optional_args.get(0) {
2561            Some(Value::Str(s)) => s.clone(),
2562            _ => "-".to_string(),
2563        };
2564        let n = match ts {
2565            Value::Int(n) => n,
2566            _ => 0,
2567        };
2568        let dt = chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n);
2569        match dt {
2570            Some(t) => Value::Str(t.format(&format!("%Y{i}%m{i}%d", i = infix)).to_string()),
2571            None => Value::Null,
2572        }
2573    }
2574    /// `ymdhms(timestamp, infix=' ')` — UTC `YYYY-MM-DD<infix>HH:MM:SS`.
2575    pub fn ymdhms(&self, ts: Value, optional_args: &[Value]) -> Value {
2576        let infix = match optional_args.get(0) {
2577            Some(Value::Str(s)) => s.clone(),
2578            _ => " ".to_string(),
2579        };
2580        let n = match ts {
2581            Value::Int(n) => n,
2582            Value::Float(f) => f as i64,
2583            _ => 0,
2584        };
2585        let dt = chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n);
2586        match dt {
2587            Some(t) => Value::Str(t.format(&format!("%Y-%m-%d{infix}%H:%M:%S")).to_string()),
2588            None => Value::Null,
2589        }
2590    }
2591
2592    /// `rawencode(params, [doSeq])` — URL-encode without sorting.
2593    /// `rawencode(object)` — `qs.stringify(object, { encode: false })`:
2594    /// flat `key=value` pairs with no percent-encoding.
2595    pub fn rawencode(&self, params: Value, _optional_args: &[Value]) -> Value {
2596        let m = match &params {
2597            Value::Dict(m) => m,
2598            _ => return Value::Str(String::new()),
2599        };
2600        let pairs: Vec<String> = m
2601            .iter()
2602            .map(|(k, v)| format!("{}={}", k, stringify_param(v)))
2603            .collect();
2604        Value::Str(pairs.join("&"))
2605    }
2606
2607    /// `intToBase16(n)` — int → lowercase hex string.
2608    pub fn int_to_base16(&self, n: Value, _optional_args: &[Value]) -> Value {
2609        let v = match n {
2610            Value::Int(n) => n as u64,
2611            Value::Float(f) => f as u64,
2612            Value::Str(s) => s.parse::<u64>().unwrap_or(0),
2613            _ => 0,
2614        };
2615        Value::Str(format!("{:x}", v))
2616    }
2617
2618    /// `packb(action)` — MessagePack pack stub. Hyperliquid signs the
2619    /// packed bytes of an action. Returning empty bytes here is enough
2620    /// to make the call compile; live signing won't be correct.
2621    /// `packb(value)` — MessagePack-encode a Value into a byte array.
2622    pub fn packb(&self, action: Value, _optional_args: &[Value]) -> Value {
2623        fn to_rmpv(v: &Value) -> rmpv::Value {
2624            match v {
2625                Value::Null => rmpv::Value::Nil,
2626                Value::Bool(b) => rmpv::Value::Boolean(*b),
2627                Value::Int(i) => rmpv::Value::Integer((*i).into()),
2628                Value::Float(f) => rmpv::Value::F64(*f),
2629                Value::Str(s) => rmpv::Value::String(s.clone().into()),
2630                Value::Arr(a) => rmpv::Value::Array(a.iter().map(to_rmpv).collect()),
2631                Value::Dict(m) => rmpv::Value::Map(
2632                    m.iter()
2633                        .map(|(k, v)| (rmpv::Value::String(k.clone().into()), to_rmpv(v)))
2634                        .collect(),
2635                ),
2636            }
2637        }
2638        let mut buf: Vec<u8> = Vec::new();
2639        match rmpv::encode::write_value(&mut buf, &to_rmpv(&action)) {
2640            Ok(_) => Value::Array(buf.iter().map(|b| Value::Int(*b as i64)).collect()),
2641            Err(_) => Value::Null,
2642        }
2643    }
2644
2645    /// `ethEncodeStructuredData(domain, types, message)` — EIP-712
2646    /// encoding: returns the `\x19\x01 || domainSeparator || structHash`
2647    /// preimage that the caller keccak-hashes before signing.
2648    pub fn eth_encode_structured_data(&self, domain: Value, types: Value, message: Value) -> Value {
2649        let bytes = crate::exchange::eip712_encode(&domain, &types, &message);
2650        Value::Array(bytes.iter().map(|b| Value::Int(*b as i64)).collect())
2651    }
2652
2653    /// `uuid22()` — pseudo-random 22-char hex id.
2654    pub fn uuid22(&self, _optional_args: &[Value]) -> Value {
2655        Value::Str(random_hex(22))
2656    }
2657    /// `uuid16()` — pseudo-random 16-char hex id.
2658    pub fn uuid16(&self, _optional_args: &[Value]) -> Value {
2659        Value::Str(random_hex(16))
2660    }
2661    /// `uuid()` — pseudo-random UUID v4: `xxxxxxxx-xxxx-4xxx-[89ab]xxx-xxxxxxxxxxxx`.
2662    pub fn uuid(&self, _optional_args: &[Value]) -> Value {
2663        let h = random_hex(32);
2664        let variant = ['8', '9', 'a', 'b'][(random_u64() % 4) as usize];
2665        let s = format!(
2666            "{}-{}-4{}-{}{}-{}",
2667            &h[0..8],
2668            &h[8..12],
2669            &h[13..16],
2670            variant,
2671            &h[17..20],
2672            &h[20..32],
2673        );
2674        Value::Str(s)
2675    }
2676
2677    /// `urlencode(params)` — wraps the typed `urlencode_kv` for Value args.
2678    pub fn urlencode(&self, params: Value, _optional_args: &[Value]) -> Value {
2679        Value::Str(self.urlencode_kv(&params))
2680    }
2681
2682    /// `json(value)` — JSON-stringify.
2683    pub fn json(&self, v: Value) -> Value {
2684        Value::Str(self.json_str(&v))
2685    }
2686
2687    /// `encode(s)` — UTF-8 encode string to bytes (as Value::Array of ints).
2688    pub fn encode(&self, s: Value) -> Value {
2689        match s {
2690            Value::Str(s) => Value::Array(s.bytes().map(|b| Value::Int(b as i64)).collect()),
2691            _ => Value::Array(vec![]),
2692        }
2693    }
2694
2695    /// `decode(bytes)` — decode bytes to a UTF-8 string.
2696    pub fn decode(&self, b: Value) -> Value {
2697        match b {
2698            Value::Str(s) => Value::Str(s),
2699            Value::Arr(a) => {
2700                let bytes: Vec<u8> = a
2701                    .iter()
2702                    .filter_map(|v| match v {
2703                        Value::Int(n) => Some(*n as u8),
2704                        _ => None,
2705                    })
2706                    .collect();
2707                Value::Str(String::from_utf8_lossy(&bytes).to_string())
2708            }
2709            _ => Value::Str(String::new()),
2710        }
2711    }
2712
2713    /// `log(msg)` — debug print.
2714    pub fn log(&self, msg: Value) {
2715        if matches!(self.verbose, Value::Bool(true)) {
2716            println!("[ccxt] {}", crate::runtime::stringify_param(&msg));
2717        }
2718    }
2719
2720    // Dynamic dispatch for the implicit API (`public_get_exchange_info`, …)
2721    // now lives in the `ExchangeRuntime::call_method` trait method (review #1),
2722    // routing through `implicit_api_call` → `request_typed` → `fetch_typed`.
2723
2724    // ── string / number formatting ──────────────────────────────────────────
2725
2726    pub fn number_to_string(&self, n: Value) -> Value {
2727        // TS `numberToString(undefined)` returns undefined — don't
2728        // stringify a missing value into the literal "null".
2729        if matches!(n, Value::Null) {
2730            return Value::Null;
2731        }
2732        Value::Str(stringify_param(&n))
2733    }
2734
2735    pub fn parse_number(&self, v: Value, optional_args: &[Value]) -> Value {
2736        match v {
2737            Value::Float(_) | Value::Int(_) => v,
2738            Value::Str(ref s) => match s.parse::<f64>() {
2739                Ok(n) => Value::Float(n),
2740                Err(_) => arg_default(optional_args),
2741            },
2742            _ => arg_default(optional_args),
2743        }
2744    }
2745
2746    pub fn parse_timeframe(&self, tf: Value) -> Value {
2747        let s = stringify_param(&tf);
2748        let last = s.chars().last().unwrap_or('m');
2749        let num: i64 = s[..s.len().saturating_sub(1)].parse().unwrap_or(0);
2750        Value::Int(match last {
2751            's' => num,
2752            'm' => num * 60,
2753            'h' => num * 3600,
2754            'd' => num * 86400,
2755            'w' => num * 604800,
2756            'M' => num * 2592000,
2757            'y' => num * 31536000,
2758            _ => 0,
2759        })
2760    }
2761
2762    /// `precisionFromString(str)` — ports `functions/number.ts`.
2763    /// Scientific notation (`1e-4` → 4, `1e4` → -4); otherwise the
2764    /// number of fractional digits after stripping trailing zeros.
2765    pub fn precision_from_string(&self, s: Value) -> Value {
2766        let s = stringify_param(&s);
2767        if let Some(idx) = s.find(['e', 'E']) {
2768            let exp: i64 = s[idx + 1..].parse().unwrap_or(0);
2769            return Value::Int(-exp);
2770        }
2771        let trimmed = s.trim_end_matches('0');
2772        match trimmed.split_once('.') {
2773            Some((_, frac)) => Value::Int(frac.len() as i64),
2774            None => Value::Int(0),
2775        }
2776    }
2777
2778    /// `decimalToPrecision(n, roundingMode, numPrecisionDigits, [countingMode], [paddingMode])`
2779    /// — faithful port of `_decimalToPrecision` from `functions/number.ts`.
2780    pub fn decimal_to_precision(
2781        &self,
2782        n: Value,
2783        rounding: Value,
2784        precision: Value,
2785        optional_args: &[Value],
2786    ) -> Value {
2787        let n_s = stringify_param(&n);
2788        let prec_f: f64 = match &precision {
2789            Value::Int(i) => *i as f64,
2790            Value::Float(f) => *f,
2791            Value::Str(s) => s.parse().unwrap_or(f64::NAN),
2792            _ => return Value::Str(n_s),
2793        };
2794        let counting: i64 = match optional_args.get(0) {
2795            Some(Value::Int(c)) => *c,
2796            _ => crate::runtime::DECIMAL_PLACES,
2797        };
2798        let padding: i64 = match optional_args.get(1) {
2799            Some(Value::Int(p)) => *p,
2800            _ => crate::runtime::NO_PADDING,
2801        };
2802        let rounding_mode: i64 = match &rounding {
2803            Value::Int(r) => *r,
2804            _ => crate::runtime::TRUNCATE,
2805        };
2806        Value::Str(decimal_to_precision_impl(
2807            &n_s,
2808            rounding_mode,
2809            prec_f,
2810            counting,
2811            padding,
2812        ))
2813    }
2814
2815    pub fn capitalize(&self, s: Value) -> Value {
2816        let s = stringify_param(&s);
2817        let mut c = s.chars();
2818        Value::Str(match c.next() {
2819            None => String::new(),
2820            Some(f) => f.to_uppercase().chain(c).collect(),
2821        })
2822    }
2823
2824    pub fn encode_uri_component(&self, s: Value) -> Value {
2825        let s = stringify_param(&s);
2826        Value::Str(
2827            s.bytes()
2828                .map(|b| match b {
2829                    b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
2830                        (b as char).to_string()
2831                    }
2832                    _ => format!("%{b:02X}"),
2833                })
2834                .collect(),
2835        )
2836    }
2837
2838    pub fn string_to_chars_array(&self, s: Value) -> Value {
2839        let s = stringify_param(&s);
2840        Value::Array(s.chars().map(|c| Value::Str(c.to_string())).collect())
2841    }
2842
2843    pub fn string_to_base64(&self, s: Value, _optional_args: &[Value]) -> Value {
2844        self.binary_to_base64(s, &[])
2845    }
2846
2847    /// `extract_params(path)` — pulls `{name}` placeholders from a URL
2848    /// template. Returns a Value::Array of names.
2849    pub fn extract_params(&self, path: Value) -> Value {
2850        let p = stringify_param(&path);
2851        let mut out: Vec<Value> = vec![];
2852        let mut chars = p.chars().peekable();
2853        while let Some(c) = chars.next() {
2854            if c == '{' {
2855                let mut name = String::new();
2856                while let Some(&nc) = chars.peek() {
2857                    if nc == '}' {
2858                        chars.next();
2859                        break;
2860                    }
2861                    name.push(nc);
2862                    chars.next();
2863                }
2864                if !name.is_empty() {
2865                    out.push(Value::Str(name));
2866                }
2867            }
2868        }
2869        Value::Array(out)
2870    }
2871
2872    // ── async lifecycle stubs ───────────────────────────────────────────────
2873
2874    // Minimal port of TS `loadMarketsHelper`:
2875    //   1. Return the cached `markets` if already populated and not
2876    //      forcing a reload.
2877    //   2. If `has.fetchCurrencies === true`, dispatch `fetch_currencies`
2878    //      first — passing the result into `set_markets` avoids the
2879    //      O(N²) "synthesize from markets" branch (cloning the
2880    //      grouped-by-code Map inside an outer loop).
2881    //   3. Dispatch `fetch_markets` to the derived exchange.
2882    //   4. `set_markets(markets, currencies)` populates `markets`,
2883    //      `markets_by_id`, `symbols`, `ids`, and merges currencies.
2884    // Returns cached markets on hit; otherwise fetches markets (and
2885    // currencies when supported) and pushes everything through
2886    // `set_markets`. The built-in synthesize branch of `set_markets` is
2887    // O(N) per code with full Map clones —
2888    // for binance (~4k markets, ~1k unique codes) that grew to minutes
2889    // and looked like a hang. `load_markets_fast_synthesize_currencies`
2890    // below short-circuits when currencies are empty by synthesizing
2891    // them here in idiomatic Rust (HashMap-direct, no Value cloning of
2892    // the whole grouped map per code).
2893
2894    // Proxy callback "methods" — the post-processor rewrites
2895    // `self.proxy_url_callback(args)` → `self.proxy_url_callback_fn(args)`
2896    // so the field `proxy_url_callback: Value` can coexist with this
2897    // method-form for the call sites.
2898    pub fn proxy_fn(&self, _url: Value, _method: Value, _headers: Value, _body: Value) -> Value {
2899        self.proxy.clone()
2900    }
2901    pub fn proxy_url_callback_fn(
2902        &self,
2903        _url: Value,
2904        _method: Value,
2905        _headers: Value,
2906        _body: Value,
2907    ) -> Value {
2908        self.proxy_url_callback.clone()
2909    }
2910    pub fn http_proxy_callback_fn(
2911        &self,
2912        _url: Value,
2913        _method: Value,
2914        _headers: Value,
2915        _body: Value,
2916    ) -> Value {
2917        self.http_proxy_callback.clone()
2918    }
2919    pub fn https_proxy_callback_fn(
2920        &self,
2921        _url: Value,
2922        _method: Value,
2923        _headers: Value,
2924        _body: Value,
2925    ) -> Value {
2926        self.https_proxy_callback.clone()
2927    }
2928    pub fn socks_proxy_callback_fn(
2929        &self,
2930        _url: Value,
2931        _method: Value,
2932        _headers: Value,
2933        _body: Value,
2934    ) -> Value {
2935        self.socks_proxy_callback.clone()
2936    }
2937    pub fn ws_proxy_callback_fn(
2938        &self,
2939        _url: Value,
2940        _method: Value,
2941        _headers: Value,
2942        _body: Value,
2943    ) -> Value {
2944        Value::Null
2945    }
2946    pub fn wss_proxy_callback_fn(
2947        &self,
2948        _url: Value,
2949        _method: Value,
2950        _headers: Value,
2951        _body: Value,
2952    ) -> Value {
2953        Value::Null
2954    }
2955    pub fn ws_socks_proxy_callback_fn(
2956        &self,
2957        _url: Value,
2958        _method: Value,
2959        _headers: Value,
2960        _body: Value,
2961    ) -> Value {
2962        Value::Null
2963    }
2964
2965    pub fn init_throttler(&mut self) { /* stub */
2966    }
2967    /// Leaky-bucket rate limiter, mirroring `ts/src/base/functions/throttle.ts`.
2968    /// `rateLimit` is milliseconds-per-token, so `refillRate = 1/rateLimit`
2969    /// tokens/ms; `tokens` may go negative (a request proceeds when `tokens >= 0`
2970    /// and then subtracts its cost), and the next request waits until the bucket
2971    /// refills back to zero. State lives in `internals.throttle` behind an async
2972    /// mutex, so concurrent calls on one instance serialize (the TS single queue).
2973    /// A no-op when `enableRateLimit` is false or the rate is effectively
2974    /// unlimited.
2975    pub async fn throttle(&self, cost: &[Value]) -> Value {
2976        if !matches!(self.enableRateLimit, Value::Bool(true)) {
2977            return Value::Null;
2978        }
2979        let tb = |key: &str| -> Option<f64> {
2980            crate::get_value(&self.tokenBucket, &Value::Str(key.to_string())).as_f64()
2981        };
2982        let rate_limit = self.rateLimit.as_f64().unwrap_or(0.0);
2983        let refill_rate = tb("refillRate").unwrap_or_else(|| {
2984            if rate_limit > 0.0 {
2985                1.0 / rate_limit
2986            } else {
2987                f64::MAX
2988            }
2989        });
2990        if !(refill_rate.is_finite() && refill_rate > 0.0) {
2991            return Value::Null; // effectively unlimited
2992        }
2993        let capacity = tb("capacity").unwrap_or(1.0);
2994        let delay_ms = tb("delay").unwrap_or(0.001) * 1000.0;
2995        let this_cost = cost
2996            .first()
2997            .and_then(|v| v.as_f64())
2998            .unwrap_or_else(|| tb("cost").unwrap_or(1.0));
2999
3000        let now_ms = || {
3001            std::time::SystemTime::now()
3002                .duration_since(std::time::UNIX_EPOCH)
3003                .map(|d| d.as_millis() as i64)
3004                .unwrap_or(0)
3005        };
3006
3007        let mut guard = self.internals.throttle.lock().await;
3008        let (tokens, last_ms) = &mut *guard;
3009        if *last_ms == 0 {
3010            *last_ms = now_ms();
3011        }
3012        // Refill for the elapsed time (capped at capacity).
3013        let n = now_ms();
3014        *tokens = (*tokens + refill_rate * (n - *last_ms).max(0) as f64).min(capacity);
3015        *last_ms = n;
3016        // In deficit → wait until the bucket refills to zero, holding the lock so
3017        // requests stay serialized.
3018        if *tokens < 0.0 {
3019            let wait = ((-*tokens) / refill_rate).max(delay_ms);
3020            tokio::time::sleep(std::time::Duration::from_millis(wait.ceil() as u64)).await;
3021            let n2 = now_ms();
3022            *tokens = (*tokens + refill_rate * (n2 - *last_ms).max(0) as f64).min(capacity);
3023            *last_ms = n2;
3024        }
3025        *tokens -= this_cost;
3026        Value::Null
3027    }
3028
3029    pub fn resolve<T>(&self, v: T) -> T {
3030        v
3031    }
3032    pub fn reject(&self, err: ExchangeError) -> ExchangeError {
3033        err
3034    }
3035}
3036
3037/// Synthesizes a `code → currency` map from a list of markets, mirroring
3038/// what `Exchange::set_markets`' else-branch does in TS — but in straight
3039/// Rust without re-cloning the grouped Map per outer iteration. For
3040/// binance (~4k markets, ~1k codes) the transpiled path took minutes;
3041/// this version completes in milliseconds.
3042pub(crate) fn synthesize_currencies_from_markets(markets: &Value, precision_mode: &Value) -> Value {
3043    let market_list: Vec<&Value> = match markets {
3044        Value::Arr(a) => a.iter().collect(),
3045        Value::Dict(m) => m.values().collect(),
3046        _ => return Value::Map(HashMap::new()),
3047    };
3048    let is_tick_size = matches!(precision_mode, Value::Int(n) if *n == crate::runtime::TICK_SIZE);
3049    let default_precision = if is_tick_size {
3050        Value::Float(1e-8)
3051    } else {
3052        Value::Int(8)
3053    };
3054
3055    // Helper to compare precision: tick size → smaller is more precise;
3056    // decimal places → larger is more precise.
3057    let more_precise = |new: &Value, cur: &Value| -> bool {
3058        let to_f = |v: &Value| -> f64 {
3059            match v {
3060                Value::Int(n) => *n as f64,
3061                Value::Float(f) => *f,
3062                Value::Str(s) => s.parse().unwrap_or(f64::NAN),
3063                _ => f64::NAN,
3064            }
3065        };
3066        let n = to_f(new);
3067        let c = to_f(cur);
3068        if n.is_nan() {
3069            return false;
3070        }
3071        if c.is_nan() {
3072            return true;
3073        }
3074        if is_tick_size {
3075            n < c
3076        } else {
3077            n > c
3078        }
3079    };
3080
3081    // Pull out the "code", "id", "precision" triple for each side. We
3082    // dedupe by code, keeping the most-precise instance.
3083    let mut by_code: HashMap<String, HashMap<String, Value>> = HashMap::new();
3084    for market in market_list {
3085        let market_precision = crate::get_value(market, &Value::Str("precision".to_string()));
3086        // base side
3087        for (id_key, code_key, prec_keys) in [
3088            ("baseId", "base", ["base", "amount"]),
3089            ("quoteId", "quote", ["quote", "price"]),
3090        ] {
3091            let code = crate::get_value(market, &Value::Str(code_key.to_string()));
3092            let code_s = match &code {
3093                Value::Str(s) if !s.is_empty() => s.clone(),
3094                _ => continue,
3095            };
3096            let id = crate::get_value(market, &Value::Str(id_key.to_string()));
3097            let id_v = match &id {
3098                Value::Null => Value::Str(code_s.clone()),
3099                other => other.clone(),
3100            };
3101            let mut precision =
3102                crate::get_value(&market_precision, &Value::Str(prec_keys[0].to_string()));
3103            if matches!(precision, Value::Null) {
3104                precision =
3105                    crate::get_value(&market_precision, &Value::Str(prec_keys[1].to_string()));
3106            }
3107            if matches!(precision, Value::Null) {
3108                precision = default_precision.clone();
3109            }
3110            let entry = by_code.entry(code_s.clone()).or_insert_with(|| {
3111                let mut m = HashMap::new();
3112                m.insert("id".to_string(), id_v.clone());
3113                m.insert("numericId".to_string(), Value::Null);
3114                m.insert("code".to_string(), Value::Str(code_s.clone()));
3115                m.insert("precision".to_string(), precision.clone());
3116                m
3117            });
3118            let existing_precision = entry.get("precision").cloned().unwrap_or(Value::Null);
3119            if more_precise(&precision, &existing_precision) {
3120                entry.insert("precision".to_string(), precision.clone());
3121            }
3122        }
3123    }
3124    let result: HashMap<String, Value> = by_code
3125        .into_iter()
3126        .map(|(k, v)| (k, Value::Map(v)))
3127        .collect();
3128    Value::Map(result)
3129}
3130
3131#[cfg(test)]
3132mod spawn_queue_tests {
3133    use super::*;
3134
3135    // `delay(ms, method, …)` schedules a coroutine on a real deadline —
3136    // binance's `keepAliveListenKey` re-arms itself every 20 min this way.
3137    // Regression cover for the original stub, which elided `ms` entirely and
3138    // ran the coroutine on the next inbound frame instead.
3139    #[test]
3140    fn delayed_spawns_wait_for_their_deadline() {
3141        // Not yet due: held back, and reported as the next deadline.
3142        enqueue_spawn_after("keep_alive_listen_key", vec![], 10_000);
3143        assert!(drain_spawn_queue().is_empty(), "not due yet");
3144        let due_in = next_spawn_due().expect("a deadline is pending");
3145        assert!(due_in > std::time::Duration::from_secs(9));
3146
3147        // An undelayed spawn still runs on the next drain, and does not
3148        // disturb the queued deadline.
3149        enqueue_spawn("handle_order_book_snapshot", vec![]);
3150        let batch = drain_spawn_queue();
3151        assert_eq!(batch.len(), 1);
3152        assert_eq!(batch[0].0, "handle_order_book_snapshot");
3153        assert!(
3154            next_spawn_due().is_some(),
3155            "the delayed item is still queued"
3156        );
3157    }
3158
3159    #[test]
3160    fn spawns_run_once_their_deadline_passes() {
3161        enqueue_spawn_after("keep_alive_listen_key", vec![], 1);
3162        std::thread::sleep(std::time::Duration::from_millis(5));
3163        assert_eq!(next_spawn_due(), Some(std::time::Duration::ZERO));
3164        let batch = drain_spawn_queue();
3165        assert_eq!(batch.len(), 1);
3166        assert_eq!(batch[0].0, "keep_alive_listen_key");
3167        assert!(next_spawn_due().is_none(), "queue drained");
3168    }
3169}