Skip to main content

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