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