1#![allow(non_snake_case, dead_code, unused_variables)]
17
18use crate::exchange::Exchange;
19use crate::runtime::stringify_param;
20use crate::{ExchangeError, Value};
21use chrono::{Datelike, TimeZone, Utc};
22use indexmap::IndexMap as HashMap;
23use std::sync::Arc;
24
25#[allow(clippy::mut_from_ref, invalid_reference_casting)]
28unsafe fn coerce_to_mut_unsafe(e: &Exchange) -> &mut Exchange {
29 let ptr = e as *const Exchange as *mut Exchange;
30 &mut *ptr
31}
32
33fn random_u64() -> u64 {
37 use std::sync::atomic::{AtomicU64, Ordering};
38 static COUNTER: AtomicU64 = AtomicU64::new(0);
39 let now = std::time::SystemTime::now()
40 .duration_since(std::time::UNIX_EPOCH)
41 .map(|d| d.as_nanos() as u64)
42 .unwrap_or(0);
43 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
44 let mut z = now ^ n.wrapping_mul(0x9E37_79B9_7F4A_7C15);
45 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
46 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
47 z ^ (z >> 31)
48}
49
50fn random_hex(n: usize) -> String {
52 let mut s = String::with_capacity(n);
53 while s.len() < n {
54 s.push_str(&format!("{:016x}", random_u64()));
55 }
56 s.truncate(n);
57 s
58}
59
60pub(crate) fn bytes_to_value(bytes: &[u8]) -> Value {
63 Value::Array(bytes.iter().map(|b| Value::Int(*b as i64)).collect())
64}
65
66fn is_byte_array(v: &Value) -> bool {
69 match v {
70 Value::Arr(a) => a
71 .iter()
72 .all(|x| matches!(x, Value::Int(n) if (0..=255).contains(n))),
73 _ => false,
74 }
75}
76
77fn urlencode_nested_walk(prefix: &str, v: &Value, out: &mut Vec<String>) {
80 match v {
81 Value::Dict(m) => {
82 for (k, val) in m.iter() {
83 urlencode_nested_walk(&format!("{prefix}[{k}]"), val, out);
84 }
85 }
86 Value::Arr(a) => {
87 for (i, val) in a.iter().enumerate() {
88 urlencode_nested_walk(&format!("{prefix}[{i}]"), val, out);
89 }
90 }
91 scalar => {
92 out.push(format!(
93 "{}={}",
94 prefix,
95 crate::exchange::url_pct(&stringify_param(scalar))
96 ));
97 }
98 }
99}
100
101fn dtp_num_to_string(x: f64) -> String {
104 format!("{x}")
105}
106
107fn precision_from_string_i64(s: &str) -> i64 {
109 if let Some(idx) = s.find(['e', 'E']) {
110 let exp: i64 = s[idx + 1..].parse().unwrap_or(0);
111 return -exp;
112 }
113 let trimmed = s.trim_end_matches('0');
114 match trimmed.split_once('.') {
115 Some((_, frac)) => frac.len() as i64,
116 None => 0,
117 }
118}
119
120fn truncate_to_string(num: &str, precision: i64) -> String {
122 if precision > 0 {
123 if let Some(dot) = num.find('.') {
124 let frac = &num[dot + 1..];
125 if frac.len() as i64 > precision {
126 return format!("{}.{}", &num[..dot], &frac[..precision as usize]);
127 }
128 }
129 return num.to_string();
130 }
131 let int_part = num.split('.').next().unwrap_or("0");
132 int_part
133 .parse::<i64>()
134 .map(|n| n.to_string())
135 .unwrap_or_else(|_| "0".to_string())
136}
137
138fn decimal_to_precision_impl(
140 x: &str,
141 rounding_mode: i64,
142 num_precision_digits: f64,
143 counting_mode: i64,
144 padding_mode: i64,
145) -> String {
146 use crate::runtime::{
147 DECIMAL_PLACES, NO_PADDING, ROUND, SIGNIFICANT_DIGITS, TICK_SIZE, TRUNCATE,
148 };
149 const ZERO: i64 = 48;
150 const ONE: i64 = 49;
151 const FIVE: i64 = 53;
152 const NINE: i64 = 57;
153
154 if num_precision_digits < 0.0 {
156 let to_nearest = 10f64.powf(-num_precision_digits);
157 let xnum: f64 = x.parse().unwrap_or(0.0);
158 if rounding_mode == ROUND {
159 let inner = decimal_to_precision_impl(
160 &dtp_num_to_string(xnum / to_nearest),
161 rounding_mode,
162 0.0,
163 counting_mode,
164 padding_mode,
165 );
166 let inner_num: f64 = inner.parse().unwrap_or(0.0);
167 return dtp_num_to_string(to_nearest * inner_num);
168 }
169 if rounding_mode == TRUNCATE {
170 return dtp_num_to_string(xnum - (xnum % to_nearest));
171 }
172 }
173
174 if counting_mode == TICK_SIZE {
176 let precision_digits_string = decimal_to_precision_impl(
177 &dtp_num_to_string(num_precision_digits),
178 ROUND,
179 22.0,
180 DECIMAL_PLACES,
181 NO_PADDING,
182 );
183 let new_npd = precision_from_string_i64(&precision_digits_string);
184 if rounding_mode == TRUNCATE {
185 let truncated_x = truncate_to_string(x, new_npd.max(0));
186 let x_num: f64 = truncated_x.parse().unwrap_or(0.0);
187 let scale = 10f64.powi(new_npd as i32);
188 let x_scaled = (x_num * scale).round();
189 let tick_scaled = (num_precision_digits * scale).round();
190 let ticks = (x_scaled / tick_scaled).trunc();
191 let x_new = (ticks * tick_scaled) / scale;
192 if padding_mode == NO_PADDING {
193 let fixed = format!("{:.*}", new_npd.max(0) as usize, x_new);
194 let renum: f64 = fixed.parse().unwrap_or(0.0);
195 return dtp_num_to_string(renum);
196 }
197 return decimal_to_precision_impl(
198 &dtp_num_to_string(x_new),
199 ROUND,
200 new_npd as f64,
201 DECIMAL_PLACES,
202 padding_mode,
203 );
204 }
205 let mut x_num: f64 = x.parse().unwrap_or(0.0);
206 let mut missing = x_num % num_precision_digits;
207 missing = decimal_to_precision_impl(
208 &dtp_num_to_string(missing),
209 ROUND,
210 8.0,
211 DECIMAL_PLACES,
212 NO_PADDING,
213 )
214 .parse()
215 .unwrap_or(0.0);
216 let fp_error = decimal_to_precision_impl(
217 &dtp_num_to_string(missing / num_precision_digits),
218 ROUND,
219 new_npd.max(8) as f64,
220 DECIMAL_PLACES,
221 NO_PADDING,
222 );
223 if precision_from_string_i64(&fp_error) != 0 {
224 if x_num > 0.0 {
225 if missing >= num_precision_digits / 2.0 {
226 x_num = x_num - missing + num_precision_digits;
227 } else {
228 x_num -= missing;
229 }
230 } else if missing >= num_precision_digits / 2.0 {
231 x_num -= missing;
232 } else {
233 x_num = x_num - missing - num_precision_digits;
234 }
235 }
236 return decimal_to_precision_impl(
237 &dtp_num_to_string(x_num),
238 ROUND,
239 new_npd as f64,
240 DECIMAL_PLACES,
241 padding_mode,
242 );
243 }
244
245 let npd = num_precision_digits as i64;
247 let bytes: Vec<u8> = x.as_bytes().to_vec();
248 let str_end = bytes.len() as i64;
249 if str_end == 0 {
250 return String::new();
251 }
252 let is_negative = bytes[0] == b'-';
253 let str_start: i64 = if is_negative { 1 } else { 0 };
254 let mut str_dot = str_end;
255 for k in 0..str_end {
256 if bytes[k as usize] == b'.' {
257 str_dot = k;
258 break;
259 }
260 }
261 let has_dot = str_dot < str_end;
262 let chars_len = ((str_end - str_start) + if has_dot { 0 } else { 1 }) as usize;
263 let mut chars = vec![ZERO as u8; chars_len];
264
265 let mut after_dot = chars_len as i64;
266 let mut digits_start: i64 = -1;
267 let mut digits_end: i64;
268 {
269 let mut i: i64 = 1;
270 let mut j: i64 = str_start;
271 while j < str_end {
272 let c = bytes[j as usize];
273 if c == b'.' {
274 after_dot = i;
275 i -= 1;
276 } else if !c.is_ascii_digit() {
277 return x.to_string();
278 } else {
279 if (i as usize) < chars.len() {
280 chars[i as usize] = c;
281 }
282 if c != b'0' && digits_start < 0 {
283 digits_start = i;
284 }
285 }
286 j += 1;
287 i += 1;
288 }
289 }
290 if digits_start < 0 {
291 digits_start = 1;
292 }
293
294 let mut precision_start = if counting_mode == DECIMAL_PLACES {
295 after_dot
296 } else {
297 digits_start
298 };
299
300 digits_end = -1;
301 let mut all_zeros = true;
302 let mut sign_needed = is_negative;
303 {
304 let mut memo: i64 = 0;
305 let mut i = chars.len() as i64 - 1;
306 while i >= 0 {
307 let mut c = chars[i as usize] as i64;
308 if i != 0 {
309 c += memo;
310 if i >= precision_start + npd {
311 let ceil =
312 (rounding_mode == ROUND) && (c >= FIVE) && !((c == FIVE) && memo != 0);
313 c = if ceil { NINE + 1 } else { ZERO };
314 }
315 if c > NINE {
316 c = ZERO;
317 memo = 1;
318 } else {
319 memo = 0;
320 }
321 } else if memo != 0 {
322 c = ONE;
323 }
324 chars[i as usize] = c as u8;
325 if c != ZERO {
326 all_zeros = false;
327 digits_start = i;
328 digits_end = if digits_end < 0 { i + 1 } else { digits_end };
329 }
330 i -= 1;
331 }
332 }
333
334 if counting_mode == SIGNIFICANT_DIGITS {
335 precision_start = digits_start;
336 }
337 let precision_end = precision_start + npd;
338 if all_zeros {
339 sign_needed = false;
340 }
341
342 let read_start = if digits_start >= after_dot || all_zeros {
343 after_dot - 1
344 } else {
345 digits_start
346 };
347 let read_end = if digits_end < after_dot {
348 after_dot
349 } else {
350 digits_end
351 };
352
353 let n_sign: i64 = if sign_needed { 1 } else { 0 };
354 let n_before_dot = n_sign + (after_dot - read_start);
355 let n_after_dot = (read_end - after_dot).max(0);
356 let actual_length = read_end - read_start;
357 let desired_length = if padding_mode == NO_PADDING {
358 actual_length
359 } else {
360 precision_end - read_start
361 };
362 let pad = (desired_length - actual_length).max(0);
363 let pad_start = n_before_dot + 1 + n_after_dot;
364 let pad_end = pad_start + pad;
365 let is_integer = (n_after_dot + pad) == 0;
366
367 let out_len =
368 (n_before_dot + if is_integer { 0 } else { 1 } + n_after_dot + pad).max(0) as usize;
369 let mut out = vec![ZERO as u8; out_len];
370 let get_char = |idx: i64| -> u8 {
371 if idx >= 0 && (idx as usize) < chars.len() {
372 chars[idx as usize]
373 } else {
374 ZERO as u8
375 }
376 };
377 if sign_needed && !out.is_empty() {
378 out[0] = b'-';
379 }
380 {
381 let mut i = n_sign;
382 let mut j = read_start;
383 while i < n_before_dot {
384 if (i as usize) < out.len() {
385 out[i as usize] = get_char(j);
386 }
387 i += 1;
388 j += 1;
389 }
390 }
391 if !is_integer && (n_before_dot as usize) < out.len() {
392 out[n_before_dot as usize] = b'.';
393 }
394 {
395 let mut i = n_before_dot + 1;
396 let mut j = after_dot;
397 while i < pad_start {
398 if (i as usize) < out.len() {
399 out[i as usize] = get_char(j);
400 }
401 i += 1;
402 j += 1;
403 }
404 }
405 {
406 let mut i = pad_start;
407 while i < pad_end {
408 if (i as usize) < out.len() {
409 out[i as usize] = ZERO as u8;
410 }
411 i += 1;
412 }
413 }
414 String::from_utf8(out).unwrap_or_default()
415}
416
417fn value_as_f64(v: Option<&Value>) -> f64 {
419 match v {
420 Some(Value::Int(n)) => *n as f64,
421 Some(Value::Float(f)) => *f,
422 Some(Value::Str(s)) => s.parse().unwrap_or(0.0),
423 _ => 0.0,
424 }
425}
426
427fn value_cmp(a: &Value, b: &Value) -> std::cmp::Ordering {
430 use std::cmp::Ordering;
431 let num = |v: &Value| -> Option<f64> {
432 match v {
433 Value::Int(n) => Some(*n as f64),
434 Value::Float(f) => Some(*f),
435 _ => None,
436 }
437 };
438 match (num(a), num(b)) {
439 (Some(x), Some(y)) => x.partial_cmp(&y).unwrap_or(Ordering::Equal),
440 _ => stringify_param(a).cmp(&stringify_param(b)),
441 }
442}
443
444const BASE58_ALPHABET: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
445
446fn base58_encode(input: &[u8]) -> String {
448 if input.is_empty() {
449 return String::new();
450 }
451 let zeros = input.iter().take_while(|&&b| b == 0).count();
452 let mut digits: Vec<u8> = Vec::new();
453 for &byte in input {
454 let mut carry = byte as u32;
455 for d in digits.iter_mut() {
456 carry += (*d as u32) << 8;
457 *d = (carry % 58) as u8;
458 carry /= 58;
459 }
460 while carry > 0 {
461 digits.push((carry % 58) as u8);
462 carry /= 58;
463 }
464 }
465 let mut out = String::with_capacity(zeros + digits.len());
466 for _ in 0..zeros {
467 out.push('1');
468 }
469 for &d in digits.iter().rev() {
470 out.push(BASE58_ALPHABET[d as usize] as char);
471 }
472 out
473}
474
475fn base58_decode(input: &str) -> Option<Vec<u8>> {
477 if input.is_empty() {
478 return Some(Vec::new());
479 }
480 let zeros = input.bytes().take_while(|&b| b == b'1').count();
481 let mut bytes: Vec<u8> = Vec::new();
482 for ch in input.bytes() {
483 let mut carry = BASE58_ALPHABET.iter().position(|&a| a == ch)? as u32;
484 for b in bytes.iter_mut() {
485 carry += (*b as u32) * 58;
486 *b = (carry & 0xff) as u8;
487 carry >>= 8;
488 }
489 while carry > 0 {
490 bytes.push((carry & 0xff) as u8);
491 carry >>= 8;
492 }
493 }
494 let mut out = vec![0u8; zeros];
495 out.extend(bytes.iter().rev());
496 Some(out)
497}
498
499fn arg_default(opt: &[Value]) -> Value {
500 opt.get(0).cloned().unwrap_or(Value::Null)
501}
502
503fn key_str(key: &Value) -> String {
504 stringify_param(key)
505}
506
507struct QueuedSpawn {
527 method: String,
528 args: Vec<Value>,
529 due_at: Option<std::time::Instant>,
530}
531
532thread_local! {
533 static SPAWN_QUEUE: std::cell::RefCell<Vec<QueuedSpawn>> =
534 std::cell::RefCell::new(Vec::new());
535}
536
537pub(crate) fn drain_spawn_queue() -> Vec<(String, Vec<Value>)> {
540 let now = std::time::Instant::now();
541 SPAWN_QUEUE.with(|q| {
542 let mut q = q.borrow_mut();
543 let mut due = Vec::new();
544 let mut pending = Vec::new();
545 for item in std::mem::take(&mut *q) {
546 if item.due_at.map(|t| t <= now).unwrap_or(true) {
547 due.push((item.method, item.args));
548 } else {
549 pending.push(item);
550 }
551 }
552 *q = pending;
553 due
554 })
555}
556
557pub(crate) fn next_spawn_due() -> Option<std::time::Duration> {
561 let now = std::time::Instant::now();
562 SPAWN_QUEUE.with(|q| {
563 q.borrow()
564 .iter()
565 .filter_map(|i| i.due_at)
566 .min()
567 .map(|t| t.saturating_duration_since(now))
568 })
569}
570
571pub async fn ws_await_flight(handle: &Value) -> Value {
576 crate::pro::ws_client::ws_await_flight(handle).await
577}
578
579pub fn enqueue_spawn(name: &str, args: Vec<Value>) {
584 SPAWN_QUEUE.with(|q| {
585 q.borrow_mut().push(QueuedSpawn {
586 method: name.to_string(),
587 args,
588 due_at: None,
589 })
590 });
591}
592
593pub fn enqueue_spawn_after(name: &str, args: Vec<Value>, ms: i64) {
598 let due_at = std::time::Instant::now() + std::time::Duration::from_millis(ms.max(0) as u64);
599 SPAWN_QUEUE.with(|q| {
600 q.borrow_mut().push(QueuedSpawn {
601 method: name.to_string(),
602 args,
603 due_at: Some(due_at),
604 })
605 });
606}
607
608impl Exchange {
609 pub fn exception_message(&self, exc: Value, _optional_args: &[Value]) -> Value {
618 let s = match exc {
619 Value::Str(s) => s,
620 other => crate::runtime::stringify_param(&other).into(),
621 };
622 let n = s.chars().count().min(100_000);
623 Value::Str(s.chars().take(n).collect())
624 }
625
626 pub fn get_ccxt_version(&self) -> Value {
635 Value::Str("4.5.71".into())
636 }
637
638 #[inline]
645 pub fn safe_value_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
646 let v = crate::value::get_value_k(&obj, key);
647 let missing = matches!(&v, Value::Null) || matches!(&v, Value::Str(s) if s.is_empty());
648 if missing {
649 arg_default(optional_args)
650 } else {
651 v
652 }
653 }
654
655 #[inline]
656 pub fn safe_string_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
657 let v = self.safe_value_k(obj, key, &[]);
658 match v {
659 Value::Str(_) => v,
660 Value::Int(n) => Value::Str(n.to_string().into()),
661 Value::Float(f) => Value::Str(f.to_string().into()),
662 _ => arg_default(optional_args),
665 }
666 }
667
668 #[inline]
669 pub fn safe_integer_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
670 let v = self.safe_value_k(obj, key, &[]);
671 match v {
672 Value::Int(_) => v,
673 Value::Float(f) => Value::Int(f as i64),
674 Value::Str(s) => match s.parse::<i64>() {
675 Ok(n) => Value::Int(n),
676 Err(_) => match s.parse::<f64>() {
677 Ok(f) if f.is_finite() => Value::Int(f as i64),
678 _ => arg_default(optional_args),
679 },
680 },
681 _ => arg_default(optional_args),
682 }
683 }
684
685 #[inline]
686 pub fn safe_float_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
687 let v = self.safe_value_k(obj, key, &[]);
688 match v {
689 Value::Float(_) => v,
690 Value::Int(n) => Value::Float(n as f64),
691 Value::Str(s) => match s.parse::<f64>() {
692 Ok(n) => Value::Float(n),
693 Err(_) => arg_default(optional_args),
694 },
695 _ => arg_default(optional_args),
696 }
697 }
698
699 #[inline]
700 pub fn safe_number_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
701 self.safe_float_k(obj, key, optional_args)
702 }
703
704 #[inline]
705 pub fn safe_bool_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
706 let v = self.safe_value_k(obj, key, &[]);
713 match v {
714 Value::Bool(_) => v,
715 _ => arg_default(optional_args),
716 }
717 }
718
719 #[inline]
720 pub fn safe_dict_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
721 let v = self.safe_value_k(obj, key, &[]);
722 if matches!(v, Value::Dict(_)) {
723 v
724 } else {
725 arg_default(optional_args)
726 }
727 }
728
729 #[inline]
730 pub fn safe_list_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
731 let v = self.safe_value_k(obj, key, &[]);
732 if matches!(v, Value::Arr(_)) {
733 v
734 } else {
735 arg_default(optional_args)
736 }
737 }
738
739 pub fn safe_value(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
740 let v = crate::get_value(&obj, &Value::Str(key_str(&key).into()));
745 let missing = matches!(&v, Value::Null) || matches!(&v, Value::Str(s) if s.is_empty());
746 if missing {
747 arg_default(optional_args)
748 } else {
749 v
750 }
751 }
752
753 pub fn safe_value2(&self, obj: Value, k1: Value, k2: Value, optional_args: &[Value]) -> Value {
754 let v = self.safe_value(obj.clone(), k1, &[]);
755 if !v.is_null() {
756 return v;
757 }
758 let v = self.safe_value(obj, k2, &[]);
759 if !v.is_null() {
760 v
761 } else {
762 arg_default(optional_args)
763 }
764 }
765
766 pub fn safe_value_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
767 if let Value::Arr(ks) = keys {
768 for k in ks.iter().cloned() {
769 let v = self.safe_value(obj.clone(), k, &[]);
770 if !v.is_null() {
771 return v;
772 }
773 }
774 }
775 arg_default(optional_args)
776 }
777
778 pub fn safe_string(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
779 let v = self.safe_value(obj, key, &[]);
780 match v {
781 Value::Str(_) => v,
782 Value::Int(n) => Value::Str(n.to_string().into()),
783 Value::Float(f) => Value::Str(f.to_string().into()),
784 Value::Null => arg_default(optional_args),
788 _ => arg_default(optional_args),
789 }
790 }
791
792 pub fn safe_string2(&self, obj: Value, k1: Value, k2: Value, optional_args: &[Value]) -> Value {
793 let v = self.safe_string(obj.clone(), k1, &[]);
794 if !v.is_null() {
795 return v;
796 }
797 let v = self.safe_string(obj, k2, &[]);
798 if !v.is_null() {
799 v
800 } else {
801 arg_default(optional_args)
802 }
803 }
804
805 pub fn safe_string_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
806 if let Value::Arr(ks) = keys {
807 for k in ks.iter().cloned() {
808 let v = self.safe_string(obj.clone(), k, &[]);
809 if !v.is_null() {
810 return v;
811 }
812 }
813 }
814 arg_default(optional_args)
815 }
816
817 pub fn safe_string_upper(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
824 let v = self.safe_string(obj, key, &[]);
825 if !v.is_null() {
826 if let Value::Str(s) = v {
827 return Value::Str(s.to_uppercase().into());
828 }
829 return v;
830 }
831 arg_default(optional_args)
832 }
833
834 #[inline]
836 pub fn safe_string_upper_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
837 let v = self.safe_string_k(obj, key, &[]);
838 if !v.is_null() {
839 if let Value::Str(s) = v {
840 return Value::Str(s.to_uppercase().into());
841 }
842 return v;
843 }
844 arg_default(optional_args)
845 }
846
847 pub fn safe_string_lower_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
848 if let Value::Arr(ks) = keys {
849 for k in ks.iter().cloned() {
850 let v = self.safe_string(obj.clone(), k, &[]);
851 if !v.is_null() {
852 if let Value::Str(s) = v {
853 return Value::Str(s.to_lowercase().into());
854 }
855 return v;
856 }
857 }
858 }
859 arg_default(optional_args)
860 }
861
862 pub fn safe_string_upper_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
863 if let Value::Arr(ks) = keys {
864 for k in ks.iter().cloned() {
865 let v = self.safe_string(obj.clone(), k, &[]);
866 if !v.is_null() {
867 if let Value::Str(s) = v {
868 return Value::Str(s.to_uppercase().into());
869 }
870 return v;
871 }
872 }
873 }
874 arg_default(optional_args)
875 }
876
877 pub fn safe_string_lower(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
878 let v = self.safe_string(obj, key, &[]);
879 if !v.is_null() {
880 if let Value::Str(s) = v {
881 return Value::Str(s.to_lowercase().into());
882 }
883 return v;
884 }
885 arg_default(optional_args)
886 }
887
888 #[inline]
891 pub fn safe_string_lower_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
892 let v = self.safe_string_k(obj, key, &[]);
893 if !v.is_null() {
894 if let Value::Str(s) = v {
895 return Value::Str(s.to_lowercase().into());
896 }
897 return v;
898 }
899 arg_default(optional_args)
900 }
901
902 pub fn safe_string_lower2(
903 &self,
904 obj: Value,
905 k1: Value,
906 k2: Value,
907 optional_args: &[Value],
908 ) -> Value {
909 let v = self.safe_string2(obj, k1, k2, &[]);
910 if !v.is_null() {
911 if let Value::Str(s) = v {
912 return Value::Str(s.to_lowercase().into());
913 }
914 return v;
915 }
916 arg_default(optional_args)
917 }
918
919 pub fn safe_string_upper2(
920 &self,
921 obj: Value,
922 k1: Value,
923 k2: Value,
924 optional_args: &[Value],
925 ) -> Value {
926 let v = self.safe_string2(obj, k1, k2, &[]);
927 if !v.is_null() {
928 if let Value::Str(s) = v {
929 return Value::Str(s.to_uppercase().into());
930 }
931 return v;
932 }
933 arg_default(optional_args)
934 }
935
936 pub fn super_currency(&self, _code: Value) -> Value {
940 Value::Null
941 }
942 pub fn super_handle_errors(
943 &self,
944 _code: Value,
945 _reason: Value,
946 _url: Value,
947 _method: Value,
948 _headers: Value,
949 _body: Value,
950 _response: Value,
951 _request_headers: Value,
952 _request_body: Value,
953 ) -> Value {
954 Value::Null
955 }
956
957 pub fn set_last_rest_request_timestamp(&self) {
964 let me = unsafe { coerce_to_mut_unsafe(self) };
965 me.lastRestRequestTimestamp = self.milliseconds();
966 }
967
968 pub fn set_last_request(&self, request: Value) {
969 let me = unsafe { coerce_to_mut_unsafe(self) };
970 me.last_request_headers =
971 crate::runtime::get_value(&request, &Value::Str("headers".into()));
972 me.last_request_body = crate::runtime::get_value(&request, &Value::Str("body".into()));
973 me.last_request_url = crate::runtime::get_value(&request, &Value::Str("url".into()));
974 }
975
976 pub fn get_fetch_cache(&self) -> Value {
977 self.fetchHistoryCache.clone()
978 }
979
980 pub fn add_fetch_cache(&self, data: Value) {
981 let me = unsafe { coerce_to_mut_unsafe(self) };
982 if crate::runtime::is_less_than_or_equal(&me.fetchHistoryCacheSize, &Value::Int(0)) {
983 return;
984 }
985 while crate::runtime::is_greater_than_or_equal(
986 &crate::runtime::get_array_length(&me.fetchHistoryCache),
987 &me.fetchHistoryCacheSize,
988 ) {
989 crate::runtime::remove(&mut me.fetchHistoryCache, &Value::Int(0));
990 }
991 crate::runtime::append_to_array(&mut me.fetchHistoryCache, data);
992 }
993
994 pub fn client(&mut self, args: &[Value]) -> Value {
1009 match args.get(0) {
1010 Some(Value::Str(url)) => crate::pro::ws_client::client_value(url),
1011 _ => Value::Null,
1012 }
1013 }
1014 pub fn spawn(&self, args: &[Value]) -> Value {
1019 if let Some(Value::Str(name)) = args.get(0) {
1021 let call_args: Vec<Value> = args.get(1..).map(|s| s.to_vec()).unwrap_or_default();
1022 enqueue_spawn(name, call_args);
1023 }
1024 Value::Null
1025 }
1026 pub async fn delay(&mut self, ms: Value, args: &[Value]) -> Value {
1027 if let Some(Value::Str(name)) = args.get(0) {
1034 let call_args: Vec<Value> = args.get(1..).map(|s| s.to_vec()).unwrap_or_default();
1035 enqueue_spawn_after(name, call_args, ms.as_f64().unwrap_or(0.0) as i64);
1036 }
1037 Value::Null
1038 }
1039 pub fn order_book(&self, args: &[Value]) -> Value {
1040 crate::pro::OrderBook::new(
1041 crate::runtime::get_arg(args, 0, Value::Null),
1042 crate::runtime::get_arg(args, 1, Value::Null),
1043 )
1044 }
1045 pub fn indexed_order_book(&self, args: &[Value]) -> Value {
1046 crate::pro::IndexedOrderBook::new(
1047 crate::runtime::get_arg(args, 0, Value::Null),
1048 crate::runtime::get_arg(args, 1, Value::Null),
1049 )
1050 }
1051 pub fn counted_order_book(&self, args: &[Value]) -> Value {
1052 crate::pro::CountedOrderBook::new(
1053 crate::runtime::get_arg(args, 0, Value::Null),
1054 crate::runtime::get_arg(args, 1, Value::Null),
1055 )
1056 }
1057 pub fn safe_order_tracker(&self, _args: &[Value]) -> Value {
1058 Value::Null
1059 }
1060 pub async fn un_watch(&mut self, _topic: Value, _args: &[Value]) -> Value {
1061 Value::Null
1062 }
1063 pub fn send(&self, _payload: Value) -> Value {
1064 Value::Null
1065 }
1066 pub fn lock_id(&self, _args: &[Value]) -> Value {
1067 Value::Null
1068 }
1069 pub fn unlock_id(&self, _args: &[Value]) -> Value {
1070 Value::Null
1071 }
1072 pub fn lock_last_nonce(&self, _args: &[Value]) -> Value {
1073 Value::Null
1074 }
1075 pub fn unlock_last_nonce(&self, _args: &[Value]) -> Value {
1076 Value::Null
1077 }
1078 pub fn extend_exchange_options(&self, _args: &[Value]) -> Value {
1079 Value::Null
1080 }
1081 pub fn on_error(&self, _args: &[Value]) -> Value {
1082 Value::Null
1083 }
1084 pub fn on_close(&self, _args: &[Value]) -> Value {
1085 Value::Null
1086 }
1087 pub fn on_pong(&self, _args: &[Value]) -> Value {
1088 Value::Null
1089 }
1090 pub fn crc32(&self, args: &[Value]) -> Value {
1094 let payload = args.get(0).cloned().unwrap_or(Value::Str(String::new().into()));
1095 let signed = args.get(1).cloned().unwrap_or(Value::Bool(false));
1096 crate::runtime::crc32(payload, signed)
1097 }
1098 pub fn decode_proto_msg(&self, args: &[Value]) -> Value {
1103 match args.get(0) {
1104 Some(v) if is_byte_array(v) => {
1105 let bytes = crate::exchange::value_to_bytes(v);
1106 crate::runtime::decode_mexc_push_data(&bytes)
1107 }
1108 Some(v) => v.clone(),
1109 None => Value::Null,
1110 }
1111 }
1112 pub async fn load_order_book(&mut self, _args: &[Value]) -> Value {
1115 Value::Null
1116 }
1117
1118 pub fn remove0x_prefix(&self, hex_data: Value) -> Value {
1125 match &hex_data {
1126 Value::Str(s) if s.len() >= 2 && (&s[0..2] == "0x" || &s[0..2] == "0X") => {
1127 Value::Str(s[2..].to_string().into())
1128 }
1129 _ => hex_data,
1130 }
1131 }
1132
1133 pub fn handle_http_status_code(&self, code: Value, reason: Value, url: Value, method: Value, body: Value) {
1136 let code_as_string = Value::Str(stringify_param(&code).into());
1137 if crate::runtime::in_op(&self.httpExceptions, &code_as_string) {
1138 let error_class = crate::runtime::get_value(&self.httpExceptions, &code_as_string);
1139 let message = [&self.id, &method, &url, &code_as_string, &reason, &body]
1140 .iter()
1141 .map(|part| stringify_param(part))
1142 .collect::<Vec<_>>()
1143 .join(" ");
1144 panic!("{}", crate::exchange_errors::create_error(&stringify_param(&error_class), message));
1145 }
1146 }
1147
1148 pub fn check_required_dependencies(&self) -> Value {
1151 Value::Null
1152 }
1153
1154 pub fn rand_number(&self, size: Value) -> Value {
1156 use rand::Rng;
1157 let n = size.as_i64().unwrap_or(0).max(0) as usize;
1158 let mut rng = rand::thread_rng();
1159 let mut s = String::new();
1160 for _ in 0..n {
1161 s.push(char::from(b'0' + rng.gen_range(0..10u8)));
1162 }
1163 Value::Int(s.parse::<i64>().unwrap_or(0))
1164 }
1165
1166 pub fn random_bytes(&self, length: Value) -> Value {
1168 use rand::Rng;
1169 let n = length.as_i64().unwrap_or(0).max(0) as usize;
1170 let mut rng = rand::thread_rng();
1171 let bytes: Vec<u8> = (0..n).map(|_| rng.gen()).collect();
1172 Value::Str(hex::encode(bytes).into())
1173 }
1174
1175 pub fn convert_to_big_int(&self, value: Value) -> Value {
1178 match &value {
1179 Value::Int(_) => value,
1180 Value::Float(f) => Value::Int(*f as i64),
1181 Value::Str(s) => {
1182 let t = s.trim();
1183 match t.parse::<i64>() {
1187 Ok(n) => Value::Int(n),
1188 Err(_) => Value::Str(t.to_string().into()),
1189 }
1190 }
1191 _ => Value::Int(0),
1192 }
1193 }
1194
1195 pub fn fix_stringified_json_members(&self, content: Value) -> Value {
1198 match &content {
1199 Value::Str(s) => Value::Str(
1200 s.replace('\\', "")
1201 .replace("\"{", "{")
1202 .replace("}\"", "}")
1203 .replace("\"[", "[")
1204 .replace("]\"", "]").into(),
1205 ),
1206 _ => content,
1207 }
1208 }
1209
1210 pub fn binary_concat_array(&self, arr: Value) -> Value {
1212 let mut out = String::new();
1213 if let Value::Arr(items) = &arr {
1214 for it in items.iter() {
1215 if let Value::Str(s) = it {
1216 out.push_str(s);
1217 }
1218 }
1219 }
1220 Value::Str(out.into())
1221 }
1222
1223 pub fn uuid5(&self, namespace: Value, name: Value) -> Value {
1225 use sha1::{Digest, Sha1};
1226 let ns = namespace.as_str().unwrap_or("").replace('-', "");
1227 let mut data: Vec<u8> = Vec::new();
1228 let mut i = 0;
1229 while i + 1 < ns.len() {
1230 if let Ok(b) = u8::from_str_radix(&ns[i..i + 2], 16) {
1231 data.push(b);
1232 }
1233 i += 2;
1234 }
1235 data.extend_from_slice(name.as_str().unwrap_or("").as_bytes());
1236 let mut hasher = Sha1::new();
1237 hasher.update(&data);
1238 let mut hash = hasher.finalize().to_vec();
1239 hash[6] = (hash[6] & 0x0f) | 0x50;
1240 hash[8] = (hash[8] & 0x3f) | 0x80;
1241 let h = hex::encode(&hash[0..16]);
1242 Value::Str(format!(
1243 "{}-{}-{}-{}-{}",
1244 &h[0..8],
1245 &h[8..12],
1246 &h[12..16],
1247 &h[16..20],
1248 &h[20..32]
1249 ).into())
1250 }
1251
1252 pub fn eth_abi_encode(&self, types: Value, values: Value) -> Value {
1262 use num_bigint::BigInt;
1263 let ts: Vec<Value> = match &types {
1264 Value::Arr(a) => (**a).clone(),
1265 _ => return Value::Null,
1266 };
1267 let vs: Vec<Value> = match &values {
1268 Value::Arr(a) => (**a).clone(),
1269 _ => return Value::Null,
1270 };
1271 let to_bytes = |v: &Value| -> Vec<u8> {
1272 match v {
1273 Value::Arr(a) => a
1274 .iter()
1275 .filter_map(|x| {
1276 if let Value::Int(n) = x {
1277 Some(*n as u8)
1278 } else {
1279 None
1280 }
1281 })
1282 .collect(),
1283 Value::Str(s) => hex::decode(s.trim_start_matches("0x")).unwrap_or_default(),
1284 _ => Vec::new(),
1285 }
1286 };
1287 let to_bigint = |v: &Value| -> BigInt {
1288 match v {
1289 Value::Int(n) => BigInt::from(*n),
1290 Value::Float(f) => BigInt::from(*f as i64),
1291 Value::Str(s) => {
1292 let t = s.trim();
1293 if let Some(h) = t.strip_prefix("0x") {
1294 BigInt::parse_bytes(h.as_bytes(), 16).unwrap_or_default()
1295 } else {
1296 BigInt::parse_bytes(t.as_bytes(), 10).unwrap_or_default()
1297 }
1298 }
1299 _ => BigInt::from(0),
1300 }
1301 };
1302 let mut out: Vec<u8> = Vec::new();
1303 for (t, v) in ts.iter().zip(vs.iter()) {
1304 let ty = match t {
1305 Value::Str(s) => s.as_ref(),
1306 _ => return Value::Null,
1307 };
1308 let mut word = [0u8; 32];
1309 if ty == "address" {
1310 let b = to_bytes(v);
1311 let n = b.len().min(20);
1312 word[32 - n..].copy_from_slice(&b[b.len() - n..]);
1313 } else if ty.starts_with("bytes") && ty != "bytes" {
1314 let b = to_bytes(v);
1316 let n = b.len().min(32);
1317 word[..n].copy_from_slice(&b[..n]);
1318 } else if ty.starts_with("uint") || ty.starts_with("int") {
1319 word = crate::exchange::eip712_int_word(ty, &to_bigint(v));
1322 } else if ty == "bool" {
1323 if matches!(v, Value::Bool(true)) {
1324 word[31] = 1;
1325 }
1326 } else {
1327 return Value::Null; }
1329 out.extend_from_slice(&word);
1330 }
1331 Value::Array(out.into_iter().map(|b| Value::Int(b as i64)).collect())
1332 }
1333
1334 pub fn set_property(&self, _property: Value, _optional_args: &[Value]) -> Value {
1338 Value::Null
1339 }
1340
1341 fn crypto_not_supported(&self, what: &str) -> ! {
1352 let id = match &self.id {
1353 Value::Str(s) => s.clone(),
1354 _ => String::new().into(),
1355 };
1356 panic!(
1357 "{}",
1358 crate::exchange_errors::not_supported(Value::Str(format!(
1359 "{id} {what}() signing is not implemented in the Rust port yet"
1360 ).into(),))
1361 );
1362 }
1363
1364 pub fn axolotl(&self, _payload: Value, _hex_key: Value, _ed25519: Value) -> Value {
1366 self.crypto_not_supported("axolotl")
1367 }
1368
1369 pub fn retrieve_stark_account(
1371 &self,
1372 _signature: Value,
1373 _class_hash: Value,
1374 _proxy_hash: Value,
1375 ) -> Value {
1376 Value::Null
1377 }
1378
1379 pub fn starknet_encode_structured_data(
1381 &self,
1382 _domain: Value,
1383 _types: Value,
1384 _data: Value,
1385 _address: Value,
1386 ) -> Value {
1387 Value::Null
1388 }
1389
1390 pub fn starknet_sign(&self, _msg_hash: Value, _pri: Value) -> Value {
1392 self.crypto_not_supported("starknetSign")
1393 }
1394
1395 pub fn extended_starknet_sign(&self, _msg_hash: Value, _pri: Value) -> Value {
1399 self.crypto_not_supported("extendedStarknetSign")
1400 }
1401
1402 pub fn extended_starknet_get_selector_from_name(&self, _name: Value) -> Value {
1404 Value::Null
1405 }
1406
1407 pub fn extended_starknet_compute_poseidon_hash_on_elements(&self, _data: Value) -> Value {
1409 Value::Null
1410 }
1411
1412 pub fn to_dydx_long(&self, _num_str: Value) -> Value {
1414 Value::Null
1415 }
1416
1417 pub fn retrieve_dydx_credentials(&self, _entropy: Value) -> Value {
1419 Value::Null
1420 }
1421
1422 pub async fn load_dydx_protos(&self) -> Value {
1424 Value::Null
1425 }
1426
1427 pub fn encode_dydx_tx_raw(&self, _sign_doc: Value, _signature: Value) -> Value {
1429 self.crypto_not_supported("encodeDydxTxRaw")
1430 }
1431
1432 pub fn encode_dydx_tx_for_simulation(
1434 &self,
1435 _message: Value,
1436 _memo: Value,
1437 _sequence: Value,
1438 _public_key: Value,
1439 ) -> Value {
1440 Value::Null
1441 }
1442
1443 pub fn encode_dydx_tx_for_signing(
1445 &self,
1446 _message: Value,
1447 _memo: Value,
1448 _chain_id: Value,
1449 _account: Value,
1450 _authenticators: Value,
1451 _optional_args: &[Value],
1452 ) -> Value {
1453 Value::Null
1454 }
1455
1456 pub async fn load_lighter_library(
1458 &self,
1459 _library_path: Value,
1460 _chain_id: Value,
1461 _private_key: Value,
1462 _api_key_index: Value,
1463 _account_index: Value,
1464 _optional_args: &[Value],
1465 ) -> Value {
1466 Value::Null
1467 }
1468
1469 pub fn lighter_create_client(
1471 &self,
1472 _signer: Value,
1473 _chain_id: Value,
1474 _private_key: Value,
1475 _api_key_index: Value,
1476 _account_index: Value,
1477 ) -> Value {
1478 Value::Null
1479 }
1480
1481 pub fn lighter_generate_api_key(&self, _signer: Value) -> Value {
1483 self.crypto_not_supported("lighterGenerateApiKey")
1484 }
1485
1486 pub async fn get_zk_transfer_signature_obj(
1488 &self,
1489 _seeds: Value,
1490 _optional_args: &[Value],
1491 ) -> Value {
1492 self.crypto_not_supported("getZKTransferSignatureObj")
1493 }
1494
1495 pub async fn get_zk_contract_signature_obj(
1497 &self,
1498 _seeds: Value,
1499 _optional_args: &[Value],
1500 ) -> Value {
1501 self.crypto_not_supported("getZKContractSignatureObj")
1502 }
1503
1504 pub async fn futures_transfer(
1507 &self,
1508 _code: Value,
1509 _amount: Value,
1510 _transfer_type: Value,
1511 _optional_args: &[Value],
1512 ) -> Value {
1513 Value::Null
1514 }
1515
1516 pub fn lighter_sign_create_order(&self, _signer: Value, _request: Value) -> Value {
1518 self.crypto_not_supported("lighterSignCreateOrder")
1519 }
1520 pub fn lighter_sign_create_grouped_orders(&self, _signer: Value, _request: Value) -> Value {
1521 self.crypto_not_supported("lighterSignCreateGroupedOrders")
1522 }
1523 pub fn lighter_sign_cancel_order(&self, _signer: Value, _request: Value) -> Value {
1524 self.crypto_not_supported("lighterSignCancelOrder")
1525 }
1526 pub fn lighter_sign_cancel_all_orders(&self, _signer: Value, _request: Value) -> Value {
1527 self.crypto_not_supported("lighterSignCancelAllOrders")
1528 }
1529 pub fn lighter_sign_withdraw(&self, _signer: Value, _request: Value) -> Value {
1530 self.crypto_not_supported("lighterSignWithdraw")
1531 }
1532 pub fn lighter_sign_create_sub_account(&self, _signer: Value, _request: Value) -> Value {
1533 self.crypto_not_supported("lighterSignCreateSubAccount")
1534 }
1535 pub fn lighter_sign_modify_order(&self, _signer: Value, _request: Value) -> Value {
1536 self.crypto_not_supported("lighterSignModifyOrder")
1537 }
1538 pub fn lighter_sign_transfer(&self, _signer: Value, _request: Value) -> Value {
1539 self.crypto_not_supported("lighterSignTransfer")
1540 }
1541 pub fn lighter_sign_update_leverage(&self, _signer: Value, _request: Value) -> Value {
1542 self.crypto_not_supported("lighterSignUpdateLeverage")
1543 }
1544 pub fn lighter_sign_update_margin(&self, _signer: Value, _request: Value) -> Value {
1545 self.crypto_not_supported("lighterSignUpdateMargin")
1546 }
1547 pub fn lighter_sign_approve_integrator(&self, _signer: Value, _request: Value) -> Value {
1548 self.crypto_not_supported("lighterSignApproveIntegrator")
1549 }
1550 pub fn lighter_sign_change_pubkey(&self, _signer: Value, _request: Value) -> Value {
1551 self.crypto_not_supported("lighterSignChangePubkey")
1552 }
1553 pub fn lighter_create_auth_token(&self, _signer: Value, _request: Value) -> Value {
1554 self.crypto_not_supported("lighterCreateAuthToken")
1555 }
1556
1557 pub fn urlencode_with_array_repeat(&self, params: Value) -> Value {
1560 let m = match ¶ms {
1561 Value::Dict(m) => m,
1562 _ => return Value::Str(String::new().into()),
1563 };
1564 let mut pairs: Vec<String> = Vec::new();
1565 for (k, v) in m.iter() {
1566 let key = crate::exchange::url_pct(k);
1567 match v {
1568 Value::Arr(items) => {
1569 for item in items.iter() {
1570 pairs.push(format!(
1571 "{}={}",
1572 key,
1573 crate::exchange::url_pct(&stringify_param(item))
1574 ));
1575 }
1576 }
1577 other => {
1578 pairs.push(format!(
1579 "{}={}",
1580 key,
1581 crate::exchange::url_pct(&stringify_param(other))
1582 ));
1583 }
1584 }
1585 }
1586 Value::Str(pairs.join("&").into())
1587 }
1588
1589 pub fn safe_integer(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
1590 let v = self.safe_value(obj, key, &[]);
1591 match v {
1592 Value::Int(_) => v,
1593 Value::Float(f) => Value::Int(f as i64),
1594 Value::Str(s) => match s.parse::<i64>() {
1598 Ok(n) => Value::Int(n),
1599 Err(_) => match s.parse::<f64>() {
1600 Ok(f) if f.is_finite() => Value::Int(f as i64),
1601 _ => arg_default(optional_args),
1602 },
1603 },
1604 _ => arg_default(optional_args),
1605 }
1606 }
1607
1608 pub fn safe_integer2(
1609 &self,
1610 obj: Value,
1611 k1: Value,
1612 k2: Value,
1613 optional_args: &[Value],
1614 ) -> Value {
1615 let v = self.safe_integer(obj.clone(), k1, &[]);
1616 if !v.is_null() {
1617 return v;
1618 }
1619 let v = self.safe_integer(obj, k2, &[]);
1620 if !v.is_null() {
1621 v
1622 } else {
1623 arg_default(optional_args)
1624 }
1625 }
1626
1627 pub fn safe_integer_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
1628 if let Value::Arr(ks) = keys {
1629 for k in ks.iter().cloned() {
1630 let v = self.safe_integer(obj.clone(), k, &[]);
1631 if !v.is_null() {
1632 return v;
1633 }
1634 }
1635 }
1636 arg_default(optional_args)
1637 }
1638
1639 pub fn safe_integer_product(
1642 &self,
1643 obj: Value,
1644 key: Value,
1645 factor: Value,
1646 optional_args: &[Value],
1647 ) -> Value {
1648 let v = self.safe_value(obj, key, &[]);
1649 let n = match v {
1650 Value::Int(n) => Some(n as f64),
1651 Value::Float(f) => Some(f),
1652 Value::Str(s) => s.parse::<f64>().ok(),
1653 _ => None,
1654 };
1655 let f = match factor {
1656 Value::Int(n) => n as f64,
1657 Value::Float(f) => f,
1658 _ => return arg_default(optional_args),
1659 };
1660 match n {
1661 Some(x) => Value::Int((x * f) as i64),
1662 None => arg_default(optional_args),
1663 }
1664 }
1665
1666 #[inline]
1668 pub fn safe_integer_product_k(
1669 &self,
1670 obj: Value,
1671 key: &str,
1672 factor: Value,
1673 optional_args: &[Value],
1674 ) -> Value {
1675 let v = self.safe_value_k(obj, key, &[]);
1676 let n = match v {
1677 Value::Int(n) => Some(n as f64),
1678 Value::Float(f) => Some(f),
1679 Value::Str(s) => s.parse::<f64>().ok(),
1680 _ => None,
1681 };
1682 let f = match factor {
1683 Value::Int(n) => n as f64,
1684 Value::Float(f) => f,
1685 _ => return arg_default(optional_args),
1686 };
1687 match n {
1688 Some(x) => Value::Int((x * f) as i64),
1689 None => arg_default(optional_args),
1690 }
1691 }
1692
1693 pub fn safe_integer_product2(
1694 &self,
1695 obj: Value,
1696 k1: Value,
1697 k2: Value,
1698 factor: Value,
1699 optional_args: &[Value],
1700 ) -> Value {
1701 let v = self.safe_integer_product(obj.clone(), k1, factor.clone(), &[]);
1702 if !v.is_null() {
1703 return v;
1704 }
1705 let v = self.safe_integer_product(obj, k2, factor, &[]);
1706 if !v.is_null() {
1707 v
1708 } else {
1709 arg_default(optional_args)
1710 }
1711 }
1712
1713 pub fn safe_integer_product_n(
1714 &self,
1715 obj: Value,
1716 keys: Value,
1717 factor: Value,
1718 optional_args: &[Value],
1719 ) -> Value {
1720 if let Value::Arr(ks) = keys {
1721 for k in ks.iter().cloned() {
1722 let v = self.safe_integer_product(obj.clone(), k, factor.clone(), &[]);
1723 if !v.is_null() {
1724 return v;
1725 }
1726 }
1727 }
1728 arg_default(optional_args)
1729 }
1730
1731 pub fn safe_timestamp2(
1732 &self,
1733 obj: Value,
1734 k1: Value,
1735 k2: Value,
1736 optional_args: &[Value],
1737 ) -> Value {
1738 self.safe_integer_product2(obj, k1, k2, Value::Int(1000), optional_args)
1739 }
1740
1741 pub fn safe_timestamp_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
1742 self.safe_integer_product_n(obj, keys, Value::Int(1000), optional_args)
1743 }
1744
1745 pub fn safe_float(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
1746 let v = self.safe_value(obj, key, &[]);
1747 match v {
1748 Value::Float(_) => v,
1749 Value::Int(n) => Value::Float(n as f64),
1750 Value::Str(s) => match s.parse::<f64>() {
1751 Ok(n) => Value::Float(n),
1752 Err(_) => arg_default(optional_args),
1753 },
1754 _ => arg_default(optional_args),
1755 }
1756 }
1757
1758 pub fn safe_timestamp(&self, obj: Value, key: Value, optional_args: &[Value]) -> Value {
1762 match self.safe_float(obj, key, &[]) {
1763 Value::Float(f) => Value::Int((f * 1000.0) as i64),
1764 Value::Int(n) => Value::Int(n * 1000),
1765 _ => arg_default(optional_args),
1766 }
1767 }
1768
1769 #[inline]
1771 pub fn safe_timestamp_k(&self, obj: Value, key: &str, optional_args: &[Value]) -> Value {
1772 match self.safe_float_k(obj, key, &[]) {
1773 Value::Float(f) => Value::Int((f * 1000.0) as i64),
1774 Value::Int(n) => Value::Int(n * 1000),
1775 _ => arg_default(optional_args),
1776 }
1777 }
1778
1779 pub fn is_empty(&self, v: Value) -> Value {
1783 let empty = match &v {
1784 Value::Null => true,
1785 Value::Arr(a) => a.is_empty(),
1786 Value::Dict(m) => m.is_empty(),
1787 _ => false,
1788 };
1789 Value::Bool(empty)
1790 }
1791
1792 pub fn value_is_defined(&self, v: Value) -> Value {
1793 Value::Bool(!v.is_null())
1794 }
1795
1796 pub fn extend(&self, a: Value, optional_args: &[Value]) -> Value {
1799 let mut out = match a {
1800 Value::Dict(m) => Arc::try_unwrap(m).unwrap_or_else(|x| (*x).clone()),
1801 _ => HashMap::new(),
1802 };
1803 let merge = |out: &mut HashMap<String, Value>, src: Value| {
1804 if let Value::Dict(m) = src {
1805 let m = Arc::try_unwrap(m).unwrap_or_else(|x| (*x).clone());
1806 for (k, v) in m {
1807 out.insert(k, v);
1808 }
1809 }
1810 };
1811 for extra in optional_args {
1812 merge(&mut out, extra.clone());
1813 }
1814 Value::Map(out)
1815 }
1816
1817 pub fn deep_extend(&self, a: Value, optional_args: &[Value]) -> Value {
1818 let mut current = a;
1819 for extra in optional_args {
1820 current = crate::value::deep_extend(current, extra.clone());
1821 }
1822 current
1823 }
1824
1825 pub fn omit(&self, obj: Value, keys: Value, _optional_args: &[Value]) -> Value {
1826 match obj {
1827 Value::Dict(mut m) => {
1828 let mm = Arc::make_mut(&mut m);
1829 match keys {
1830 Value::Arr(ks) => {
1831 for k in ks.iter() {
1832 if let Value::Str(s) = k {
1833 mm.shift_remove(s.as_ref());
1834 }
1835 }
1836 }
1837 Value::Str(s) => {
1838 mm.shift_remove(s.as_ref());
1839 }
1840 _ => {}
1841 }
1842 Value::Dict(m)
1843 }
1844 other => other,
1845 }
1846 }
1847
1848 pub fn omit_zero(&self, v: Value) -> Value {
1849 match &v {
1855 Value::Int(0) => Value::Null,
1856 Value::Float(f) if *f == 0.0 => Value::Null,
1857 Value::Str(s) => {
1858 if s.is_empty() {
1859 return Value::Null;
1860 }
1861 match s.parse::<f64>() {
1862 Ok(n) if n == 0.0 => Value::Null,
1863 _ => v,
1864 }
1865 }
1866 _ => v,
1867 }
1868 }
1869
1870 pub fn to_array(&self, v: Value) -> Value {
1873 if let Some(entries) = crate::value::cache_entries_as_value(&v) {
1877 return entries;
1878 }
1879 match v {
1880 Value::Arr(_) => v,
1881 Value::Dict(m) => Value::Array(m.values().cloned().collect()),
1882 Value::Null => Value::Array(vec![]),
1883 other => Value::Array(vec![other]),
1884 }
1885 }
1886
1887 pub fn array_concat(&self, a: Value, b: Value) -> Value {
1888 crate::runtime::concat_arrays(&a, &b)
1889 }
1890
1891 pub fn array_slice(&self, v: Value, start: Value, optional_args: &[Value]) -> Value {
1892 let Value::Arr(a) = v else {
1893 return Value::Array(vec![]);
1894 };
1895 let len = a.len() as i64;
1896 let s = match start {
1897 Value::Int(n) => n,
1898 _ => 0,
1899 };
1900 let s = if s < 0 {
1901 (len + s).max(0) as usize
1902 } else {
1903 (s as usize).min(a.len())
1904 };
1905 let e = match optional_args.get(0) {
1906 None | Some(Value::Null) => a.len(),
1907 Some(Value::Int(n)) => {
1908 if *n < 0 {
1909 ((len) + n).max(0) as usize
1910 } else {
1911 (*n as usize).min(a.len())
1912 }
1913 }
1914 _ => a.len(),
1915 };
1916 if s <= e {
1917 Value::Array(a[s..e].to_vec())
1918 } else {
1919 Value::Array(vec![])
1920 }
1921 }
1922
1923 pub fn in_array(&self, needle: Value, haystack: Value) -> Value {
1924 let hit = if let Value::Arr(a) = haystack {
1925 a.iter().any(|x| crate::runtime::is_equal(x, &needle))
1926 } else {
1927 false
1928 };
1929 Value::Bool(hit)
1930 }
1931
1932 pub fn unique(&self, v: Value) -> Value {
1933 if let Value::Arr(a) = v {
1934 let mut out: Vec<Value> = vec![];
1935 for item in a.iter().cloned() {
1936 if !out.iter().any(|x| crate::runtime::is_equal(x, &item)) {
1937 out.push(item);
1938 }
1939 }
1940 Value::Array(out)
1941 } else {
1942 Value::Array(vec![])
1943 }
1944 }
1945
1946 pub fn index_by(&self, arr: Value, key: Value) -> Value {
1947 let k = key_str(&key);
1948 let mut out: HashMap<String, Value> = HashMap::new();
1949 let items: Vec<Value> = match arr {
1955 Value::Arr(items) => Arc::try_unwrap(items).unwrap_or_else(|a| (*a).clone()),
1956 Value::Dict(m) => m.values().cloned().collect(),
1957 _ => return Value::Map(out),
1958 };
1959 for item in items {
1960 if let Some(kv) = crate::value::safe_string(&item, &k, None) {
1961 out.insert(kv, item);
1962 }
1963 }
1964 Value::Map(out)
1965 }
1966
1967 pub fn index_by_safe(&self, arr: Value, key: Value) -> Value {
1968 self.index_by(arr, key)
1969 }
1970
1971 pub fn group_by(&self, arr: Value, key: Value, _optional_args: &[Value]) -> Value {
1972 let k = key_str(&key);
1973 let mut out: HashMap<String, Vec<Value>> = HashMap::new();
1974 if let Value::Arr(items) = arr {
1975 for item in items.iter().cloned() {
1976 if let Some(kv) = crate::value::safe_string(&item, &k, None) {
1977 out.entry(kv).or_default().push(item);
1978 }
1979 }
1980 }
1981 Value::Map(out.into_iter().map(|(k, v)| (k, Value::Array(v))).collect())
1982 }
1983
1984 pub fn filter_by(
1985 &self,
1986 arr: Value,
1987 key: Value,
1988 value: Value,
1989 _optional_args: &[Value],
1990 ) -> Value {
1991 let k = key_str(&key);
1992 if let Value::Arr(items) = arr {
1993 let items = Arc::try_unwrap(items).unwrap_or_else(|a| (*a).clone());
1994 let out: Vec<Value> = items
1995 .into_iter()
1996 .filter(|it| {
1997 let v = crate::get_value(it, &Value::Str(k.clone().into()));
1998 crate::runtime::is_equal(&v, &value)
1999 })
2000 .collect();
2001 Value::Array(out)
2002 } else {
2003 Value::Array(vec![])
2004 }
2005 }
2006
2007 pub fn sort_by(&self, arr: Value, key: Value, optional_args: &[Value]) -> Value {
2010 let mut items = match arr {
2011 Value::Arr(a) => Arc::try_unwrap(a).unwrap_or_else(|x| (*x).clone()),
2012 other => return other,
2013 };
2014 let descending = matches!(optional_args.get(0), Some(Value::Bool(true)));
2015 let key = Value::Str(stringify_param(&key).into());
2016 items.sort_by(|a, b| {
2017 let av = crate::get_value(a, &key);
2018 let bv = crate::get_value(b, &key);
2019 let ord = value_cmp(&av, &bv);
2020 if descending {
2021 ord.reverse()
2022 } else {
2023 ord
2024 }
2025 });
2026 Value::Array(items)
2027 }
2028
2029 pub fn sort_by2(&self, arr: Value, k1: Value, k2: Value, optional_args: &[Value]) -> Value {
2032 let mut items = match arr {
2033 Value::Arr(a) => Arc::try_unwrap(a).unwrap_or_else(|x| (*x).clone()),
2034 other => return other,
2035 };
2036 let descending = matches!(optional_args.get(0), Some(Value::Bool(true)));
2037 let k1 = Value::Str(stringify_param(&k1).into());
2038 let k2 = Value::Str(stringify_param(&k2).into());
2039 items.sort_by(|a, b| {
2040 let ord = value_cmp(&crate::get_value(a, &k1), &crate::get_value(b, &k1)).then(
2041 value_cmp(&crate::get_value(a, &k2), &crate::get_value(b, &k2)),
2042 );
2043 if descending {
2044 ord.reverse()
2045 } else {
2046 ord
2047 }
2048 });
2049 Value::Array(items)
2050 }
2051
2052 pub fn keysort(&self, obj: Value, _optional_args: &[Value]) -> Value {
2053 if let Value::Dict(m) = obj {
2054 let mut keys: Vec<&String> = m.keys().collect();
2055 keys.sort();
2056 let mut out = HashMap::new();
2057 for k in &keys {
2058 out.insert((*k).clone(), m[*k].clone());
2059 }
2060 Value::Map(out)
2061 } else {
2062 obj
2063 }
2064 }
2065
2066 pub fn aggregate(&self, arr: Value) -> Value {
2070 let arr = crate::value::side_entries_as_value(&arr).unwrap_or(arr);
2074 let items = match arr {
2075 Value::Arr(a) => Arc::try_unwrap(a).unwrap_or_else(|x| (*x).clone()),
2076 _ => return Value::Array(vec![]),
2077 };
2078 let mut order: Vec<u64> = Vec::new();
2079 let mut buckets: HashMap<u64, (f64, f64)> = HashMap::new();
2080 for item in items {
2081 let row = match item {
2082 Value::Arr(r) => r,
2083 _ => continue,
2084 };
2085 let price = value_as_f64(row.get(0));
2086 let volume = value_as_f64(row.get(1));
2087 if volume > 0.0 {
2088 let bits = price.to_bits();
2089 let entry = buckets.entry(bits).or_insert_with(|| {
2090 order.push(bits);
2091 (price, 0.0)
2092 });
2093 entry.1 += volume;
2094 }
2095 }
2096 let out: Vec<Value> = order
2097 .iter()
2098 .map(|b| {
2099 let (p, v) = buckets[b];
2100 Value::Array(vec![Value::Float(p), Value::Float(v)])
2101 })
2102 .collect();
2103 Value::Array(out)
2104 }
2105 pub fn map_to_safe_map(&self, v: Value) -> Value {
2106 v
2107 }
2108 pub fn create_safe_dictionary(&self, _optional_args: &[Value]) -> Value {
2109 Value::Map(HashMap::new())
2110 }
2111
2112 pub fn check_option_string(&self, _method_name: Value, _option_name: Value, value: Value) -> Value {
2114 value
2115 }
2116 pub fn check_option_bool(&self, method_name: Value, option_name: Value, value: Value) -> Value {
2118 if value.is_null() {
2119 return Value::Null;
2120 }
2121 let parsed = match &value {
2122 Value::Bool(b) => Some(*b),
2123 Value::Str(s) if s == "true" || s == "false" => Some(s == "true"),
2124 Value::Int(n) if *n == 1 || *n == 0 => Some(*n == 1),
2125 Value::Float(n) if *n == 1.0 || *n == 0.0 => Some(*n == 1.0),
2126 _ => None,
2127 };
2128 if parsed.is_none() {
2129 let label = if method_name.is_null() { "exchange-wide".to_string() } else { format!("{}()", stringify_param(&method_name)) };
2130 let message = format!("{} {} option {} must be a boolean", stringify_param(&self.id), label, stringify_param(&option_name));
2131 panic!("{}", crate::exchange_errors::create_error("BadRequest", message));
2132 }
2133 Value::Bool(parsed == Some(true))
2134 }
2135 pub fn check_option_integer(&self, _method_name: Value, _option_name: Value, value: Value) -> Value {
2136 value
2137 }
2138
2139 pub fn clone_value(&self, v: Value) -> Value {
2142 v
2143 }
2144
2145 pub fn sum(&self, optional_args: &[Value]) -> Value {
2148 let mut acc: Option<Value> = None;
2149 for x in optional_args {
2150 acc = Some(match acc {
2151 None => x.clone(),
2152 Some(a) => crate::runtime::add(&a, x),
2153 });
2154 }
2155 acc.unwrap_or(Value::Null)
2156 }
2157
2158 pub fn parse_json_value(&self, v: Value) -> Value {
2164 match v {
2165 Value::Str(s) => {
2166 let prepared = crate::runtime::quote_json_numbers(&s);
2167 crate::runtime::json_parse(&Value::Str(prepared.into()))
2168 }
2169 other => other,
2172 }
2173 }
2174
2175 pub fn clone_self(&self) -> Exchange {
2186 Clone::clone(self)
2187 }
2188
2189 pub fn clone(&self, v: Value) -> Value {
2194 v
2195 }
2196
2197 pub fn prop(&self, key: &Value) -> Value {
2202 crate::get_value(&self.to_value(), key)
2203 }
2204
2205 pub fn to_value(&self) -> Value {
2209 let mut m = indexmap::IndexMap::new();
2210 let mut put = |k: &str, v: &Value| {
2211 m.insert(k.to_string(), v.clone());
2212 };
2213 put("id", &self.id);
2214 put("name", &self.name);
2215 put("countries", &self.countries);
2216 put("version", &self.version);
2217 put("alias", &self.alias);
2218 put("certified", &self.certified);
2219 put("pro", &self.pro);
2220 put("hostname", &self.hostname);
2221 put("apiKey", &self.apiKey);
2222 put("secret", &self.secret);
2223 put("password", &self.password);
2224 put("uid", &self.uid);
2225 put("walletAddress", &self.walletAddress);
2226 put("privateKey", &self.privateKey);
2227 put("twofa", &self.twofa);
2228 put("token", &self.token);
2229 put("login", &self.login);
2230 put("accountId", &self.accountId);
2231 put("requiredCredentials", &self.requiredCredentials);
2232 put("timeout", &self.timeout);
2233 put("rateLimit", &self.rateLimit);
2234 put("enableRateLimit", &self.enableRateLimit);
2235 put("fetchHistoryCacheSize", &self.fetchHistoryCacheSize);
2236 put("rateLimiterAlgorithm", &self.rateLimiterAlgorithm);
2237 put("rollingWindowSize", &self.rollingWindowSize);
2238 put("tokenBucket", &self.tokenBucket);
2239 put("verbose", &self.verbose);
2240 put("isSandboxModeEnabled", &self.isSandboxModeEnabled);
2241 put("proxy", &self.proxy);
2242 put("proxyUrl", &self.proxyUrl);
2243 put("proxy_url", &self.proxy_url);
2244 put("proxyUrlCallback", &self.proxyUrlCallback);
2245 put("proxy_url_callback", &self.proxy_url_callback);
2246 put("httpProxy", &self.httpProxy);
2247 put("http_proxy", &self.http_proxy);
2248 put("httpProxyCallback", &self.httpProxyCallback);
2249 put("http_proxy_callback", &self.http_proxy_callback);
2250 put("httpsProxy", &self.httpsProxy);
2251 put("https_proxy", &self.https_proxy);
2252 put("httpsProxyCallback", &self.httpsProxyCallback);
2253 put("https_proxy_callback", &self.https_proxy_callback);
2254 put("socksProxy", &self.socksProxy);
2255 put("socks_proxy", &self.socks_proxy);
2256 put("socksProxyCallback", &self.socksProxyCallback);
2257 put("socks_proxy_callback", &self.socks_proxy_callback);
2258 put("wsProxy", &self.wsProxy);
2259 put("ws_proxy", &self.ws_proxy);
2260 put("wssProxy", &self.wssProxy);
2261 put("wss_proxy", &self.wss_proxy);
2262 put("wsSocksProxy", &self.wsSocksProxy);
2263 put("ws_socks_proxy", &self.ws_socks_proxy);
2264 put("markets", &self.markets);
2265 put("markets_by_id", &self.markets_by_id);
2266 put("currencies", &self.currencies);
2267 put("currencies_by_id", &self.currencies_by_id);
2268 put("commonCurrencies", &self.commonCurrencies);
2269 put("baseCurrencies", &self.baseCurrencies);
2270 put("quoteCurrencies", &self.quoteCurrencies);
2271 put("symbols", &self.symbols);
2272 put("ids", &self.ids);
2273 put("codes", &self.codes);
2274 put("timeframes", &self.timeframes);
2275 put("precision", &self.precision);
2276 put("limits", &self.limits);
2277 put("fees", &self.fees);
2278 put("features", &self.features);
2279 put("has", &self.has);
2280 put("exceptions", &self.exceptions);
2281 put("urls", &self.urls);
2282 put("api", &self.api);
2283 put("options", &self.options);
2284 put("headers", &self.headers);
2285 put("accounts", &self.accounts);
2286 put("accountsById", &self.accountsById);
2287 put("orderbooks", &self.orderbooks);
2288 put("orders", &self.orders);
2289 put("trades", &self.trades);
2290 put("myTrades", &self.myTrades);
2291 put("positions", &self.positions);
2292 put("tickers", &self.tickers);
2293 put("bidsasks", &self.bidsasks);
2294 put("ohlcvs", &self.ohlcvs);
2295 put("clients", &self.clients);
2296 put("balance", &self.balance);
2297 put("liquidations", &self.liquidations);
2298 put("myLiquidations", &self.myLiquidations);
2299 put("transactions", &self.transactions);
2300 put("reloadingMarkets", &self.reloadingMarkets);
2301 put("marketsLoading", &self.marketsLoading);
2302 put("last_request_url", &self.last_request_url);
2303 put("last_request_headers", &self.last_request_headers);
2304 put("last_request_body", &self.last_request_body);
2305 put("last_http_response", &self.last_http_response);
2306 put("last_response_headers", &self.last_response_headers);
2307 put("last_json_response", &self.last_json_response);
2308 put("lastRestRequestTimestamp", &self.lastRestRequestTimestamp);
2309 put("paddingMode", &self.paddingMode);
2310 put("precisionMode", &self.precisionMode);
2311 put(
2312 "substituteCommonCurrencyCodes",
2313 &self.substituteCommonCurrencyCodes,
2314 );
2315 put("reduceFees", &self.reduceFees);
2316 put("minFundingAddressLength", &self.minFundingAddressLength);
2317 put("networkAliases", &self.networkAliases);
2318 put("MAX_VALUE", &self.MAX_VALUE);
2319 put("returnResponseHeaders", &self.returnResponseHeaders);
2320 put("httpExceptions", &self.httpExceptions);
2321 put("status", &self.status);
2322 put("userAgent", &self.userAgent);
2323 put("user_agent", &self.user_agent);
2324 put("userAgents", &self.userAgents);
2325 Value::Map(m)
2326 }
2327
2328 pub fn base16ToBinary(&self, hex: Value, optional_args: &[Value]) -> Value {
2329 self.base16_to_binary(hex, optional_args)
2330 }
2331 pub fn base58_to_binary(&self, s: Value, _optional_args: &[Value]) -> Value {
2332 match &s {
2333 Value::Str(s) => match base58_decode(s) {
2334 Some(b) => bytes_to_value(&b),
2335 None => Value::Null,
2336 },
2337 _ => Value::Null,
2338 }
2339 }
2340 pub fn binary_to_base58(&self, b: Value, _optional_args: &[Value]) -> Value {
2341 Value::Str(base58_encode(&crate::exchange::value_to_bytes(&b)).into())
2342 }
2343 pub fn binary_length(&self, b: Value, _optional_args: &[Value]) -> Value {
2344 match b {
2345 Value::Arr(a) => Value::Int(a.len() as i64),
2346 _ => Value::Int(0),
2347 }
2348 }
2349 pub fn is_binary_message(&self, v: Value, _optional_args: &[Value]) -> Value {
2353 Value::Bool(is_byte_array(&v))
2354 }
2355 pub fn number_to_be(&self, n: Value, optional_args: &[Value]) -> Value {
2357 let num: u64 = match &n {
2358 Value::Int(i) => (*i).max(0) as u64,
2359 Value::Float(f) => (*f).max(0.0) as u64,
2360 Value::Str(s) => s.parse().unwrap_or(0),
2361 _ => 0,
2362 };
2363 let padding: usize = match optional_args.get(0) {
2364 Some(Value::Int(i)) => (*i).max(0) as usize,
2365 Some(Value::Float(f)) => (*f).max(0.0) as usize,
2366 _ => 8,
2367 };
2368 let be = num.to_be_bytes(); let mut out: Vec<u8> = Vec::with_capacity(padding);
2370 if padding >= be.len() {
2371 out.extend(std::iter::repeat(0u8).take(padding - be.len()));
2372 out.extend_from_slice(&be);
2373 } else {
2374 out.extend_from_slice(&be[be.len() - padding..]);
2375 }
2376 bytes_to_value(&out)
2377 }
2378 pub fn parse_date(&self, s: Value, _optional_args: &[Value]) -> Value {
2382 let text = match &s {
2383 Value::Str(s) if !s.is_empty() => s.clone(),
2384 _ => return Value::Null,
2385 };
2386 if let Ok(t) = chrono::DateTime::parse_from_rfc3339(&text) {
2388 return Value::Int(t.timestamp_millis());
2389 }
2390 for fmt in [
2392 "%Y-%m-%d %H:%M:%S%.f",
2393 "%Y-%m-%d %H:%M:%S",
2394 "%Y-%m-%dT%H:%M:%S%.f",
2395 "%Y-%m-%dT%H:%M:%S",
2396 ] {
2397 if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(&text, fmt) {
2398 return Value::Int(ndt.and_utc().timestamp_millis());
2399 }
2400 }
2401 Value::Null
2402 }
2403 pub fn is_binary_message_var(&self, v: Value, _optional_args: &[Value]) -> Value {
2404 Value::Bool(is_byte_array(&v))
2405 }
2406 pub fn ymd(&self, ts: Value, optional_args: &[Value]) -> Value {
2409 if optional_args.is_empty() {
2410 self.yyyymmdd(ts, &[Value::Str(String::new().into())])
2411 } else {
2412 self.yyyymmdd(ts, optional_args)
2413 }
2414 }
2415 pub fn safe_float_n(&self, obj: Value, keys: Value, optional_args: &[Value]) -> Value {
2416 if let Value::Arr(ks) = keys {
2417 for k in ks.iter().cloned() {
2418 let v = self.safe_float(obj.clone(), k, &[]);
2419 if !v.is_null() {
2420 return v;
2421 }
2422 }
2423 }
2424 arg_default(optional_args)
2425 }
2426 pub fn safe_float2(&self, obj: Value, k1: Value, k2: Value, optional_args: &[Value]) -> Value {
2427 let v = self.safe_float(obj.clone(), k1, &[]);
2428 if !v.is_null() {
2429 return v;
2430 }
2431 let v = self.safe_float(obj, k2, &[]);
2432 if !v.is_null() {
2433 v
2434 } else {
2435 arg_default(optional_args)
2436 }
2437 }
2438 pub fn safeString2(&self, obj: Value, k1: Value, k2: Value, optional_args: &[Value]) -> Value {
2442 self.safe_string2(obj, k1, k2, optional_args)
2443 }
2444 pub fn binary_concat(&self, first: Value, optional_args: &[Value]) -> Value {
2447 let mut out = crate::exchange::value_to_bytes(&first);
2448 for v in optional_args {
2449 out.extend(crate::exchange::value_to_bytes(v));
2450 }
2451 bytes_to_value(&out)
2452 }
2453 pub fn stringToBase64(&self, s: Value, optional_args: &[Value]) -> Value {
2454 self.string_to_base64(s, optional_args)
2455 }
2456 pub fn binary_to_string(&self, b: Value, _optional_args: &[Value]) -> Value {
2458 let bytes = crate::exchange::value_to_bytes(&b);
2459 Value::Str(String::from_utf8_lossy(&bytes).into_owned().into())
2460 }
2461 pub fn string_to_binary(&self, s: Value, _optional_args: &[Value]) -> Value {
2462 match s {
2463 Value::Str(s) => Value::Array(s.bytes().map(|b| Value::Int(b as i64)).collect()),
2464 _ => Value::Array(vec![]),
2465 }
2466 }
2467 pub fn urlencode_base64(&self, v: Value, _optional_args: &[Value]) -> Value {
2471 let bytes = match &v {
2472 Value::Str(s) => s.as_bytes().to_vec(),
2473 _ => crate::exchange::value_to_bytes(&v),
2474 };
2475 let encoded = match self.binary_to_base64(bytes_to_value(&bytes), &[]) {
2476 Value::Str(s) => s,
2477 _ => String::new().into(),
2478 };
2479 let trimmed = encoded.trim_end_matches('=');
2480 Value::Str(trimmed.replace('+', "-").replace('/', "_").into())
2481 }
2482 pub fn urlencode_nested(&self, v: Value, _optional_args: &[Value]) -> Value {
2486 let m = match &v {
2487 Value::Dict(m) => m,
2488 _ => return Value::Str(String::new().into()),
2489 };
2490 let mut pairs: Vec<String> = Vec::new();
2491 for (k, val) in m.iter() {
2492 urlencode_nested_walk(k, val, &mut pairs);
2493 }
2494 Value::Str(pairs.join("&").into())
2495 }
2496 pub fn is_json_encoded_object(&self, optional_args: &[Value]) -> Value {
2497 match optional_args.get(0) {
2498 Some(Value::Str(s)) => Value::Bool(s.starts_with('{') || s.starts_with('[')),
2499 _ => Value::Bool(false),
2500 }
2501 }
2502 pub fn strip(&self, s: Value, _optional_args: &[Value]) -> Value {
2503 match s {
2504 Value::Str(s) => Value::Str(s.trim().to_string().into()),
2505 other => other,
2506 }
2507 }
2508 pub fn sort(&self, v: Value, _optional_args: &[Value]) -> Value {
2509 if let Value::Arr(a) = v {
2510 let mut a = Arc::try_unwrap(a).unwrap_or_else(|x| (*x).clone());
2511 a.sort_by(|x, y| {
2512 let xs = crate::runtime::stringify_param(x);
2513 let ys = crate::runtime::stringify_param(y);
2514 xs.cmp(&ys)
2515 });
2516 Value::Array(a)
2517 } else {
2518 v
2519 }
2520 }
2521 pub fn round_timeframe(&self, tf: Value, ts: Value, direction: Value) -> Value {
2525 let timeframe = match &tf {
2526 Value::Str(timeframe) => timeframe.as_ref(),
2527 _ => "",
2528 };
2529 let unit = timeframe.chars().last().unwrap_or(' ');
2530 let amount = timeframe[..timeframe.len().saturating_sub(1)]
2531 .parse::<i64>()
2532 .unwrap_or(0);
2533 let secs = match self.parse_timeframe(tf) {
2534 Value::Int(s) => s,
2535 Value::Float(s) => s as i64,
2536 _ => return ts,
2537 };
2538 let ms = secs * 1000;
2539 let t = match &ts {
2540 Value::Int(i) => *i,
2541 Value::Float(f) => *f as i64,
2542 _ => return ts,
2543 };
2544 if ms == 0 {
2545 return ts;
2546 }
2547 if ((unit == 'w') || (unit == 'M') || (unit == 'y')) && (amount >= 1) {
2548 let date = match Utc.timestamp_millis_opt(t).single() {
2549 Some(date) => date,
2550 None => return ts,
2551 };
2552 let mut rounded = date.date_naive().and_hms_opt(0, 0, 0).unwrap().and_utc();
2553 if unit == 'w' {
2554 let days_since_monday = date.weekday().num_days_from_monday() as i64;
2555 let monday = rounded - chrono::Duration::days(days_since_monday);
2556 let epoch_monday = Utc.with_ymd_and_hms(1970, 1, 5, 0, 0, 0).unwrap();
2557 let weeks_since_epoch_monday = (monday - epoch_monday).num_days() / 7;
2558 rounded = epoch_monday
2559 + chrono::Duration::days(
2560 weeks_since_epoch_monday.div_euclid(amount) * amount * 7,
2561 );
2562 if matches!(&direction, Value::Int(d) if *d == crate::runtime::ROUND_UP) {
2563 rounded = rounded + chrono::Duration::days(amount * 7);
2564 }
2565 } else if unit == 'M' {
2566 let months_since_year_zero = date.year() as i64 * 12 + date.month0() as i64;
2567 let rounded_months = months_since_year_zero.div_euclid(amount) * amount;
2568 let year = rounded_months.div_euclid(12) as i32;
2569 let month = (rounded_months.rem_euclid(12) + 1) as u32;
2570 rounded = Utc.with_ymd_and_hms(year, month, 1, 0, 0, 0).unwrap();
2571 if matches!(&direction, Value::Int(d) if *d == crate::runtime::ROUND_UP) {
2572 rounded = rounded + chrono::Months::new(amount as u32);
2573 }
2574 } else {
2575 let year = (date.year() as i64).div_euclid(amount) * amount;
2576 rounded = Utc.with_ymd_and_hms(year as i32, 1, 1, 0, 0, 0).unwrap();
2577 if matches!(&direction, Value::Int(d) if *d == crate::runtime::ROUND_UP) {
2578 rounded = rounded + chrono::Months::new((amount * 12) as u32);
2579 }
2580 }
2581 return Value::Int(rounded.timestamp_millis());
2582 }
2583 let offset = t % ms;
2584 let is_up = matches!(&direction, Value::Int(d) if *d == crate::runtime::ROUND_UP);
2585 Value::Int(t - offset + if is_up { ms } else { 0 })
2586 }
2587 pub async fn sleep(&self, ms: Value) -> Value {
2588 if let Some(n) = match ms {
2589 Value::Int(n) => Some(n),
2590 Value::Float(f) => Some(f as i64),
2591 _ => None,
2592 } {
2593 if n > 0 {
2594 tokio::time::sleep(std::time::Duration::from_millis(n as u64)).await;
2595 }
2596 }
2597 Value::Null
2598 }
2599 pub fn eth_get_address_from_private_key(&self, pk: Value, _optional_args: &[Value]) -> Value {
2602 use k256::ecdsa::SigningKey;
2603 let pk_s = match &pk {
2604 Value::Str(s) => s.trim_start_matches("0x").to_string(),
2605 _ => return Value::Str(String::new().into()),
2606 };
2607 let pk_bytes = match hex::decode(&pk_s) {
2608 Ok(b) => b,
2609 Err(_) => return Value::Str(String::new().into()),
2610 };
2611 let sk = match SigningKey::from_slice(&pk_bytes) {
2612 Ok(k) => k,
2613 Err(_) => return Value::Str(String::new().into()),
2614 };
2615 let point = sk.verifying_key().to_encoded_point(false); let pubkey = &point.as_bytes()[1..]; let hash = crate::exchange::hash_raw(pubkey, "keccak");
2618 Value::Str(format!("0x{}", hex::encode(&hash[12..32])).into())
2619 }
2620 pub fn exists_file(&self, p: Value) -> Value {
2621 match &p {
2622 Value::Str(path) => Value::Bool(std::path::Path::new(path.as_ref()).is_file()),
2623 _ => Value::Bool(false),
2624 }
2625 }
2626 pub fn read_file(&self, p: Value) -> Value {
2627 match &p {
2628 Value::Str(path) => match std::fs::read_to_string(path.as_ref()) {
2629 Ok(s) => Value::Str(s.into()),
2630 Err(_) => Value::Null,
2631 },
2632 _ => Value::Null,
2633 }
2634 }
2635 pub fn write_file(&self, p: Value, content: Value) -> Value {
2636 let path = match &p {
2637 Value::Str(s) => s.to_string(),
2638 _ => return Value::Bool(false),
2639 };
2640 let body = match &content {
2641 Value::Str(s) => s.to_string(),
2642 other => stringify_param(other).into(),
2643 };
2644 Value::Bool(std::fs::write(&*path, body).is_ok())
2645 }
2646 pub fn get_temp_dir(&self) -> Value {
2647 Value::Str(format!(
2648 "{}/",
2649 std::env::temp_dir().to_string_lossy().trim_end_matches('/')
2650 ).into())
2651 }
2652 pub fn get_property(&self, obj: Value, key: Value) -> Value {
2653 crate::get_value(&obj, &Value::Str(stringify_param(&key).into()))
2654 }
2655
2656 pub fn yymmdd(&self, ts: Value, optional_args: &[Value]) -> Value {
2657 let infix = match optional_args.get(0) {
2658 Some(Value::Str(s)) => s.clone(),
2659 _ => String::new().into(),
2660 };
2661 let n = match ts {
2662 Value::Int(n) => n,
2663 _ => 0,
2664 };
2665 let dt = chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n);
2666 match dt {
2667 Some(t) => Value::Str(t.format(&format!("%y{i}%m{i}%d", i = infix)).to_string().into()),
2668 None => Value::Null,
2669 }
2670 }
2671 pub fn yyyymmdd(&self, ts: Value, optional_args: &[Value]) -> Value {
2672 let infix = match optional_args.get(0) {
2674 Some(Value::Str(s)) => s.clone(),
2675 _ => "-".to_string().into(),
2676 };
2677 let n = match ts {
2678 Value::Int(n) => n,
2679 _ => 0,
2680 };
2681 let dt = chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n);
2682 match dt {
2683 Some(t) => Value::Str(t.format(&format!("%Y{i}%m{i}%d", i = infix)).to_string().into()),
2684 None => Value::Null,
2685 }
2686 }
2687 pub fn ymdhms(&self, ts: Value, optional_args: &[Value]) -> Value {
2689 let infix = match optional_args.get(0) {
2690 Some(Value::Str(s)) => s.clone(),
2691 _ => " ".to_string().into(),
2692 };
2693 let n = match ts {
2694 Value::Int(n) => n,
2695 Value::Float(f) => f as i64,
2696 _ => 0,
2697 };
2698 let dt = chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n);
2699 match dt {
2700 Some(t) => Value::Str(t.format(&format!("%Y-%m-%d{infix}%H:%M:%S")).to_string().into()),
2701 None => Value::Null,
2702 }
2703 }
2704
2705 pub fn rawencode(&self, params: Value, _optional_args: &[Value]) -> Value {
2709 let m = match ¶ms {
2710 Value::Dict(m) => m,
2711 _ => return Value::Str(String::new().into()),
2712 };
2713 let pairs: Vec<String> = m
2714 .iter()
2715 .map(|(k, v)| format!("{}={}", k, stringify_param(v)))
2716 .collect();
2717 Value::Str(pairs.join("&").into())
2718 }
2719
2720 pub fn int_to_base16(&self, n: Value, _optional_args: &[Value]) -> Value {
2722 let v = match n {
2723 Value::Int(n) => n as u64,
2724 Value::Float(f) => f as u64,
2725 Value::Str(s) => s.parse::<u64>().unwrap_or(0),
2726 _ => 0,
2727 };
2728 Value::Str(format!("{:x}", v).into())
2729 }
2730
2731 pub fn packb(&self, action: Value, _optional_args: &[Value]) -> Value {
2736 fn to_rmpv(v: &Value) -> rmpv::Value {
2737 match v {
2738 Value::Null => rmpv::Value::Nil,
2739 Value::Bool(b) => rmpv::Value::Boolean(*b),
2740 Value::Int(i) => rmpv::Value::Integer((*i).into()),
2741 Value::Float(f) => rmpv::Value::F64(*f),
2742 Value::Str(s) => rmpv::Value::String(s.clone().into()),
2743 Value::Arr(a) => rmpv::Value::Array(a.iter().map(to_rmpv).collect()),
2744 Value::Dict(m) => rmpv::Value::Map(
2745 m.iter()
2746 .map(|(k, v)| (rmpv::Value::String(k.clone().into()), to_rmpv(v)))
2747 .collect(),
2748 ),
2749 }
2750 }
2751 let mut buf: Vec<u8> = Vec::new();
2752 match rmpv::encode::write_value(&mut buf, &to_rmpv(&action)) {
2753 Ok(_) => Value::Array(buf.iter().map(|b| Value::Int(*b as i64)).collect()),
2754 Err(_) => Value::Null,
2755 }
2756 }
2757
2758 pub fn eth_encode_structured_data(&self, domain: Value, types: Value, message: Value) -> Value {
2762 let bytes = crate::exchange::eip712_encode(&domain, &types, &message);
2763 Value::Array(bytes.iter().map(|b| Value::Int(*b as i64)).collect())
2764 }
2765
2766 pub fn uuid22(&self, _optional_args: &[Value]) -> Value {
2768 Value::Str(random_hex(22).into())
2769 }
2770 pub fn uuid16(&self, _optional_args: &[Value]) -> Value {
2772 Value::Str(random_hex(16).into())
2773 }
2774 pub fn uuid(&self, _optional_args: &[Value]) -> Value {
2776 let h = random_hex(32);
2777 let variant = ['8', '9', 'a', 'b'][(random_u64() % 4) as usize];
2778 let s = format!(
2779 "{}-{}-4{}-{}{}-{}",
2780 &h[0..8],
2781 &h[8..12],
2782 &h[13..16],
2783 variant,
2784 &h[17..20],
2785 &h[20..32],
2786 );
2787 Value::Str(s.into())
2788 }
2789
2790 pub fn urlencode(&self, params: Value, _optional_args: &[Value]) -> Value {
2792 Value::Str(self.urlencode_kv(¶ms).into())
2793 }
2794
2795 pub fn json(&self, v: Value) -> Value {
2797 Value::Str(self.json_str(&v).into())
2798 }
2799
2800 pub fn encode(&self, s: Value) -> Value {
2802 match s {
2803 Value::Str(s) => Value::Array(s.bytes().map(|b| Value::Int(b as i64)).collect()),
2804 _ => Value::Array(vec![]),
2805 }
2806 }
2807
2808 pub fn decode(&self, b: Value) -> Value {
2810 match b {
2811 Value::Str(s) => Value::Str(s),
2812 Value::Arr(a) => {
2813 let bytes: Vec<u8> = a
2814 .iter()
2815 .filter_map(|v| match v {
2816 Value::Int(n) => Some(*n as u8),
2817 _ => None,
2818 })
2819 .collect();
2820 Value::Str(String::from_utf8_lossy(&bytes).into_owned().into())
2821 }
2822 _ => Value::Str(String::new().into()),
2823 }
2824 }
2825
2826 pub fn log(&self, msg: Value) {
2828 if matches!(self.verbose, Value::Bool(true)) {
2829 println!("[ccxt] {}", crate::runtime::stringify_param(&msg));
2830 }
2831 }
2832
2833 pub fn number_to_string(&self, n: Value) -> Value {
2840 if matches!(n, Value::Null) {
2843 return Value::Null;
2844 }
2845 Value::Str(stringify_param(&n).into())
2846 }
2847
2848 pub fn parse_number(&self, v: Value, optional_args: &[Value]) -> Value {
2849 match v {
2850 Value::Float(_) | Value::Int(_) => v,
2851 Value::Str(ref s) => match s.parse::<f64>() {
2852 Ok(n) => Value::Float(n),
2853 Err(_) => arg_default(optional_args),
2854 },
2855 _ => arg_default(optional_args),
2856 }
2857 }
2858
2859 pub fn parse_timeframe(&self, tf: Value) -> Value {
2860 let s = stringify_param(&tf);
2861 let last = s.chars().last().unwrap_or('m');
2862 let num: i64 = s[..s.len().saturating_sub(1)].parse().unwrap_or(0);
2863 Value::Int(match last {
2864 's' => num,
2865 'm' => num * 60,
2866 'h' => num * 3600,
2867 'd' => num * 86400,
2868 'w' => num * 604800,
2869 'M' => num * 2592000,
2870 'y' => num * 31536000,
2871 _ => 0,
2872 })
2873 }
2874
2875 pub fn precision_from_string(&self, s: Value) -> Value {
2879 let s = stringify_param(&s);
2880 if let Some(idx) = s.find(['e', 'E']) {
2881 let exp: i64 = s[idx + 1..].parse().unwrap_or(0);
2882 return Value::Int(-exp);
2883 }
2884 let trimmed = s.trim_end_matches('0');
2885 match trimmed.split_once('.') {
2886 Some((_, frac)) => Value::Int(frac.len() as i64),
2887 None => Value::Int(0),
2888 }
2889 }
2890
2891 pub fn decimal_to_precision(
2894 &self,
2895 n: Value,
2896 rounding: Value,
2897 precision: Value,
2898 optional_args: &[Value],
2899 ) -> Value {
2900 let n_s = stringify_param(&n);
2901 let prec_f: f64 = match &precision {
2902 Value::Int(i) => *i as f64,
2903 Value::Float(f) => *f,
2904 Value::Str(s) => s.parse().unwrap_or(f64::NAN),
2905 _ => return Value::Str(n_s.into()),
2906 };
2907 let counting: i64 = match optional_args.get(0) {
2908 Some(Value::Int(c)) => *c,
2909 _ => crate::runtime::DECIMAL_PLACES,
2910 };
2911 let padding: i64 = match optional_args.get(1) {
2912 Some(Value::Int(p)) => *p,
2913 _ => crate::runtime::NO_PADDING,
2914 };
2915 let rounding_mode: i64 = match &rounding {
2916 Value::Int(r) => *r,
2917 _ => crate::runtime::TRUNCATE,
2918 };
2919 Value::Str(decimal_to_precision_impl(
2920 &n_s,
2921 rounding_mode,
2922 prec_f,
2923 counting,
2924 padding,
2925 ).into())
2926 }
2927
2928 pub fn capitalize(&self, s: Value) -> Value {
2929 let s = stringify_param(&s);
2930 let mut c = s.chars();
2931 Value::Str(match c.next() {
2932 None => String::new().into(),
2933 Some(f) => f.to_uppercase().chain(c).collect(),
2934 })
2935 }
2936
2937 pub fn encode_uri_component(&self, s: Value) -> Value {
2938 let s = stringify_param(&s);
2939 Value::Str(
2940 s.bytes()
2941 .map(|b| match b {
2942 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
2943 (b as char).to_string()
2944 }
2945 _ => format!("%{b:02X}"),
2946 })
2947 .collect(),
2948 )
2949 }
2950
2951 pub fn string_to_chars_array(&self, s: Value) -> Value {
2952 let s = stringify_param(&s);
2953 Value::Array(s.chars().map(|c| Value::Str(c.to_string().into())).collect())
2954 }
2955
2956 pub fn string_to_base64(&self, s: Value, _optional_args: &[Value]) -> Value {
2957 self.binary_to_base64(s, &[])
2958 }
2959
2960 pub fn extract_params(&self, path: Value) -> Value {
2963 let p = stringify_param(&path);
2964 let mut out: Vec<Value> = vec![];
2965 let mut chars = p.chars().peekable();
2966 while let Some(c) = chars.next() {
2967 if c == '{' {
2968 let mut name = String::new();
2969 while let Some(&nc) = chars.peek() {
2970 if nc == '}' {
2971 chars.next();
2972 break;
2973 }
2974 name.push(nc);
2975 chars.next();
2976 }
2977 if !name.is_empty() {
2978 out.push(Value::Str(name.into()));
2979 }
2980 }
2981 }
2982 Value::Array(out)
2983 }
2984
2985 pub fn proxy_fn(&self, _url: Value, _method: Value, _headers: Value, _body: Value) -> Value {
3012 self.proxy.clone()
3013 }
3014 pub fn proxy_url_callback_fn(
3015 &self,
3016 _url: Value,
3017 _method: Value,
3018 _headers: Value,
3019 _body: Value,
3020 ) -> Value {
3021 self.proxy_url_callback.clone()
3022 }
3023 pub fn http_proxy_callback_fn(
3024 &self,
3025 _url: Value,
3026 _method: Value,
3027 _headers: Value,
3028 _body: Value,
3029 ) -> Value {
3030 self.http_proxy_callback.clone()
3031 }
3032 pub fn https_proxy_callback_fn(
3033 &self,
3034 _url: Value,
3035 _method: Value,
3036 _headers: Value,
3037 _body: Value,
3038 ) -> Value {
3039 self.https_proxy_callback.clone()
3040 }
3041 pub fn socks_proxy_callback_fn(
3042 &self,
3043 _url: Value,
3044 _method: Value,
3045 _headers: Value,
3046 _body: Value,
3047 ) -> Value {
3048 self.socks_proxy_callback.clone()
3049 }
3050 pub fn ws_proxy_callback_fn(
3051 &self,
3052 _url: Value,
3053 _method: Value,
3054 _headers: Value,
3055 _body: Value,
3056 ) -> Value {
3057 Value::Null
3058 }
3059 pub fn wss_proxy_callback_fn(
3060 &self,
3061 _url: Value,
3062 _method: Value,
3063 _headers: Value,
3064 _body: Value,
3065 ) -> Value {
3066 Value::Null
3067 }
3068 pub fn ws_socks_proxy_callback_fn(
3069 &self,
3070 _url: Value,
3071 _method: Value,
3072 _headers: Value,
3073 _body: Value,
3074 ) -> Value {
3075 Value::Null
3076 }
3077
3078 pub fn init_throttler(&mut self) { }
3080 pub async fn throttle(&self, cost: &[Value]) -> Value {
3089 if !matches!(self.enableRateLimit, Value::Bool(true)) {
3090 return Value::Null;
3091 }
3092 let tb = |key: &str| -> Option<f64> {
3093 crate::get_value(&self.tokenBucket, &Value::Str(key.to_string().into())).as_f64()
3094 };
3095 let rate_limit = self.rateLimit.as_f64().unwrap_or(0.0);
3096 let refill_rate = tb("refillRate").unwrap_or_else(|| {
3097 if rate_limit > 0.0 {
3098 1.0 / rate_limit
3099 } else {
3100 f64::MAX
3101 }
3102 });
3103 if !(refill_rate.is_finite() && refill_rate > 0.0) {
3104 return Value::Null; }
3106 let capacity = tb("capacity").unwrap_or(1.0);
3107 let delay_ms = tb("delay").unwrap_or(0.001) * 1000.0;
3108 let this_cost = cost
3109 .first()
3110 .and_then(|v| v.as_f64())
3111 .unwrap_or_else(|| tb("cost").unwrap_or(1.0));
3112
3113 let now_ms = || {
3114 std::time::SystemTime::now()
3115 .duration_since(std::time::UNIX_EPOCH)
3116 .map(|d| d.as_millis() as i64)
3117 .unwrap_or(0)
3118 };
3119
3120 let mut guard = self.internals.throttle.lock().await;
3121 let (tokens, last_ms) = &mut *guard;
3122 if *last_ms == 0 {
3123 *last_ms = now_ms();
3124 }
3125 let n = now_ms();
3127 *tokens = (*tokens + refill_rate * (n - *last_ms).max(0) as f64).min(capacity);
3128 *last_ms = n;
3129 if *tokens < 0.0 {
3132 let wait = ((-*tokens) / refill_rate).max(delay_ms);
3133 tokio::time::sleep(std::time::Duration::from_millis(wait.ceil() as u64)).await;
3134 let n2 = now_ms();
3135 *tokens = (*tokens + refill_rate * (n2 - *last_ms).max(0) as f64).min(capacity);
3136 *last_ms = n2;
3137 }
3138 *tokens -= this_cost;
3139 Value::Null
3140 }
3141
3142 pub fn resolve<T>(&self, v: T) -> T {
3143 v
3144 }
3145 pub fn reject(&self, err: ExchangeError) -> ExchangeError {
3146 err
3147 }
3148}
3149
3150pub(crate) fn synthesize_currencies_from_markets(markets: &Value, precision_mode: &Value) -> Value {
3156 let market_list: Vec<&Value> = match markets {
3157 Value::Arr(a) => a.iter().collect(),
3158 Value::Dict(m) => m.values().collect(),
3159 _ => return Value::Map(HashMap::new()),
3160 };
3161 let is_tick_size = matches!(precision_mode, Value::Int(n) if *n == crate::runtime::TICK_SIZE);
3162 let default_precision = if is_tick_size {
3163 Value::Float(1e-8)
3164 } else {
3165 Value::Int(8)
3166 };
3167
3168 let more_precise = |new: &Value, cur: &Value| -> bool {
3171 let to_f = |v: &Value| -> f64 {
3172 match v {
3173 Value::Int(n) => *n as f64,
3174 Value::Float(f) => *f,
3175 Value::Str(s) => s.parse().unwrap_or(f64::NAN),
3176 _ => f64::NAN,
3177 }
3178 };
3179 let n = to_f(new);
3180 let c = to_f(cur);
3181 if n.is_nan() {
3182 return false;
3183 }
3184 if c.is_nan() {
3185 return true;
3186 }
3187 if is_tick_size {
3188 n < c
3189 } else {
3190 n > c
3191 }
3192 };
3193
3194 let mut by_code: HashMap<String, HashMap<String, Value>> = HashMap::new();
3197 for market in market_list {
3198 let market_precision = crate::get_value(market, &Value::Str("precision".into()));
3199 for (id_key, code_key, prec_keys) in [
3201 ("baseId", "base", ["base", "amount"]),
3202 ("quoteId", "quote", ["quote", "price"]),
3203 ] {
3204 let code = crate::get_value(market, &Value::Str(code_key.to_string().into()));
3205 let code_s = match &code {
3206 Value::Str(s) if !s.is_empty() => s.clone(),
3207 _ => continue,
3208 };
3209 let id = crate::get_value(market, &Value::Str(id_key.to_string().into()));
3210 let id_v = match &id {
3211 Value::Null => Value::Str(code_s.clone()),
3212 other => other.clone(),
3213 };
3214 let mut precision =
3215 crate::get_value(&market_precision, &Value::Str(prec_keys[0].to_string().into()));
3216 if matches!(precision, Value::Null) {
3217 precision =
3218 crate::get_value(&market_precision, &Value::Str(prec_keys[1].to_string().into()));
3219 }
3220 if matches!(precision, Value::Null) {
3221 precision = default_precision.clone();
3222 }
3223 let entry = by_code.entry(code_s.to_string()).or_insert_with(|| {
3224 let mut m = HashMap::new();
3225 m.insert("id".to_string(), id_v.clone());
3226 m.insert("numericId".to_string(), Value::Null);
3227 m.insert("code".to_string(), Value::Str(code_s.clone()));
3228 m.insert("precision".to_string(), precision.clone());
3229 m
3230 });
3231 let existing_precision = entry.get("precision").cloned().unwrap_or(Value::Null);
3232 if more_precise(&precision, &existing_precision) {
3233 entry.insert("precision".to_string(), precision.clone());
3234 }
3235 }
3236 }
3237 let result: HashMap<String, Value> = by_code
3238 .into_iter()
3239 .map(|(k, v)| (k, Value::Map(v)))
3240 .collect();
3241 Value::Map(result)
3242}
3243
3244#[cfg(test)]
3245mod spawn_queue_tests {
3246 use super::*;
3247
3248 #[test]
3253 fn delayed_spawns_wait_for_their_deadline() {
3254 enqueue_spawn_after("keep_alive_listen_key", vec![], 10_000);
3256 assert!(drain_spawn_queue().is_empty(), "not due yet");
3257 let due_in = next_spawn_due().expect("a deadline is pending");
3258 assert!(due_in > std::time::Duration::from_secs(9));
3259
3260 enqueue_spawn("handle_order_book_snapshot", vec![]);
3263 let batch = drain_spawn_queue();
3264 assert_eq!(batch.len(), 1);
3265 assert_eq!(batch[0].0, "handle_order_book_snapshot");
3266 assert!(
3267 next_spawn_due().is_some(),
3268 "the delayed item is still queued"
3269 );
3270 }
3271
3272 #[test]
3273 fn spawns_run_once_their_deadline_passes() {
3274 enqueue_spawn_after("keep_alive_listen_key", vec![], 1);
3275 std::thread::sleep(std::time::Duration::from_millis(5));
3276 assert_eq!(next_spawn_due(), Some(std::time::Duration::ZERO));
3277 let batch = drain_spawn_queue();
3278 assert_eq!(batch.len(), 1);
3279 assert_eq!(batch[0].0, "keep_alive_listen_key");
3280 assert!(next_spawn_due().is_none(), "queue drained");
3281 }
3282}