1use crate::Value;
24use indexmap::IndexMap;
25
26#[derive(Clone, Debug, Default, PartialEq)]
31pub struct Params {
32 entries: IndexMap<String, Value>,
33}
34
35impl Params {
36 pub fn new() -> Self {
38 Self::default()
39 }
40
41 pub fn none() -> Self {
44 Self::default()
45 }
46
47 pub fn is_empty(&self) -> bool {
49 self.entries.is_empty()
50 }
51
52 pub fn len(&self) -> usize {
54 self.entries.len()
55 }
56
57 pub fn with_str(mut self, key: &str, value: &str) -> Self {
59 self.entries.insert(key.to_string(), Value::Str(value.to_string().into()));
60 self
61 }
62
63 pub fn with_int(mut self, key: &str, value: i64) -> Self {
65 self.entries.insert(key.to_string(), Value::Int(value));
66 self
67 }
68
69 pub fn with_float(mut self, key: &str, value: f64) -> Self {
71 self.entries.insert(key.to_string(), Value::Float(value));
72 self
73 }
74
75 pub fn with_bool(mut self, key: &str, value: bool) -> Self {
77 self.entries.insert(key.to_string(), Value::Bool(value));
78 self
79 }
80
81 pub fn with_strs(mut self, key: &str, values: &[&str]) -> Self {
83 let list: Vec<Value> = values.iter().map(|s| Value::Str((*s).to_string().into())).collect();
84 self.entries.insert(key.to_string(), Value::Arr(std::sync::Arc::new(list)));
85 self
86 }
87
88 pub fn with_json(mut self, key: &str, json: &str) -> Self {
91 let parsed = crate::runtime::json_parse(&Value::Str(json.to_string().into()));
92 let v = if matches!(parsed, Value::Null) { Value::Str(json.to_string().into()) } else { parsed };
93 self.entries.insert(key.to_string(), v);
94 self
95 }
96
97 pub fn with_params(mut self, key: &str, value: Params) -> Self {
101 let mut base = match self.entries.get(key) {
102 Some(Value::Dict(d)) => (**d).clone(),
103 _ => IndexMap::new(),
104 };
105 deep_merge(&mut base, value.into_entries());
106 self.entries.insert(key.to_string(), Value::Dict(std::sync::Arc::new(base)));
108 self
109 }
110
111 pub(crate) fn into_entries(self) -> IndexMap<String, Value> {
113 self.entries
114 }
115
116 pub fn into_value_object(self) -> Value {
120 Value::Dict(std::sync::Arc::new(self.entries))
121 }
122
123 pub fn into_value(self) -> Value {
127 if self.entries.is_empty() {
128 return Value::Null;
129 }
130 Value::Map(self.entries)
131 }
132}
133
134impl From<Params> for Value {
135 fn from(p: Params) -> Value {
136 p.into_value()
137 }
138}
139
140impl From<Value> for Params {
143 fn from(v: Value) -> Params {
144 match v {
145 Value::Dict(entries) => Params {
146 entries: std::sync::Arc::try_unwrap(entries).unwrap_or_else(|a| (*a).clone()),
147 },
148 Value::Null => Params::default(),
149 _ => Params::default(),
152 }
153 }
154}
155
156impl From<()> for Params {
158 fn from(_: ()) -> Params {
159 Params::default()
160 }
161}
162
163impl<const N: usize> From<[(&str, &str); N]> for Params {
164 fn from(pairs: [(&str, &str); N]) -> Params {
165 let mut p = Params::new();
166 for (k, v) in pairs {
167 p = p.with_str(k, v);
168 }
169 p
170 }
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176
177 #[test]
178 fn empty_lowers_to_null() {
179 assert!(matches!(Params::none().into_value(), Value::Null));
180 assert!(Params::new().is_empty());
181 }
182
183 #[test]
184 fn preserves_insertion_order_and_types() {
185 let v = Params::new()
186 .with_str("timeInForce", "GTC")
187 .with_bool("postOnly", true)
188 .with_float("stopPrice", 49_000.0)
189 .with_int("recvWindow", 5_000)
190 .into_value();
191 let map = match &v { Value::Dict(m) => m, _ => panic!("expected a map") };
192 let keys: Vec<&str> = map.keys().map(|k| k.as_str()).collect();
193 assert_eq!(keys, ["timeInForce", "postOnly", "stopPrice", "recvWindow"]);
194 assert_eq!(map["postOnly"], Value::Bool(true));
195 assert_eq!(map["recvWindow"], Value::Int(5_000));
196 }
197
198 #[test]
199 fn round_trips_through_value() {
200 let p = Params::new().with_str("a", "1").with_int("b", 2);
201 let back: Params = Params::from(p.clone().into_value());
202 assert_eq!(p, back);
203 }
204
205 #[test]
206 fn value_null_and_unit_are_empty() {
207 assert!(Params::from(Value::Null).is_empty());
208 assert!(Params::from(()).is_empty());
209 }
210
211 #[test]
212 fn array_literal_shorthand() {
213 let p: Params = [("timeInForce", "IOC"), ("newClientOrderId", "x1")].into();
214 assert_eq!(p.len(), 2);
215 }
216}
217
218#[derive(Clone, Debug, Default, PartialEq)]
247pub struct Config {
248 top: IndexMap<String, Value>,
249 options: IndexMap<String, Value>,
250}
251
252impl Config {
253 pub fn new() -> Self {
254 Self::default()
255 }
256
257 pub fn none() -> Self {
259 Self::default()
260 }
261
262 pub fn api_key(self, v: &str) -> Self { self.set_str("apiKey", v) }
263 pub fn secret(self, v: &str) -> Self { self.set_str("secret", v) }
264 pub fn password(self, v: &str) -> Self { self.set_str("password", v) }
265 pub fn uid(self, v: &str) -> Self { self.set_str("uid", v) }
266 pub fn wallet_address(self, v: &str) -> Self { self.set_str("walletAddress", v) }
267 pub fn private_key(self, v: &str) -> Self { self.set_str("privateKey", v) }
268 pub fn token(self, v: &str) -> Self { self.set_str("token", v) }
269
270 pub fn sandbox(self, on: bool) -> Self { self.option_bool("sandbox", on) }
272 pub fn enable_rate_limit(self, on: bool) -> Self { self.set_bool("enableRateLimit", on) }
274 pub fn rate_limit_ms(self, ms: i64) -> Self { self.set_int("rateLimit", ms) }
276 pub fn timeout_ms(self, ms: i64) -> Self { self.set_int("timeout", ms) }
278 pub fn verbose(self, on: bool) -> Self { self.set_bool("verbose", on) }
280
281 pub fn set_str(mut self, key: &str, v: &str) -> Self {
283 self.top.insert(key.to_string(), Value::Str(v.to_string().into()));
284 self
285 }
286 pub fn set_int(mut self, key: &str, v: i64) -> Self {
287 self.top.insert(key.to_string(), Value::Int(v));
288 self
289 }
290 pub fn set_float(mut self, key: &str, v: f64) -> Self {
291 self.top.insert(key.to_string(), Value::Float(v));
292 self
293 }
294 pub fn set_bool(mut self, key: &str, v: bool) -> Self {
295 self.top.insert(key.to_string(), Value::Bool(v));
296 self
297 }
298
299 pub fn options(mut self, options: Params) -> Self {
304 deep_merge(&mut self.options, options.into_entries());
305 self
306 }
307
308 pub fn option(mut self, key: &str, value: Params) -> Self {
315 let mut base = match self.options.get(key) {
316 Some(Value::Dict(d)) => (**d).clone(),
317 _ => IndexMap::new(),
318 };
319 deep_merge(&mut base, value.into_entries());
320 self.options.insert(key.to_string(), Value::Dict(std::sync::Arc::new(base)));
321 self
322 }
323
324 pub fn option_str(self, key: &str, v: &str) -> Self {
326 self.option_value(key, Value::Str(v.to_string().into()))
327 }
328 pub fn option_int(self, key: &str, v: i64) -> Self {
329 self.option_value(key, Value::Int(v))
330 }
331 pub fn option_float(self, key: &str, v: f64) -> Self {
332 self.option_value(key, Value::Float(v))
333 }
334 pub fn option_bool(self, key: &str, v: bool) -> Self {
335 self.option_value(key, Value::Bool(v))
336 }
337 pub fn option_strs(self, key: &str, values: &[&str]) -> Self {
338 let list: Vec<Value> = values.iter().map(|s| Value::Str((*s).to_string().into())).collect();
339 self.option_value(key, Value::Arr(std::sync::Arc::new(list)))
340 }
341
342 fn option_value(mut self, key: &str, v: Value) -> Self {
343 self.options.insert(key.to_string(), v);
344 self
345 }
346
347 pub fn into_value(self) -> Value {
349 let mut top = self.top;
350 if !self.options.is_empty() {
351 let merged = match top.shift_remove("options") {
353 Some(Value::Dict(existing)) => {
354 let mut m = (*existing).clone();
355 for (k, v) in self.options { m.insert(k, v); }
356 m
357 }
358 _ => self.options,
359 };
360 top.insert("options".to_string(), Value::Dict(std::sync::Arc::new(merged)));
361 }
362 if top.is_empty() { Value::Null } else { Value::Dict(std::sync::Arc::new(top)) }
363 }
364
365 pub fn into_option(self) -> Option<Value> {
367 match self.into_value() {
368 Value::Null => None,
369 v => Some(v),
370 }
371 }
372}
373
374fn deep_merge(into: &mut IndexMap<String, Value>, from: IndexMap<String, Value>) {
377 for (k, v) in from {
378 let merged = match (into.get(&k), &v) {
379 (Some(Value::Dict(a)), Value::Dict(b)) => {
380 let mut m = (**a).clone();
381 deep_merge(&mut m, (**b).clone());
382 Value::Dict(std::sync::Arc::new(m))
383 }
384 _ => v,
385 };
386 into.insert(k, merged);
387 }
388}
389
390impl From<Config> for Value {
391 fn from(c: Config) -> Value { c.into_value() }
392}
393
394impl From<Config> for Option<Value> {
395 fn from(c: Config) -> Option<Value> { c.into_option() }
396}
397
398#[cfg(test)]
399mod config_tests {
400 use super::*;
401
402 fn dict(v: &Value) -> IndexMap<String, Value> {
403 match v { Value::Dict(d) => (**d).clone(), other => panic!("expected a dict, got {other:?}") }
404 }
405
406 #[test]
407 fn empty_config_is_none() {
408 assert!(Config::new().into_option().is_none());
409 }
410
411 #[test]
414 fn options_nest_like_the_other_bindings() {
415 let v = Config::new()
416 .api_key("k")
417 .option("fetchMarkets", Params::new().with_strs("types", &["spot", "linear"]))
418 .option_str("defaultType", "spot")
419 .sandbox(true)
420 .into_value();
421 let top = dict(&v);
422 assert_eq!(top["apiKey"], Value::Str("k".into()));
423 let options = dict(&top["options"]);
424 assert_eq!(options["defaultType"], Value::Str("spot".into()));
425 assert_eq!(options["sandbox"], Value::Bool(true));
426 let fetch_markets = dict(&options["fetchMarkets"]);
428 let types = match &fetch_markets["types"] { Value::Arr(a) => a.clone(), _ => panic!("types") };
429 assert_eq!(&types[..], &[Value::Str("spot".into()), Value::Str("linear".into())]);
430 }
431
432 #[test]
433 fn options_block_can_be_handed_over_wholesale() {
434 let v = Config::new()
435 .options(Params::new()
436 .with_params("fetchMarkets", Params::new().with_strs("types", &["swap"]))
437 .with_str("defaultType", "swap"))
438 .into_value();
439 let options = dict(&dict(&v)["options"]);
440 assert_eq!(options["defaultType"], Value::Str("swap".into()));
441 let types = match &dict(&options["fetchMarkets"])["types"] { Value::Arr(a) => a.clone(), _ => panic!("types") };
442 assert_eq!(&types[..], &[Value::Str("swap".into())]);
443 }
444
445 #[test]
447 fn many_entries_at_one_level() {
448 let v = Config::new()
449 .option("fetchMarkets", Params::new()
450 .with_strs("types", &["spot", "swap"])
451 .with_bool("skipDelisted", true)
452 .with_int("limit", 500))
453 .into_value();
454 let fm = dict(&dict(&dict(&v)["options"])["fetchMarkets"]);
455 assert_eq!(fm.len(), 3);
456 assert_eq!(fm["skipDelisted"], Value::Bool(true));
457 assert_eq!(fm["limit"], Value::Int(500));
458 }
459
460 #[test]
462 fn repeated_option_calls_merge() {
463 let v = Config::new()
464 .option("fetchMarkets", Params::new().with_strs("types", &["spot"]))
465 .option("fetchMarkets", Params::new().with_bool("skipDelisted", true))
466 .into_value();
467 let fm = dict(&dict(&dict(&v)["options"])["fetchMarkets"]);
468 assert_eq!(fm.len(), 2, "second call must not clobber the first");
469 assert!(matches!(fm["types"], Value::Arr(_)));
470 assert_eq!(fm["skipDelisted"], Value::Bool(true));
471 }
472
473 #[test]
475 fn options_block_merges_with_neighbours() {
476 let v = Config::new()
477 .sandbox(true)
478 .options(Params::new().with_str("defaultType", "swap"))
479 .option_int("recvWindow", 5_000)
480 .into_value();
481 let options = dict(&dict(&v)["options"]);
482 assert_eq!(options["sandbox"], Value::Bool(true), "sandbox must survive options()");
483 assert_eq!(options["defaultType"], Value::Str("swap".into()));
484 assert_eq!(options["recvWindow"], Value::Int(5_000));
485 }
486
487 #[test]
488 fn a_literal_dot_in_a_key_stays_a_literal_dot() {
489 let v = Config::new().option_str("a.b", "x").into_value();
490 assert_eq!(dict(&dict(&v)["options"])["a.b"], Value::Str("x".into()));
491 }
492}