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