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