Skip to main content

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