Skip to main content

ccxt_common/
runtime.rs

1// Runtime helpers used by transpiled Rust code.
2//
3// The ast-transpiler emits code like `add(&a, &b)`, `is_equal(&x, &y)`,
4// `get_value(&obj, &key)`, etc. — a Value-only "duck-typed" runtime,
5// modelled after how the Python/PHP transpilations work.
6//
7// These helpers implement those primitives on `crate::Value`. They aim to
8// be lenient: any type mismatch returns `Value::Null` or `false` rather
9// than panicking, mirroring JS semantics.
10
11#![allow(clippy::float_cmp, clippy::needless_return, dead_code)]
12
13use crate::Value;
14use indexmap::IndexMap as HashMap;
15use std::sync::Arc;
16
17// ── numeric / arithmetic ─────────────────────────────────────────────────────
18
19fn as_f64(v: &Value) -> Option<f64> {
20    match v {
21        Value::Int(n)   => Some(*n as f64),
22        Value::Float(f) => Some(*f),
23        Value::Str(s)   => s.parse().ok(),
24        Value::Bool(b)  => Some(if *b { 1.0 } else { 0.0 }),
25        _ => None,
26    }
27}
28
29fn as_i64(v: &Value) -> Option<i64> {
30    match v {
31        Value::Int(n)   => Some(*n),
32        Value::Float(f) => Some(*f as i64),
33        Value::Str(s)   => s.parse().ok(),
34        Value::Bool(b)  => Some(if *b { 1 } else { 0 }),
35        _ => None,
36    }
37}
38
39fn both_ints(a: &Value, b: &Value) -> bool {
40    matches!(a, Value::Int(_)) && matches!(b, Value::Int(_))
41}
42
43pub fn add(a: &Value, b: &Value) -> Value {
44    // String concatenation if either side is a string (JS-style)
45    if let (Value::Str(sa), Value::Str(sb)) = (a, b) {
46        return Value::Str(format!("{sa}{sb}").into());
47    }
48    if let Value::Str(_) = a { if let Some(_) = as_f64(b) {} return string_concat(a, b); }
49    if let Value::Str(_) = b { return string_concat(a, b); }
50    if both_ints(a, b) {
51        return Value::Int(as_i64(a).unwrap() + as_i64(b).unwrap());
52    }
53    match (as_f64(a), as_f64(b)) {
54        (Some(x), Some(y)) => Value::Float(x + y),
55        _ => Value::Null,
56    }
57}
58
59fn string_concat(a: &Value, b: &Value) -> Value {
60    let sa = stringify_simple(a);
61    let sb = stringify_simple(b);
62    Value::Str(format!("{sa}{sb}").into())
63}
64
65pub fn stringify_param(v: &Value) -> String { stringify_simple(v) }
66
67fn stringify_simple(v: &Value) -> String {
68    match v {
69        Value::Str(s)   => s.to_string(),
70        Value::Int(n)   => n.to_string(),
71        Value::Float(f) => f.to_string(),
72        Value::Bool(b)  => b.to_string(),
73        Value::Null     => "null".to_string(),
74        // Precise sentinel — { integer, decimals, __precise: true }.
75        // Reconstruct the decimal representation so `to_string_val` in
76        // transpiled code returns the expected number string (phemex
77        // `toEn` shifts decimals by `valueScale`, then reduce/stringify).
78        Value::Dict(m) if m.contains_key("__precise") => precise_to_string(m),
79        _ => format!("{v}"),
80    }
81}
82
83fn precise_to_string(m: &indexmap::IndexMap<String, Value>) -> String {
84    let decimals: i64 = match m.get("decimals") { Some(Value::Int(n)) => *n, _ => 0 };
85    let integer: String = match m.get("integer") {
86        Some(Value::Str(s)) => s.to_string(),
87        _ => return "0".to_string(),
88    };
89    let (sign, mut digits) = if let Some(rest) = integer.strip_prefix('-') {
90        ("-".to_string(), rest.to_string())
91    } else { ("".to_string(), integer) };
92    if decimals <= 0 {
93        // Pad zeros onto the integer side.
94        for _ in 0..(-decimals) { digits.push('0'); }
95        return format!("{sign}{digits}");
96    }
97    let d = decimals as usize;
98    if digits.len() <= d {
99        // Need leading zeros: "1" with decimals=4 → "0.0001"
100        let zeros = "0".repeat(d - digits.len());
101        format!("{sign}0.{zeros}{digits}")
102    } else {
103        let split = digits.len() - d;
104        let (int_part, frac_part) = digits.split_at(split);
105        format!("{sign}{int_part}.{frac_part}")
106    }
107}
108
109pub fn subtract(a: &Value, b: &Value) -> Value {
110    if both_ints(a, b) { return Value::Int(as_i64(a).unwrap() - as_i64(b).unwrap()); }
111    match (as_f64(a), as_f64(b)) {
112        (Some(x), Some(y)) => Value::Float(x - y),
113        _ => Value::Null,
114    }
115}
116
117pub fn multiply(a: &Value, b: &Value) -> Value {
118    if both_ints(a, b) { return Value::Int(as_i64(a).unwrap() * as_i64(b).unwrap()); }
119    match (as_f64(a), as_f64(b)) {
120        (Some(x), Some(y)) => Value::Float(x * y),
121        _ => Value::Null,
122    }
123}
124
125// Printed by the rust `/` wrapper table; keep at 0 call sites.
126pub fn divide(a: &Value, b: &Value) -> Value {
127    match (as_f64(a), as_f64(b)) {
128        (Some(_), Some(y)) if y == 0.0 => Value::Null,
129        (Some(x), Some(y)) => Value::Float(x / y),
130        _ => Value::Null,
131    }
132}
133
134// Printed by the rust `%` / `%=` wrapper table; keep at 0 call sites.
135pub fn mod_val(a: &Value, b: &Value) -> Value {
136    if both_ints(a, b) {
137        let yi = as_i64(b).unwrap();
138        if yi == 0 { return Value::Null; }
139        return Value::Int(as_i64(a).unwrap() % yi);
140    }
141    match (as_f64(a), as_f64(b)) {
142        (Some(_), Some(y)) if y == 0.0 => Value::Null,
143        (Some(x), Some(y)) => Value::Float(x % y),
144        _ => Value::Null,
145    }
146}
147
148// Printed by printPrefixUnaryExpression when native negation declines; keep.
149pub fn negate(v: &Value) -> Value {
150    match v {
151        Value::Int(n)   => Value::Int(-n),
152        Value::Float(f) => Value::Float(-f),
153        _ => match as_f64(v) {
154            Some(x) => Value::Float(-x),
155            None    => Value::Null,
156        },
157    }
158}
159
160// ── comparisons ─────────────────────────────────────────────────────────────
161
162pub fn is_equal(a: &Value, b: &Value) -> bool {
163    match (a, b) {
164        (Value::Null, Value::Null) => true,
165        (Value::Bool(x), Value::Bool(y)) => x == y,
166        (Value::Str(x), Value::Str(y))   => x == y,
167        (Value::Int(x), Value::Int(y))   => x == y,
168        (Value::Float(x), Value::Float(y)) => x == y,
169        _ => match (as_f64(a), as_f64(b)) {
170            (Some(x), Some(y)) => x == y,
171            _ => false,
172        },
173    }
174}
175
176pub fn is_greater_than(a: &Value, b: &Value) -> bool {
177    match (as_f64(a), as_f64(b)) {
178        (Some(x), Some(y)) => x > y,
179        _ => match (a, b) { (Value::Str(x), Value::Str(y)) => x > y, _ => false },
180    }
181}
182
183pub fn is_less_than(a: &Value, b: &Value) -> bool {
184    match (as_f64(a), as_f64(b)) {
185        (Some(x), Some(y)) => x < y,
186        _ => match (a, b) { (Value::Str(x), Value::Str(y)) => x < y, _ => false },
187    }
188}
189
190pub fn is_greater_than_or_equal(a: &Value, b: &Value) -> bool {
191    is_greater_than(a, b) || is_equal(a, b)
192}
193
194pub fn is_less_than_or_equal(a: &Value, b: &Value) -> bool {
195    is_less_than(a, b) || is_equal(a, b)
196}
197
198// ── type checks ─────────────────────────────────────────────────────────────
199
200/// `is_true(x)` — polymorphic truthy check. The transpiler emits
201/// `is_true(&X)` where `X` may be a `Value`, a `bool`, or the result of
202/// any other predicate (`is_equal`, `in_op`, …). This trait lets all of
203/// them work without manual conversion at the call site.
204pub trait IsTruthy { fn truthy(&self) -> bool; }
205impl IsTruthy for Value     { fn truthy(&self) -> bool { self.is_truthy() } }
206impl IsTruthy for bool      { fn truthy(&self) -> bool { *self } }
207impl IsTruthy for &Value    { fn truthy(&self) -> bool { (*self).is_truthy() } }
208impl IsTruthy for &bool     { fn truthy(&self) -> bool { **self } }
209
210pub fn is_true<T: IsTruthy + ?Sized>(v: &T) -> bool { v.truthy() }
211
212pub fn is_array(v: &Value)    -> bool { matches!(v, Value::Arr(_)) }
213pub fn is_object(v: &Value)   -> bool { matches!(v, Value::Dict(_)) }
214pub fn is_number(v: &Value)   -> bool { matches!(v, Value::Int(_) | Value::Float(_)) }
215pub fn is_bool(v: &Value)     -> bool { matches!(v, Value::Bool(_)) }
216pub fn is_function(_v: &Value)-> bool { false }
217
218/// Convert a `catch_unwind` panic payload into the `Value::Str` shape
219/// that transpiled `catch (e)` blocks expect. The transpiled code uses
220/// this from the catch arm emitted by `rewriteTryCatchAsync` — kept in
221/// the ccxt crate (rather than the test crate) so exchange files that
222/// catch downstream panics (e.g. pacifica `try { approveBuilderCode }
223/// catch { disable_builder_fee }`) can use it without a test-crate dep.
224pub fn panic_to_value(payload: Box<dyn std::any::Any + Send>) -> Value {
225    let msg = payload.downcast_ref::<String>().cloned()
226        .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string()))
227        .unwrap_or_else(|| "panic".to_string());
228    Value::Str(msg.into())
229}
230
231/// Parse a transpiled error payload (`"[Kind] message"`) into a typed
232/// `ExchangeError`. Falls back to the generic `ExchangeError` kind when
233/// the payload doesn't carry a leading `[Kind]` marker.
234pub fn panic_msg_to_error(msg: &str) -> crate::ExchangeError {
235    if let Some(start) = msg.find('[') {
236        let after = &msg[start + 1..];
237        if let Some(end) = after.find(']') {
238            let kind = &after[..end];
239            let rest = after[end + 1..].trim_start_matches(|c: char| c == ' ' || c == ':');
240            return crate::ExchangeError::new(kind, rest);
241        }
242    }
243    crate::ExchangeError::new("ExchangeError", msg)
244}
245
246/// Bridge an async exchange call's panic-based error convention onto Rust's
247/// `Result`. The transpiled bodies use `panic!("[Kind] message")` (mirroring
248/// the TS `throw new <Kind>(message)` pattern); the typed-wrapper layer
249/// wraps every delegate call in this helper so its public surface is
250/// idiomatic Rust (`Result<T, ExchangeError>`) rather than panicking.
251/// Synchronous sibling of [`call_typed`]: runs a closure that may signal an
252/// error the transpiled way (`panic!("[Kind] message")`) and converts that into
253/// a typed `Result`. Used by the typed wrappers' non-async accessors.
254pub fn catch_typed<F, T>(f: F) -> crate::Result<T>
255where
256    F: FnOnce() -> T,
257{
258    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
259        Ok(v) => Ok(v),
260        Err(payload) => {
261            let msg = payload.downcast_ref::<String>().cloned()
262                .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string()))
263                .unwrap_or_else(|| "panic".to_string());
264            Err(panic_msg_to_error(&msg))
265        }
266    }
267}
268
269pub async fn call_typed<F, T>(fut: F) -> crate::Result<T>
270where
271    F: std::future::Future<Output = T>,
272{
273    use futures::FutureExt;
274    use std::panic::AssertUnwindSafe;
275    match AssertUnwindSafe(fut).catch_unwind().await {
276        Ok(v) => Ok(v),
277        Err(payload) => {
278            let msg = payload.downcast_ref::<String>().cloned()
279                .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string()))
280                .unwrap_or_else(|| "panic".to_string());
281            Err(panic_msg_to_error(&msg))
282        }
283    }
284}
285
286/// Mirrors TS `e instanceof <ClassName>`: panic payloads in the
287/// transpiled tests are `Value::Str(format!("[{kind}] {message}"))`
288/// (see `ExchangeError`'s `Display` impl), so the class name is whatever
289/// sits between the first pair of square brackets. Matches the
290/// expected-error-class names that broker-id and static-request tests
291/// pass as `Value::Str("InvalidProxySettings")`.
292pub fn is_instance(value: &Value, class: &Value) -> bool {
293    let (msg, cls) = match (value, class) {
294        (Value::Str(s), Value::Str(c)) => (s, c),
295        _ => return false,
296    };
297    // Errors are stringified as `[Kind] message` (see ExchangeError's
298    // Display). A direct `[cls]` hit covers the exact class and any
299    // non-hierarchy class name.
300    if msg.contains(&format!("[{cls}]")) {
301        return true;
302    }
303    // Hierarchy-aware check: `[RateLimitExceeded]` IS-A `OperationFailed`.
304    // Extract the actual class from the leading `[Kind]` and walk its
305    // ancestor chain (errorHierarchy.ts) — without this, test_safe's
306    // `is_instance(e, "OperationFailed")` retry/warn path never fires for
307    // a rate-limit / network error and those get logged as failures.
308    if let Some(actual) = extract_error_kind(msg) {
309        let mut cur = error_parent(actual);
310        while let Some(c) = cur {
311            if c == cls.as_ref() {
312                return true;
313            }
314            cur = error_parent(c);
315        }
316    }
317    false
318}
319
320/// Extracts the class name from the leading `[Kind]` of an error message.
321fn extract_error_kind(msg: &str) -> Option<&str> {
322    let start = msg.find('[')? + 1;
323    let end = msg[start..].find(']')? + start;
324    Some(&msg[start..end])
325}
326
327/// Parent class in the CCXT error hierarchy (mirrors
328/// `ts/src/base/errorHierarchy.ts`). `None` for `BaseError` / unknowns.
329fn error_parent(class: &str) -> Option<&'static str> {
330    Some(match class {
331        // ExchangeError branch
332        "ExchangeError" => "BaseError",
333        "AuthenticationError" => "ExchangeError",
334        "PermissionDenied" => "AuthenticationError",
335        "AccountNotEnabled" => "PermissionDenied",
336        "AccountSuspended" => "AuthenticationError",
337        "ArgumentsRequired" => "ExchangeError",
338        "BadRequest" => "ExchangeError",
339        "BadSymbol" => "BadRequest",
340        "OperationRejected" => "ExchangeError",
341        "NoChange" => "OperationRejected",
342        "MarginModeAlreadySet" => "NoChange",
343        "MarketClosed" => "OperationRejected",
344        "ManualInteractionNeeded" => "OperationRejected",
345        "RestrictedLocation" => "OperationRejected",
346        "InsufficientFunds" => "ExchangeError",
347        "InvalidAddress" => "ExchangeError",
348        "AddressPending" => "InvalidAddress",
349        "InvalidOrder" => "ExchangeError",
350        "OrderNotFound" => "InvalidOrder",
351        "OrderNotCached" => "InvalidOrder",
352        "OrderImmediatelyFillable" => "InvalidOrder",
353        "OrderNotFillable" => "InvalidOrder",
354        "DuplicateOrderId" => "InvalidOrder",
355        "ContractUnavailable" => "InvalidOrder",
356        "NotSupported" => "ExchangeError",
357        "InvalidProxySettings" => "ExchangeError",
358        "ExchangeClosedByUser" => "ExchangeError",
359        // OperationFailed branch
360        "OperationFailed" => "BaseError",
361        "NetworkError" => "OperationFailed",
362        "DDoSProtection" => "NetworkError",
363        "RateLimitExceeded" => "NetworkError",
364        "ExchangeNotAvailable" => "NetworkError",
365        "OnMaintenance" => "ExchangeNotAvailable",
366        "InvalidNonce" => "NetworkError",
367        "ChecksumError" => "InvalidNonce",
368        "RequestTimeout" => "NetworkError",
369        "BadResponse" => "OperationFailed",
370        "NullResponse" => "BadResponse",
371        "CancelPending" => "OperationFailed",
372        "UnsubscribeError" => "BaseError",
373        _ => return None,
374    })
375}
376
377// ── element access ───────────────────────────────────────────────────────────
378
379pub fn get_value(obj: &Value, key: &Value) -> Value {
380    crate::value::get_value(obj, key)
381}
382
383/// Forge a `&mut Value` from a `&Value`. Used by the transpiler to
384/// emit nested-key writes (`this.options['k1'][k2] = v` in TS) inside
385/// `&self` parser methods like `bitstamp.parseCurrency` that accumulate
386/// state into `self.options`. The naive `&mut self.options.clone()`
387/// mutably borrows a temporary — the write never reaches `self.options`,
388/// silently breaking the parser.
389///
390/// SAFETY: the caller must guarantee no concurrent readers of the same
391/// `Value` exist. In CCXT's transpiled parsers the only reader is the
392/// owning exchange (called sequentially from a single test or fetch),
393/// so this is sound. Wraps the pointer cast in a function so the
394/// `invalid_reference_casting` lint can be allowed in one place. Mirrors
395/// `coerce_to_mut_unsafe` in `exchange_stubs.rs`.
396#[allow(clippy::mut_from_ref, invalid_reference_casting)]
397pub unsafe fn coerce_value_to_mut(v: &Value) -> &mut Value {
398    let ptr = v as *const Value as *mut Value;
399    &mut *ptr
400}
401
402pub fn get_value_mut<'a>(obj: &'a mut Value, key: &Value) -> &'a mut Value {
403    match (obj, key) {
404        (Value::Dict(m), Value::Str(k)) => Arc::make_mut(m).entry(k.to_string()).or_insert(Value::Null),
405        (Value::Arr(a), Value::Int(i)) => {
406            let idx = *i as usize;
407            let a = Arc::make_mut(a);
408            while a.len() <= idx { a.push(Value::Null); }
409            &mut a[idx]
410        }
411        (other, _) => other,
412    }
413}
414
415pub fn add_element_to_object(obj: &mut Value, key: &Value, val: Value) {
416    match (obj, key) {
417        (Value::Dict(m), Value::Str(k)) => {
418            if crate::value::try_book_meta_write(m, k, &val) { return; }
419            // Persist to the live client AND update the local snapshot (see
420            // set_value) so a read-back of client.subscriptions is coherent.
421            crate::value::try_ws_subs_write(m, k, &val);
422            crate::value::try_ws_sub_field_write(m, k, &val);
423            // A write onto a tagged cache-hashmap bucket (`cache.hashmap[sym][id]
424            // = order`) must reach the shared CACHE_STORE, not just this local
425            // COW clone — mirrors the JS reference write.
426            crate::value::try_cache_hashmap_write(m, k, &val);
427            Arc::make_mut(m).insert(k.to_string(), val);
428        }
429        (Value::Dict(m), other) => { Arc::make_mut(m).insert(stringify_simple(other), val); }
430        (Value::Arr(a), Value::Int(i)) => {
431            let idx = *i as usize;
432            let a = Arc::make_mut(a);
433            while a.len() <= idx { a.push(Value::Null); }
434            a[idx] = val;
435        }
436        _ => {}
437    }
438}
439
440pub fn remove(obj: &mut Value, key: &Value) {
441    match (obj, key) {
442        (Value::Dict(m), Value::Str(k)) => {
443            crate::value::try_ws_subs_remove(m, k);
444            Arc::make_mut(m).shift_remove(k.as_ref());
445        }
446        (Value::Arr(a), Value::Int(i)) => {
447            let idx = *i as usize;
448            let a = Arc::make_mut(a);
449            if idx < a.len() { a.remove(idx); }
450        }
451        _ => {}
452    }
453}
454
455/// `Array.prototype.shift()` — removes and returns the first element.
456/// Called as a free function from transpiled WS code (`shift(stored)`).
457/// Returns `Value::Null` if the array is empty or the target isn't an
458/// array.
459pub fn shift(mut arr: Value) -> Value {
460    if let Value::Arr(a) = &mut arr {
461        let inner = Arc::make_mut(a);
462        if !inner.is_empty() { return inner.remove(0); }
463    }
464    Value::Null
465}
466
467pub fn in_op(obj: &Value, key: &Value) -> bool {
468    match (obj, key) {
469        (Value::Dict(m), Value::Str(k)) => m.contains_key(k.as_ref()),
470        (Value::Arr(a), v) => a.iter().any(|x| is_equal(x, v)),
471        _ => false,
472    }
473}
474
475/// Synthetic key that tags a live-subscriptions snapshot with its client URL
476/// (see `try_ws_subs_write`). It must never surface to transpiled code that
477/// enumerates `client.subscriptions` (upbit builds its subscribe frame from
478/// those keys), so filter it out of key/value enumeration.
479fn is_ws_internal_tag(k: &str) -> bool {
480    k == "__ws_subs_url" || k == "__ws_sub_ref"
481}
482
483pub fn object_keys(v: &Value) -> Value {
484    match v {
485        Value::Dict(m) => Value::Array(
486            m.keys().filter(|k| !is_ws_internal_tag(k))
487                .map(|k| Value::Str(k.clone().into())).collect()),
488        _ => Value::Array(vec![]),
489    }
490}
491
492pub fn object_values(v: &Value) -> Value {
493    match v {
494        Value::Dict(m) => Value::Array(
495            m.iter().filter(|(k, _)| !is_ws_internal_tag(k))
496                .map(|(_, val)| val.clone()).collect()),
497        _ => Value::Array(vec![]),
498    }
499}
500
501pub fn get_array_length(v: &Value) -> Value {
502    // Cache / order-book markers expose their rolling buffer via
503    // `_data` / `_entries` — `cache.length` in TS refers to the
504    // backing array, not the marker dict's keys. Look those up first
505    // so `get_array_length(&cache)` reports the right number.
506    if let Value::Dict(d) = v {
507        if let Some(n) = crate::value::book_cache_len_of(d) {
508            return Value::Int(n as i64);
509        }
510        if let Some(n) = crate::value::cache_len_of_marker(d) {
511            return Value::Int(n as i64);
512        }
513        if d.contains_key("__sideKind") {
514            return Value::Int(crate::value::side_entries_len(d) as i64);
515        }
516    }
517    Value::Int(v.len() as i64)
518}
519
520// ── JSON ────────────────────────────────────────────────────────────────────
521
522pub fn json_parse(v: &Value) -> Value {
523    match v {
524        Value::Str(s) => match serde_json::from_str::<serde_json::Value>(s) {
525            Ok(j)  => Value::from_json(&j),
526            Err(_) => Value::Null,
527        },
528        _ => Value::Null,
529    }
530}
531
532/// Wraps every JSON object number VALUE in quotes, replicating CCXT's
533/// `onJsonResponse` transform `responseBody.replace(/":([+.0-9eE-]+)([,}])/g, '":"$1"$2')`
534/// used when `quoteJsonNumbers` is on (the default). This preserves big
535/// integer ids and high-precision decimals as strings through parsing,
536/// matching how the unified parsers (safeString/safeNumber/Precise)
537/// expect to read them. Only object values (a number right after `":`
538/// and right before `,` or `}`) are quoted — array elements are left
539/// alone, mirroring the upstream regex. Byte-oriented so multi-byte
540/// UTF-8 in the surrounding text is preserved.
541pub fn quote_json_numbers(s: &str) -> String {
542    let b = s.as_bytes();
543    let n = b.len();
544    let mut out: Vec<u8> = Vec::with_capacity(n + 16);
545    let mut i = 0;
546    while i < n {
547        if b[i] == b'"' && i + 1 < n && b[i + 1] == b':' {
548            out.push(b'"');
549            out.push(b':');
550            let start = i + 2;
551            let mut j = start;
552            while j < n && matches!(b[j], b'+' | b'.' | b'0'..=b'9' | b'e' | b'E' | b'-') {
553                j += 1;
554            }
555            if j > start && j < n && (b[j] == b',' || b[j] == b'}') {
556                out.push(b'"');
557                out.extend_from_slice(&b[start..j]);
558                out.push(b'"');
559                out.push(b[j]);
560                i = j + 1;
561                continue;
562            }
563            i += 2;
564            continue;
565        }
566        out.push(b[i]);
567        i += 1;
568    }
569    String::from_utf8(out).unwrap_or_else(|_| s.to_string())
570}
571
572pub fn json_stringify(v: &Value) -> Value {
573    Value::Str(serde_json::to_string(&v.to_json()).unwrap_or_default().into())
574}
575
576// ── math ────────────────────────────────────────────────────────────────────
577
578pub fn math_floor(v: &Value) -> Value {
579    match as_f64(v) { Some(x) => Value::Float(x.floor()), None => Value::Null }
580}
581pub fn math_round(v: &Value) -> Value {
582    match as_f64(v) { Some(x) => Value::Float(x.round()), None => Value::Null }
583}
584pub fn math_ceil(v: &Value) -> Value {
585    match as_f64(v) { Some(x) => Value::Float(x.ceil()), None => Value::Null }
586}
587
588// ── misc ────────────────────────────────────────────────────────────────────
589
590pub fn println_val(v: &Value) {
591    println!("{v}");
592}
593
594/// Async equivalent of Promise.all — awaits all futures and collects results.
595/// Currently a stub: takes a Value::Array and returns it unchanged.
596pub async fn promise_all(v: &Value) -> Value {
597    v.clone()
598}
599
600// ── variadic / array helpers ─────────────────────────────────────────────────
601
602/// `get_arg(args, index, default)` — used by transpiled methods that accept
603/// `params = []` variadic optional arguments.
604pub fn get_arg(args: &[Value], idx: usize, default: Value) -> Value {
605    // JS default parameters trigger on `undefined`, so `f(a, b)` and
606    // `f(a, b, undefined, undefined)` both apply the declared defaults. The port
607    // collapses `undefined`/`null` into `Value::Null`, and virtual-dispatch
608    // wrappers forward *every* optional slot as an explicit `Null` (see
609    // exchange_generated `parse_order_book` → `DerivedExchange::parse_order_book`
610    // with six `get_arg(..., Null)` args). A plain `unwrap_or` would then hand an
611    // override an explicit `Null` and clobber its own default (ndax
612    // `parseOrderBook`'s priceKey=6/bidsKey='bids'), producing an empty book. So
613    // when the slot is `Null` *and* a non-`Null` default is declared, honour the
614    // default — matching JS. A `Null` default is unchanged (explicit `Null`
615    // stays `Null`).
616    match args.get(idx) {
617        None => default,
618        Some(Value::Null) if !matches!(default, Value::Null) => default,
619        Some(v) => v.clone(),
620    }
621}
622
623pub fn append_to_array(arr: &mut Value, v: Value) {
624    if crate::value::try_book_cache_push(arr, &v) { return; }
625    if let Value::Arr(a) = arr {
626        Arc::make_mut(a).push(v);
627    }
628}
629
630/// `obj[key].push(v)` — append to an array *field* of a dict in place. The
631/// transpiled `dict['bids'].push(x)` otherwise lowers to
632/// `append_to_array(&mut get_value(&dict, &key), x)`, whose `get_value` yields a
633/// COW clone, so the push is lost (paradex's order-book inserts). Mutate the
634/// field through the dict instead.
635pub fn append_to_object_array(obj: &mut Value, key: &Value, v: Value) {
636    // Registry-backed fields (a book's "cache") expose a live handle whose
637    // append already reflects — route through it.
638    let field = crate::get_value(obj, key);
639    if crate::value::try_book_cache_push(&field, &v) {
640        return;
641    }
642    // Plain array field: mutate through the dict (get_value would COW-clone).
643    if let (Value::Dict(m), Value::Str(k)) = (obj, key) {
644        let entry = Arc::make_mut(m).entry(k.to_string())
645            .or_insert_with(|| Value::Array(Vec::new()));
646        if let Value::Arr(a) = entry {
647            Arc::make_mut(a).push(v);
648        }
649    }
650}
651
652/// Recursively deep-extend `base` with `over` (CCXT `deepExtend` semantics):
653/// nested dicts are merged key-by-key rather than wholesale-replaced, and
654/// `over`'s leaves win on conflict. Used by generated init() to merge a pro
655/// Core's describe().options over the parent REST Core's — e.g. mexc's
656/// options.timeframes is a flat `{1m: Min1}` in the pro block but a nested
657/// `{spot, swap}` in REST; a shallow merge dropped one, breaking watchOHLCV's
658/// interval lookup. Deep-merge yields the union both forms rely on.
659pub fn deep_merge_dict(base: &Value, over: &Value) -> Value {
660    match (base, over) {
661        (Value::Dict(b), Value::Dict(o)) => {
662            let mut out = (**b).clone();
663            for (k, v) in o.iter() {
664                let merged = match out.get(k) {
665                    Some(existing) => deep_merge_dict(existing, v),
666                    None => v.clone(),
667                };
668                out.insert(k.clone(), merged);
669            }
670            Value::Map(out)
671        }
672        _ => over.clone(),
673    }
674}
675
676pub fn concat_arrays(a: &Value, b: &Value) -> Value {
677    match (a, b) {
678        (Value::Arr(x), Value::Arr(y)) => {
679            let mut out = (**x).clone();
680            out.extend(y.iter().cloned());
681            Value::Array(out)
682        }
683        _ => Value::Array(vec![]),
684    }
685}
686
687// ── error constructors – re-exported so transpiled code can call them ───────
688
689pub use crate::exchange_errors::*;
690pub use crate::precise::Precise;
691
692// ── Math (TS Math.min/max/abs/pow) ──────────────────────────────────────────
693
694#[allow(non_snake_case)]
695pub mod Math {
696    use super::Value;
697    use super::{as_f64, as_i64, both_ints};
698    // integer inputs to min/max/abs must stay integers (same contract as add/sub/mul above):
699    // a Float result serializes as `10.0` in request JSON bodies, which servers
700    // with strict integer fields reject (e.g. nado archive `limit: u32` -> HTTP 422),
701    // which matches how the other language ports treat these three helpers
702    pub fn min(a: &Value, b: &Value) -> Value {
703        if both_ints(a, b) { return Value::Int(as_i64(a).unwrap().min(as_i64(b).unwrap())); }
704        match (as_f64(a), as_f64(b)) { (Some(x), Some(y)) => Value::Float(x.min(y)), _ => Value::Null }
705    }
706    pub fn max(a: &Value, b: &Value) -> Value {
707        if both_ints(a, b) { return Value::Int(as_i64(a).unwrap().max(as_i64(b).unwrap())); }
708        match (as_f64(a), as_f64(b)) { (Some(x), Some(y)) => Value::Float(x.max(y)), _ => Value::Null }
709    }
710    pub fn abs(a: &Value) -> Value {
711        // checked_abs so i64::MIN falls through to the float branch instead of
712        // panicking on overflow, keeping the module's lenient no-panic contract
713        if let Value::Int(n) = a { if let Some(v) = n.checked_abs() { return Value::Int(v); } }
714        match as_f64(a) { Some(x) => Value::Float(x.abs()), None => Value::Null }
715    }
716    pub fn pow(a: &Value, b: &Value) -> Value {
717        match (as_f64(a), as_f64(b)) { (Some(x), Some(y)) => Value::Float(x.powf(y)), _ => Value::Null }
718    }
719    pub fn floor(v: &Value) -> Value { super::math_floor(v) }
720    pub fn round(v: &Value) -> Value { super::math_round(v) }
721    pub fn ceil(v: &Value)  -> Value { super::math_ceil(v) }
722    pub fn log(v: &Value) -> Value {
723        match as_f64(v) { Some(x) => Value::Float(x.ln()), None => Value::Null }
724    }
725}
726
727// Allow `Math.min(...)` style access through a Math singleton with method
728// syntax (transpiler emits `Math.X(...)` which becomes `Math::X(...)` only
729// if the rust transpiler picks up FullPropertyAccessReplacements). Post-
730// processing in build/rustTranspiler.ts converts `Math.X(...)` to
731// `crate::runtime::Math::X(...)`.
732
733/// `join(array, separator)` — joins array elements into a string.
734pub fn join(arr: &Value, sep: &Value) -> Value {
735    let s = stringify_simple(sep);
736    if let Value::Arr(a) = arr {
737        let parts: Vec<String> = a.iter().map(stringify_simple).collect();
738        Value::Str(parts.join(&s).into())
739    } else { Value::Str(String::new().into()) }
740}
741
742/// Generic `.toString()` for Value.
743pub fn to_string_val(v: &Value) -> Value {
744    Value::Str(stringify_simple(v).into())
745}
746
747/// `parse_int(value)` — best-effort to integer.
748pub fn parse_int(v: &Value) -> Value {
749    match v {
750        Value::Int(_)   => v.clone(),
751        Value::Float(f) => Value::Int(*f as i64),
752        Value::Str(s)   => s.trim().parse::<i64>().map(Value::Int).unwrap_or(Value::Null),
753        _ => Value::Null,
754    }
755}
756
757/// `parse_float(value)` — best-effort to float.
758pub fn parse_float(v: &Value) -> Value {
759    match v {
760        Value::Float(_) => v.clone(),
761        Value::Int(n)   => Value::Float(*n as f64),
762        Value::Str(s)   => s.trim().parse::<f64>().map(Value::Float).unwrap_or(Value::Null),
763        _ => Value::Null,
764    }
765}
766
767/// `starts_with(haystack, prefix)` — true if Value haystack starts with prefix.
768pub fn starts_with(haystack: &Value, prefix: &Value) -> bool {
769    match (haystack, prefix) {
770        (Value::Str(h), Value::Str(p)) => h.starts_with(p.as_ref()),
771        _ => false,
772    }
773}
774
775/// `ends_with(haystack, suffix)` — true if Value haystack ends with suffix.
776pub fn ends_with(haystack: &Value, suffix: &Value) -> bool {
777    match (haystack, suffix) {
778        (Value::Str(h), Value::Str(s)) => h.ends_with(s.as_ref()),
779        _ => false,
780    }
781}
782
783/// `trim(s)` — string trim.
784pub fn trim(v: &Value) -> Value {
785    match v { Value::Str(s) => Value::Str(s.trim().to_string().into()), _ => Value::Null }
786}
787
788/// `contains(haystack, needle)` — substring check for `Value::Str`,
789/// element check for `Value::Array`. Used by the transpiled tests
790/// for `string.includes(...)` / `array.includes(...)` (the regex
791/// transpiler rewrites both into this free function).
792pub fn contains(haystack: &Value, needle: &Value) -> bool {
793    match (haystack, needle) {
794        (Value::Str(h), Value::Str(n))   => h.contains(n.as_ref()),
795        (Value::Arr(a), n)             => a.iter().any(|el| is_equal(el, n)),
796        _ => false,
797    }
798}
799
800// ── Numeric / precision constants (mirrors decimal_to_precision.ts) ─────────
801
802pub const TRUNCATE:  i64 = 0;
803pub const ROUND:     i64 = 1;
804pub const ROUND_UP:  i64 = 2;
805pub const ROUND_DOWN: i64 = 3;
806pub const DECIMAL_PLACES:       i64 = 2;
807pub const SIGNIFICANT_DIGITS:   i64 = 3;
808pub const TICK_SIZE: i64 = 4;
809pub const NO_PADDING:           i64 = 5;
810pub const PAD_WITH_ZERO:        i64 = 6;
811
812/// `string_replace(s, old, new)` — string replacement.
813pub fn string_replace(s: &Value, old: &Value, new_val: &Value) -> Value {
814    match (s, old, new_val) {
815        (Value::Str(s), Value::Str(o), Value::Str(n)) => Value::Str(s.replace(o.as_ref(), n.as_ref()).into()),
816        _ => s.clone(),
817    }
818}
819
820/// `split(s, delim)` — string split returning Value::Array of Value::Str.
821pub fn split(s: &Value, delim: &Value) -> Value {
822    match (s, delim) {
823        (Value::Str(s), Value::Str(d)) => {
824            Value::Array(s.split(d.as_ref()).map(|p| Value::Str(p.to_string().into())).collect())
825        }
826        _ => Value::Array(vec![]),
827    }
828}
829
830/// `repeat(s, n)` — repeat string n times.
831pub fn repeat(s: &Value, n: &Value) -> Value {
832    let count = match as_i64(n) { Some(v) => v as usize, None => 0 };
833    match s { Value::Str(s) => Value::Str(s.repeat(count).into()), _ => Value::Null }
834}
835
836/// RFC 4648 base32 decode (upper-case A–Z 2–7, `=` padding ignored). Unknown
837/// characters (e.g. spaces already stripped by `totp`) are skipped.
838fn base32_decode(s: &str) -> Vec<u8> {
839    const ALPHA: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
840    let mut buf: u32 = 0;
841    let mut bits: u32 = 0;
842    let mut out = Vec::new();
843    for c in s.bytes() {
844        let up = c.to_ascii_uppercase();
845        let val = match ALPHA.iter().position(|&x| x == up) {
846            Some(v) => v as u32,
847            None => continue,
848        };
849        buf = (buf << 5) | val;
850        bits += 5;
851        if bits >= 8 {
852            bits -= 8;
853            out.push((buf >> bits) as u8);
854        }
855    }
856    out
857}
858
859/// `totp(secret)` — RFC 6238 time-based one-time password (HMAC-SHA1, 30s step,
860/// 6 digits), mirroring `ts/src/base/functions/totp.ts`. The `secret` is a
861/// base32 string (spaces allowed, as in "4TDV WOGO"). Returns `Value::Null` for
862/// a non-string secret.
863pub fn totp(secret: Value) -> Value {
864    use hmac::{Hmac, Mac};
865    use sha1::Sha1;
866    let sec = match &secret {
867        Value::Str(s) => s.replace(' ', ""),
868        _ => return Value::Null,
869    };
870    let key = base32_decode(&sec);
871    let epoch = std::time::SystemTime::now()
872        .duration_since(std::time::UNIX_EPOCH)
873        .map(|d| d.as_secs())
874        .unwrap_or(0);
875    let counter: u64 = epoch / 30;
876    let mut mac = match Hmac::<Sha1>::new_from_slice(&key) {
877        Ok(m) => m,
878        Err(_) => return Value::Null,
879    };
880    mac.update(&counter.to_be_bytes());
881    let digest = mac.finalize().into_bytes(); // 20 bytes
882    let offset = (digest[19] & 0x0f) as usize;
883    let code = ((digest[offset] as u32 & 0x7f) << 24)
884        | ((digest[offset + 1] as u32) << 16)
885        | ((digest[offset + 2] as u32) << 8)
886        | (digest[offset + 3] as u32);
887    Value::Str(format!("{:06}", code % 1_000_000).into())
888}
889
890/// `encode(s)` — UTF-8 bytes of a string as a byte-array Value.
891pub fn encode(s: Value) -> Value {
892    match &s {
893        Value::Str(st) => Value::Array(st.bytes().map(|b| Value::Int(b as i64)).collect()),
894        Value::Arr(_) => s,
895        _ => Value::Array(vec![]),
896    }
897}
898
899/// Free-function `hash(data, algo, digest)` — used by transpiled crypto
900/// code that imports `hash` from `base/functions/crypto.js`.
901pub fn hash(data: Value, algo: Value, digest: Value) -> Value {
902    let dbytes = crate::exchange::value_to_bytes(&data);
903    let a = match &algo { Value::Str(s) => s.as_ref(), _ => "sha256" };
904    let dg = match &digest { Value::Str(s) => s.as_ref(), _ => "hex" };
905    crate::exchange::digest_value(&crate::exchange::hash_raw(&dbytes, a), dg)
906}
907
908/// Free-function `hmac(data, secret, algo, digest)`.
909pub fn hmac(data: Value, secret: Value, algo: Value, digest: Value) -> Value {
910    let dbytes = crate::exchange::value_to_bytes(&data);
911    let sbytes = crate::exchange::value_to_bytes(&secret);
912    let a = match &algo { Value::Str(s) => s.as_ref(), _ => "sha256" };
913    let dg = match &digest { Value::Str(s) => s.as_ref(), _ => "hex" };
914    match crate::exchange::hmac_raw(&dbytes, &sbytes, a) {
915        Some(raw) => crate::exchange::digest_value(&raw, dg),
916        None => Value::Null,
917    }
918}
919
920/// `crc32(string, signed)` — IEEE CRC-32. With `signed = true` the u32 is
921/// reinterpreted as a signed 32-bit integer.
922pub fn crc32(s: Value, signed: Value) -> Value {
923    let bytes = crate::exchange::value_to_bytes(&s);
924    let mut crc: u32 = 0xFFFF_FFFF;
925    for &b in &bytes {
926        crc ^= b as u32;
927        for _ in 0..8 {
928            crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
929        }
930    }
931    crc = !crc;
932    if matches!(signed, Value::Bool(true)) {
933        Value::Int(crc as i32 as i64)
934    } else {
935        Value::Int(crc as i64)
936    }
937}
938
939/// Minimal protobuf wire-format reader over a byte slice, sufficient to
940/// decode mexc's `PushDataV3ApiWrapper` order-book frames.
941struct PbReader<'a> {
942    buf: &'a [u8],
943    pos: usize,
944}
945
946impl<'a> PbReader<'a> {
947    fn new(buf: &'a [u8]) -> Self {
948        Self { buf, pos: 0 }
949    }
950    fn eof(&self) -> bool {
951        self.pos >= self.buf.len()
952    }
953    /// Read a base-128 varint (LEB128, little-endian groups).
954    fn read_varint(&mut self) -> u64 {
955        let mut result: u64 = 0;
956        let mut shift = 0u32;
957        while self.pos < self.buf.len() && shift < 64 {
958            let b = self.buf[self.pos];
959            self.pos += 1;
960            result |= ((b & 0x7f) as u64) << shift;
961            if b & 0x80 == 0 {
962                break;
963            }
964            shift += 7;
965        }
966        result
967    }
968    /// Read a tag → (field number, wire type).
969    fn read_tag(&mut self) -> (u64, u8) {
970        let t = self.read_varint();
971        (t >> 3, (t & 7) as u8)
972    }
973    /// Read a length-delimited chunk (wire type 2).
974    fn read_bytes(&mut self) -> &'a [u8] {
975        let len = self.read_varint() as usize;
976        let end = self.pos.saturating_add(len).min(self.buf.len());
977        let s = &self.buf[self.pos..end];
978        self.pos = end;
979        s
980    }
981    /// Skip an unrecognised field by wire type.
982    fn skip(&mut self, wire: u8) {
983        match wire {
984            0 => {
985                self.read_varint();
986            }
987            1 => self.pos = self.pos.saturating_add(8).min(self.buf.len()),
988            2 => {
989                let len = self.read_varint() as usize;
990                self.pos = self.pos.saturating_add(len).min(self.buf.len());
991            }
992            5 => self.pos = self.pos.saturating_add(4).min(self.buf.len()),
993            _ => self.pos = self.buf.len(),
994        }
995    }
996}
997
998fn pb_string(b: &[u8]) -> Value {
999    Value::Str(String::from_utf8_lossy(b).into_owned().into())
1000}
1001
1002/// Decode a `Public*DepthV3ApiItem` — a `{ price, quantity }` pair.
1003fn pb_decode_depth_item(b: &[u8]) -> Value {
1004    let mut r = PbReader::new(b);
1005    let mut m: HashMap<String, Value> = HashMap::new();
1006    while !r.eof() {
1007        match r.read_tag() {
1008            (1, 2) => {
1009                m.insert("price".to_string(), pb_string(r.read_bytes()));
1010            }
1011            (2, 2) => {
1012                m.insert("quantity".to_string(), pb_string(r.read_bytes()));
1013            }
1014            (_, wire) => r.skip(wire),
1015        }
1016    }
1017    Value::Map(m)
1018}
1019
1020/// Decode a depth body (`PublicAggreDepthsV3Api` / `PublicIncreaseDepthsV3Api`
1021/// / `PublicLimitDepthsV3Api` — all share `asks`=1, `bids`=2, `eventType`=3).
1022fn pb_decode_depths(b: &[u8]) -> Value {
1023    let mut r = PbReader::new(b);
1024    let mut asks: Vec<Value> = Vec::new();
1025    let mut bids: Vec<Value> = Vec::new();
1026    let mut m: HashMap<String, Value> = HashMap::new();
1027    while !r.eof() {
1028        match r.read_tag() {
1029            (1, 2) => asks.push(pb_decode_depth_item(r.read_bytes())),
1030            (2, 2) => bids.push(pb_decode_depth_item(r.read_bytes())),
1031            (3, 2) => {
1032                m.insert("eventType".to_string(), pb_string(r.read_bytes()));
1033            }
1034            (4, 2) => {
1035                m.insert("fromVersion".to_string(), pb_string(r.read_bytes()));
1036            }
1037            (5, 2) => {
1038                m.insert("toVersion".to_string(), pb_string(r.read_bytes()));
1039            }
1040            (_, wire) => r.skip(wire),
1041        }
1042    }
1043    m.insert("asks".to_string(), Value::List(asks));
1044    m.insert("bids".to_string(), Value::List(bids));
1045    Value::Map(m)
1046}
1047
1048/// Decode a book-ticker body (`PublicBookTickerV3Api` / `PublicAggreBook
1049/// TickerV3Api` — bidPrice=1, bidQuantity=2, askPrice=3, askQuantity=4).
1050fn pb_decode_book_ticker(b: &[u8]) -> Value {
1051    let mut r = PbReader::new(b);
1052    let mut m: HashMap<String, Value> = HashMap::new();
1053    let fields = ["bidPrice", "bidQuantity", "askPrice", "askQuantity"];
1054    while !r.eof() {
1055        match r.read_tag() {
1056            (n @ 1..=4, 2) => {
1057                m.insert(fields[(n - 1) as usize].to_string(), pb_string(r.read_bytes()));
1058            }
1059            (_, wire) => r.skip(wire),
1060        }
1061    }
1062    Value::Map(m)
1063}
1064
1065/// Decode a deal item (`PublicDealsV3ApiItem` / `PublicAggreDealsV3ApiItem` —
1066/// price=1, quantity=2, tradeType=3 (varint), time=4 (varint)).
1067fn pb_decode_deal_item(b: &[u8]) -> Value {
1068    let mut r = PbReader::new(b);
1069    let mut m: HashMap<String, Value> = HashMap::new();
1070    while !r.eof() {
1071        match r.read_tag() {
1072            (1, 2) => { m.insert("price".to_string(), pb_string(r.read_bytes())); }
1073            (2, 2) => { m.insert("quantity".to_string(), pb_string(r.read_bytes())); }
1074            (3, 0) => { m.insert("tradeType".to_string(), Value::Int(r.read_varint() as i64)); }
1075            (4, 0) => { m.insert("time".to_string(), Value::Int(r.read_varint() as i64)); }
1076            (_, wire) => r.skip(wire),
1077        }
1078    }
1079    Value::Map(m)
1080}
1081
1082/// Decode a deals body (`PublicDealsV3Api` / `PublicAggreDealsV3Api` —
1083/// deals=1 (repeated), eventType=2).
1084fn pb_decode_deals(b: &[u8]) -> Value {
1085    let mut r = PbReader::new(b);
1086    let mut deals: Vec<Value> = Vec::new();
1087    let mut m: HashMap<String, Value> = HashMap::new();
1088    while !r.eof() {
1089        match r.read_tag() {
1090            (1, 2) => deals.push(pb_decode_deal_item(r.read_bytes())),
1091            (2, 2) => { m.insert("eventType".to_string(), pb_string(r.read_bytes())); }
1092            (_, wire) => r.skip(wire),
1093        }
1094    }
1095    m.insert("deals".to_string(), Value::List(deals));
1096    Value::Map(m)
1097}
1098
1099/// Decode a spot-kline body (`PublicSpotKlineV3Api`).
1100fn pb_decode_spot_kline(b: &[u8]) -> Value {
1101    let mut r = PbReader::new(b);
1102    let mut m: HashMap<String, Value> = HashMap::new();
1103    while !r.eof() {
1104        match r.read_tag() {
1105            (1, 2) => { m.insert("interval".to_string(), pb_string(r.read_bytes())); }
1106            (2, 0) => { m.insert("windowStart".to_string(), Value::Int(r.read_varint() as i64)); }
1107            (3, 2) => { m.insert("openingPrice".to_string(), pb_string(r.read_bytes())); }
1108            (4, 2) => { m.insert("closingPrice".to_string(), pb_string(r.read_bytes())); }
1109            (5, 2) => { m.insert("highestPrice".to_string(), pb_string(r.read_bytes())); }
1110            (6, 2) => { m.insert("lowestPrice".to_string(), pb_string(r.read_bytes())); }
1111            (7, 2) => { m.insert("volume".to_string(), pb_string(r.read_bytes())); }
1112            (8, 2) => { m.insert("amount".to_string(), pb_string(r.read_bytes())); }
1113            (9, 0) => { m.insert("windowEnd".to_string(), Value::Int(r.read_varint() as i64)); }
1114            (_, wire) => r.skip(wire),
1115        }
1116    }
1117    Value::Map(m)
1118}
1119
1120/// Decode mexc's `PushDataV3ApiWrapper` protobuf frame into the same shape
1121/// protobufjs' `.toJSON()` produces, so the ported handlers read it unchanged.
1122/// Wires the public order-book (depth), book-ticker, deals and kline bodies.
1123pub fn decode_mexc_push_data(bytes: &[u8]) -> Value {
1124    let mut r = PbReader::new(bytes);
1125    let mut m: HashMap<String, Value> = HashMap::new();
1126    while !r.eof() {
1127        match r.read_tag() {
1128            (1, 2) => {
1129                m.insert("channel".to_string(), pb_string(r.read_bytes()));
1130            }
1131            (3, 2) => {
1132                m.insert("symbol".to_string(), pb_string(r.read_bytes()));
1133            }
1134            (4, 2) => {
1135                m.insert("symbolId".to_string(), pb_string(r.read_bytes()));
1136            }
1137            (5, 0) => {
1138                m.insert("createTime".to_string(), Value::Int(r.read_varint() as i64));
1139            }
1140            (6, 0) => {
1141                m.insert("sendTime".to_string(), Value::Int(r.read_varint() as i64));
1142            }
1143            (302, 2) => {
1144                m.insert("publicIncreaseDepths".to_string(), pb_decode_depths(r.read_bytes()));
1145            }
1146            (303, 2) => {
1147                m.insert("publicLimitDepths".to_string(), pb_decode_depths(r.read_bytes()));
1148            }
1149            (313, 2) => {
1150                m.insert("publicAggreDepths".to_string(), pb_decode_depths(r.read_bytes()));
1151            }
1152            (301, 2) => {
1153                m.insert("publicDeals".to_string(), pb_decode_deals(r.read_bytes()));
1154            }
1155            (314, 2) => {
1156                m.insert("publicAggreDeals".to_string(), pb_decode_deals(r.read_bytes()));
1157            }
1158            (305, 2) => {
1159                m.insert("publicBookTicker".to_string(), pb_decode_book_ticker(r.read_bytes()));
1160            }
1161            (315, 2) => {
1162                m.insert("publicAggreBookTicker".to_string(), pb_decode_book_ticker(r.read_bytes()));
1163            }
1164            (308, 2) => {
1165                m.insert("publicSpotKline".to_string(), pb_decode_spot_kline(r.read_bytes()));
1166            }
1167            (_, wire) => r.skip(wire),
1168        }
1169    }
1170    Value::Map(m)
1171}
1172
1173/// `rsa(message, key, hash)` — RSA PKCS#1 v1.5 signature (SHA-256),
1174/// returned base64-encoded. `key` is a PKCS#1 PEM private key.
1175pub fn rsa(message: Value, key: Value, _hash: Value) -> Value {
1176    use rsa::RsaPrivateKey;
1177    use rsa::pkcs1::DecodeRsaPrivateKey;
1178    use rsa::pkcs1v15::SigningKey;
1179    use rsa::signature::{SignatureEncoding, Signer};
1180    let msg = crate::exchange::value_to_bytes(&message);
1181    let pem = String::from_utf8_lossy(&crate::exchange::value_to_bytes(&key)).into_owned();
1182    let pk = match RsaPrivateKey::from_pkcs1_pem(pem.trim()) {
1183        Ok(k) => k,
1184        Err(_) => return Value::Str(String::new().into()),
1185    };
1186    let signing_key = SigningKey::<sha2::Sha256>::new(pk);
1187    let sig = signing_key.sign(&msg);
1188    Value::Str(b64_encode(&sig.to_bytes()).into())
1189}
1190
1191/// `ecdsa(message, secret, curve, preHash)` — secp256k1 ECDSA signature
1192/// with public-key recovery. Returns `{r, s, v}` (hex r/s, integer
1193/// recovery id). `message` is a hex digest (already hashed) unless
1194/// `preHash` names a hash algorithm to apply first.
1195pub fn ecdsa(message: Value, secret: Value, _curve: Value, pre_hash: Value) -> Value {
1196    use k256::ecdsa::SigningKey;
1197    let empty = || Value::Map(indexmap::IndexMap::new());
1198    let msg_s = match &message { Value::Str(s) => s.trim_start_matches("0x").to_string(), _ => return empty() };
1199    let sk_s  = match &secret  { Value::Str(s) => s.trim_start_matches("0x").to_string(), _ => return empty() };
1200    let sk_bytes = match crate::exchange::hex_decode(&sk_s) { Some(b) => b, None => return empty() };
1201    // The 32-byte digest to sign.
1202    let digest: Vec<u8> = match &pre_hash {
1203        Value::Str(algo) => crate::exchange::hash_raw(
1204            &crate::exchange::value_to_bytes(&message), algo),
1205        _ => match crate::exchange::hex_decode(&msg_s) { Some(b) => b, None => return empty() },
1206    };
1207    let sk = match SigningKey::from_slice(&sk_bytes) { Ok(k) => k, Err(_) => return empty() };
1208    let (sig, recid) = match sk.sign_prehash_recoverable(&digest) {
1209        Ok(x) => x,
1210        Err(_) => return empty(),
1211    };
1212    let bytes = sig.to_bytes(); // 64 bytes: r || s, low-S normalized
1213    let mut m = indexmap::IndexMap::new();
1214    m.insert("r".to_string(), Value::Str(crate::exchange::hex_encode(&bytes[0..32]).into()));
1215    m.insert("s".to_string(), Value::Str(crate::exchange::hex_encode(&bytes[32..64]).into()));
1216    m.insert("v".to_string(), Value::Int(recid.to_byte() as i64));
1217    Value::Map(m)
1218}
1219
1220/// Strip PEM armor (`-----BEGIN…-----` / `-----END…-----`) and base64-decode the
1221/// body to DER bytes. Returns the input's raw base64 decode if there is no armor.
1222fn pem_to_der(pem: &str) -> Vec<u8> {
1223    use base64::{engine::general_purpose::STANDARD, Engine as _};
1224    let body: String = pem
1225        .lines()
1226        .filter(|l| !l.starts_with("-----"))
1227        .collect::<Vec<_>>()
1228        .join("");
1229    STANDARD.decode(body.trim()).unwrap_or_default()
1230}
1231
1232/// `eddsa(request, secret, curve)` — Ed25519 signature, mirroring
1233/// `ts/src/base/functions/crypto.ts`. `request` is the message (already-bytes
1234/// `Value::Arr` as produced by `encode(...)`, or a hex/utf8 string); `secret` is
1235/// either a 32-byte raw seed string or a base64/PEM PKCS#8 key (seed at DER
1236/// offset 16). Returns the standard-base64 signature. Fails loudly (NotSupported
1237/// panic) rather than returning an empty/invalid signature.
1238pub fn eddsa(request: Value, secret: Value, _curve: Value) -> Value {
1239    use ed25519_dalek::{Signer, SigningKey};
1240    let bad = |why: &str| -> ! {
1241        panic!("{}", crate::exchange_errors::not_supported(
1242            Value::Str(format!("eddsa: {why}").into())));
1243    };
1244    let msg: Vec<u8> = match &request {
1245        Value::Arr(_) => crate::exchange::value_to_bytes(&request),
1246        Value::Str(s) => {
1247            let t = s.trim_start_matches("0x");
1248            crate::exchange::hex_decode(t).unwrap_or_else(|| s.as_bytes().to_vec())
1249        }
1250        _ => bad("request must be bytes or a string"),
1251    };
1252    // The seed (32 bytes) comes in as either raw bytes (`Value::Arr`, e.g.
1253    // pacifica's base58-decoded key sliced to 32), a 32-char raw string, or a
1254    // base64/PEM PKCS#8 key (seed at DER offset 16).
1255    let seed: [u8; 32] = match &secret {
1256        Value::Arr(_) => {
1257            let b = crate::exchange::value_to_bytes(&secret);
1258            if b.len() >= 32 { b[..32].try_into().unwrap() } else { bad("seed shorter than 32 bytes") }
1259        }
1260        Value::Str(sec_s) if sec_s.len() == 32 => {
1261            sec_s.as_bytes().try_into().unwrap()
1262        }
1263        Value::Str(sec_s) => {
1264            let der = pem_to_der(sec_s);
1265            if der.len() >= 48 {
1266                der[16..48].try_into().unwrap()
1267            } else if der.len() >= 32 {
1268                der[der.len() - 32..].try_into().unwrap()
1269            } else {
1270                bad("secret is not a 32-byte seed or a decodable PKCS#8 key");
1271            }
1272        }
1273        _ => bad("secret must be a string or byte array"),
1274    };
1275    let sk = SigningKey::from_bytes(&seed);
1276    let sig = sk.sign(&msg);
1277    Value::Str(b64_encode(&sig.to_bytes()).into())
1278}
1279
1280/// Standard base64.
1281fn b64_encode(data: &[u8]) -> String {
1282    use base64::{engine::general_purpose::STANDARD, Engine as _};
1283    STANDARD.encode(data)
1284}
1285
1286/// URL-safe base64, no padding (the `urlencodeBase64` of CCXT).
1287fn b64url_encode(data: &[u8]) -> String {
1288    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
1289    URL_SAFE_NO_PAD.encode(data)
1290}
1291
1292/// `jwt(request, secret, algorithm, isRsa, opts)` — JSON Web Token.
1293/// HS256 (HMAC) or RS256 (RSA), signing `header.payload`.
1294pub fn jwt(request: Value, secret: Value, algorithm: Value, is_rsa: Value, _opts: Value) -> Value {
1295    let rsa_mode = matches!(is_rsa, Value::Bool(true));
1296    let bits = match algorithm.as_str() {
1297        Some("sha512") => "512",
1298        Some("sha384") => "384",
1299        _ => "256",
1300    };
1301    let alg = format!("{}{}", if rsa_mode { "RS" } else { "HS" }, bits);
1302    // Header keys must be in a fixed order — build the JSON literally.
1303    let header = format!("{{\"alg\":\"{alg}\",\"typ\":\"JWT\"}}");
1304    let payload = serde_json::to_string(&request.to_json()).unwrap_or_else(|_| "{}".to_string());
1305    let token = format!("{}.{}",
1306        b64url_encode(header.as_bytes()),
1307        b64url_encode(payload.as_bytes()));
1308    // Signature: standard base64 from rsa()/hmac(), then made URL-safe.
1309    let sig_std: String = if rsa_mode {
1310        match rsa(Value::Str(token.clone().into()), secret, algorithm) {
1311            Value::Str(s) => s.to_string(),
1312            _ => String::new(),
1313        }
1314    } else {
1315        match hmac(encode(Value::Str(token.clone().into())), secret, algorithm,
1316                   Value::Str("base64".into())) {
1317            Value::Str(s) => s.to_string(),
1318            _ => String::new(),
1319        }
1320    };
1321    let sig_url = sig_std.replace('+', "-").replace('/', "_")
1322        .trim_end_matches('=').to_string();
1323    Value::Str(format!("{token}.{sig_url}").into())
1324}
1325
1326/// `replace_str(s, old, new)` — string replacement, alias for string_replace.
1327pub fn replace_str(s: &Value, old: &Value, new_val: &Value) -> Value {
1328    string_replace(s, old, new_val)
1329}
1330
1331/// `replace_all_str(s, old, new)` — replace every occurrence (TS String.replaceAll).
1332pub fn replace_all_str(s: &Value, old: &Value, new_val: &Value) -> Value {
1333    let (Value::Str(sv), Value::Str(ov), Value::Str(nv)) = (s, old, new_val) else {
1334        return s.clone();
1335    };
1336    Value::Str(sv.replace(ov.as_ref(), nv.as_ref()).into())
1337}
1338
1339/// `Date.now()` — current Unix time in milliseconds.
1340pub fn date_now() -> Value {
1341    let ms = std::time::SystemTime::now()
1342        .duration_since(std::time::UNIX_EPOCH)
1343        .map(|d| d.as_millis() as i64)
1344        .unwrap_or(0);
1345    Value::Int(ms)
1346}
1347
1348/// `pad_start(s, len, pad)` / `pad_end` — left/right pad strings.
1349pub fn pad_start(s: &Value, len: &Value, pad: &Value) -> Value {
1350    let target = match as_i64(len) { Some(v) => v as usize, None => 0 };
1351    let p = match pad { Value::Str(p) => p.clone(), _ => " ".to_string().into() };
1352    match s {
1353        Value::Str(sv) => {
1354            if sv.chars().count() >= target { Value::Str(sv.clone()) }
1355            else {
1356                let need = target - sv.chars().count();
1357                Value::Str(format!("{}{}", p.repeat((need / p.chars().count().max(1)).max(1)), sv).into())
1358            }
1359        }
1360        _ => Value::Null,
1361    }
1362}
1363
1364pub fn pad_end(s: &Value, len: &Value, pad: &Value) -> Value {
1365    let target = match as_i64(len) { Some(v) => v as usize, None => 0 };
1366    let p = match pad { Value::Str(p) => p.clone(), _ => " ".to_string().into() };
1367    match s {
1368        Value::Str(sv) => {
1369            if sv.chars().count() >= target { Value::Str(sv.clone()) }
1370            else {
1371                let need = target - sv.chars().count();
1372                Value::Str(format!("{}{}", sv, p.repeat((need / p.chars().count().max(1)).max(1))).into())
1373            }
1374        }
1375        _ => Value::Null,
1376    }
1377}
1378
1379/// `to_fixed(x, digits)` — JS `Number.prototype.toFixed`: format a number
1380/// with a fixed number of decimal places, returned as a string.
1381pub fn to_fixed(x: &Value, digits: &Value) -> Value {
1382    let d = match as_i64(digits) { Some(v) => v.max(0) as usize, None => 0 };
1383    let n = match x {
1384        Value::Int(i) => *i as f64,
1385        Value::Float(f) => *f,
1386        Value::Str(s) => s.trim().parse::<f64>().unwrap_or(0.0),
1387        _ => 0.0,
1388    };
1389    Value::Str(format!("{:.*}", d, n).into())
1390}
1391
1392// ── Value helpers used by transpiled code in HashMap-construction blocks ─────