indodax-cli 0.1.49

A command-line interface for the Indodax cryptocurrency exchange
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use crate::client::IndodaxClient;
use crate::config::ResolvedCredentials;
use crate::output::CommandOutput;
use anyhow::Result;
use rustyline::completion::{Completer, Pair};
use rustyline::highlight::{Highlighter, MatchingBracketHighlighter};
use rustyline::hint::{HistoryHinter};
use rustyline::validate::MatchingBracketValidator;
use rustyline::{Helper};
use std::collections::HashMap;

#[derive(Debug, clap::Subcommand)]
pub enum UtilityCommand {
    #[command(name = "setup", about = "Interactive setup wizard")]
    Setup,

    #[command(name = "shell", about = "Start interactive REPL")]
    Shell,
}

struct IndodaxHelper {
    completer: IndodaxCompleter,
    highlighter: MatchingBracketHighlighter,
    validator: MatchingBracketValidator,
    hinter: HistoryHinter,
}

struct IndodaxCompleter {
    commands: Vec<String>,
    pairs: Vec<String>,
}

impl Completer for IndodaxCompleter {
    type Candidate = Pair;

    fn complete(
        &self,
        line: &str,
        pos: usize,
        _ctx: &rustyline::Context<'_>,
    ) -> rustyline::Result<(usize, Vec<Pair>)> {
        let (start, word) = rustyline::completion::extract_word(line, pos, None, |c: char| c == ' ' || c == '/');
        let word_lower = word.to_lowercase();

        let mut candidates = Vec::new();

        // If it looks like we are typing a pair (e.g. after a space or --pair)
        let line_before = &line[..start];
        let is_pair_context = line_before.contains("ticker") || 
                             line_before.contains("book") || 
                             line_before.contains("trades") ||
                             line_before.contains("--pair") ||
                             line_before.contains("-p");

        if is_pair_context {
            for pair in &self.pairs {
                if pair.starts_with(&word_lower) {
                    candidates.push(Pair {
                        display: pair.clone(),
                        replacement: pair.clone(),
                    });
                }
            }
        }

        // Also suggest commands if we are at the start or just after 'indodax '
        if start == 0 || line_before.trim().is_empty() {
            for cmd in &self.commands {
                if cmd.starts_with(&word_lower) {
                    candidates.push(Pair {
                        display: cmd.clone(),
                        replacement: cmd.clone(),
                    });
                }
            }
        }

        Ok((start, candidates))
    }
}

impl Highlighter for IndodaxHelper {
    fn highlight<'l>(&self, line: &'l str, pos: usize) -> std::borrow::Cow<'l, str> {
        self.highlighter.highlight(line, pos)
    }
    fn highlight_char(&self, line: &str, pos: usize) -> bool {
        self.highlighter.highlight_char(line, pos)
    }
}

impl rustyline::hint::Hinter for IndodaxHelper {
    type Hint = String;
    fn hint(&self, line: &str, pos: usize, ctx: &rustyline::Context<'_>) -> Option<String> {
        self.hinter.hint(line, pos, ctx)
    }
}

impl rustyline::validate::Validator for IndodaxHelper {
    fn validate(&self, ctx: &mut rustyline::validate::ValidationContext<'_>) -> rustyline::Result<rustyline::validate::ValidationResult> {
        self.validator.validate(ctx)
    }
    fn validate_while_typing(&self) -> bool {
        self.validator.validate_while_typing()
    }
}

impl Completer for IndodaxHelper {
    type Candidate = Pair;
    fn complete(&self, line: &str, pos: usize, ctx: &rustyline::Context<'_>) -> rustyline::Result<(usize, Vec<Pair>)> {
        self.completer.complete(line, pos, ctx)
    }
}

impl Helper for IndodaxHelper {}

pub async fn execute(
    client: &IndodaxClient,
    creds: &Option<ResolvedCredentials>,
    cmd: &UtilityCommand,
) -> Result<CommandOutput> {
    match cmd {
        UtilityCommand::Setup => setup().await,
        UtilityCommand::Shell => shell(client, creds).await,
    }
}

async fn test_credentials(api_key: &str, api_secret: &str) {
    use crate::auth::Signer;
    let signer = Signer::new(api_key, api_secret);
    match IndodaxClient::new(Some(signer)) {
        Ok(client) => {
            match client
                .private_post_v1::<serde_json::Value>("getInfo", &HashMap::new())
                .await
            {
                Ok(info) => {
                    let name = info
                        .get("name")
                        .and_then(|v| v.as_str())
                        .unwrap_or("unknown");
                    let user_id = info
                        .get("user_id")
                        .and_then(|v| v.as_str())
                        .unwrap_or("unknown");
                    eprintln!(
                        "  Credentials validated: logged in as '{}' (user ID: {})",
                        name, user_id
                    );
                }
                Err(e) => {
                    eprintln!("  Warning: Credentials saved but validation failed: {}", e);
                    eprintln!("  Check that your API key and secret are correct.");
                }
            }
        }
        Err(e) => {
            eprintln!("  Warning: Could not create client for validation: {}", e);
        }
    }
}

async fn setup() -> Result<CommandOutput> {
    use dialoguer::{Confirm, Input, Password};

    eprintln!("=== Indodax CLI Setup Wizard ===\n");

    let api_key: String = Input::new()
        .with_prompt("Enter your Indodax API key")
        .interact_text()?;

    let api_secret: String = Password::new()
        .with_prompt("Enter your Indodax API secret")
        .interact()?;

    let callback_url: String = Input::new()
        .with_prompt("Enter your Indodax Callback URL (optional, e.g., https://indodax.tep2.in/)")
        .allow_empty(true)
        .interact_text()?;

    let save: bool = Confirm::new()
        .with_prompt("Save configuration to config?")
        .default(true)
        .interact()?;

    if save {
        let mut config = crate::config::IndodaxConfig::load()?;
        config.api_key = Some(crate::config::SecretValue::new(&api_key));
        config.api_secret = Some(crate::config::SecretValue::new(&api_secret));
        if !callback_url.is_empty() {
            config.callback_url = Some(callback_url);
        }
        config.save()?;
        eprintln!(
            "\nConfiguration saved to {:?}",
            crate::config::IndodaxConfig::config_path()
        );
    }

    eprintln!("\nValidating credentials...");
    test_credentials(&api_key, &api_secret).await;

    let data = serde_json::json!({
        "status": "ok",
        "message": "Setup complete"
    });
    Ok(CommandOutput::json(data))
}

async fn shell(
    client: &IndodaxClient,
    _creds: &Option<ResolvedCredentials>,
) -> Result<CommandOutput> {
    use crate::Cli;
    use clap::Parser;
    use clap::CommandFactory;

    println!("Indodax CLI interactive shell");
    println!("Type commands without 'indodax' prefix (e.g. 'ticker btc/idr')");
    println!("Type 'help' for available commands, 'exit' to quit\n");

    // Pre-collect commands for completion
    let mut command_list = Vec::new();
    let cli_cmd = Cli::command();
    for cmd in cli_cmd.get_subcommands() {
        command_list.push(cmd.get_name().to_string());
    }
    
    // Add common pairs for completion
    let common_pairs = vec![
        "btc_idr".to_string(), "eth_idr".to_string(), "usdt_idr".to_string(), 
        "idrt_idr".to_string(), "bnb_idr".to_string(), "doge_idr".to_string(),
        "xrpidr".to_string(), "adaidr".to_string(), "dotidr".to_string(),
    ];

    let h = IndodaxHelper {
        completer: IndodaxCompleter {
            commands: command_list,
            pairs: common_pairs,
        },
        highlighter: MatchingBracketHighlighter::new(),
        validator: MatchingBracketValidator::new(),
        hinter: HistoryHinter {},
    };

    let mut rl = rustyline::Editor::<IndodaxHelper, rustyline::history::DefaultHistory>::new()?;
    rl.set_helper(Some(h));
    
    let mut config = crate::config::IndodaxConfig::load()?;
    let client_ref = client;

    loop {
        let line = rl.readline("indodax> ");
        match line {
            Ok(input) if input.trim().is_empty() => continue,
            Ok(input) if input.trim() == "exit" || input.trim() == "quit" => break,
            Ok(input) => {
                let _ = rl.add_history_entry(&input);
                let args = format!("indodax {}", input);
                let args: Vec<String> = shell_parse(&args);
                match Cli::try_parse_from(args) {
                    Ok(cli) => {
                        if matches!(cli.command, crate::Command::Shell) {
                            println!("Already in shell mode");
                            continue;
                        }
                        if matches!(cli.command, crate::Command::Setup) {
                            println!("Setup is only available from the command line, not inside the shell");
                            continue;
                        }
                        match crate::dispatch(cli, client_ref, &mut config).await {
                            Ok(output) => println!("{}", output.render()),
                            Err(e) => {
                                eprintln!("Error: {}", e);
                            }
                        }
                    }
                    Err(e) => eprintln!("{}", e.render()),
                }
            }
            Err(_) => break,
        }
    }

    let data = serde_json::json!({"status": "exited"});
    Ok(CommandOutput::json(data))
}

/// Splits a shell-style command line into argv-like tokens.
fn shell_parse(input: &str) -> Vec<String> {
    #[cfg(not(target_arch = "wasm32"))]
    {
        shlex::split(input).unwrap_or_default()
    }

    #[cfg(target_arch = "wasm32")]
    {
        input.split_whitespace().map(|s| s.to_string()).collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_shell_parse_simple() {
        let result = shell_parse("market ticker btc_idr");
        assert_eq!(result, vec!["market", "ticker", "btc_idr"]);
    }

    #[test]
    fn test_shell_parse_single_word() {
        let result = shell_parse("help");
        assert_eq!(result, vec!["help"]);
    }

    #[test]
    fn test_shell_parse_empty() {
        let result = shell_parse("");
        assert!(result.is_empty());
    }

    #[test]
    fn test_shell_parse_with_quotes() {
        let result = shell_parse(r#"auth set --api-key "my key" --api-secret "my secret""#);
        assert_eq!(
            result,
            vec![
                "auth",
                "set",
                "--api-key",
                "my key",
                "--api-secret",
                "my secret",
            ]
        );
    }

    #[test]
    fn test_shell_parse_quoted_value_with_dash() {
        let result = shell_parse(r#"market ticker --pair "btc_idr""#);
        assert_eq!(result, vec!["market", "ticker", "--pair", "btc_idr"]);
    }

    #[test]
    fn test_shell_parse_multiple_spaces() {
        let result = shell_parse("market   ticker   btc_idr");
        assert_eq!(result, vec!["market", "ticker", "btc_idr"]);
    }

    #[test]
    fn test_shell_parse_leading_trailing_spaces() {
        let result = shell_parse("  market ticker btc_idr  ");
        assert_eq!(result, vec!["market", "ticker", "btc_idr"]);
    }

    #[test]
    fn test_shell_parse_only_whitespace() {
        let result = shell_parse("    ");
        assert!(result.is_empty());
    }

    #[test]
    fn test_shell_parse_quoted_empty_string() {
        let result = shell_parse(r#"set key """#);
        assert_eq!(result, vec!["set", "key", ""]);
    }

    #[test]
    fn test_shell_parse_quoted_whitespace_only() {
        let result = shell_parse(r#"echo "   ""#);
        assert_eq!(result, vec!["echo", "   "]);
    }

    #[test]
    fn test_shell_parse_escaped_quote_inside_quotes() {
        let result = shell_parse(r#"echo "he said \"hi\"""#);
        assert_eq!(result, vec!["echo", r#"he said "hi""#]);
    }

    #[test]
    fn test_shell_parse_escaped_backslash_inside_quotes() {
        let result = shell_parse(r#"path "a\\b""#);
        assert_eq!(result, vec!["path", r#"a\b"#]);
    }

    #[test]
    fn test_shell_parse_unclosed_quote_returns_empty() {
        let result = shell_parse(r#"foo "bar baz"#);
        // shlex returns None on parse error (unclosed quotes), unwrap_or_default gives empty vec
        assert!(result.is_empty());
    }

    #[test]
    fn test_shell_parse_adjacent_quoted_and_bare() {
        let result = shell_parse(r#"x="hello world""#);
        assert_eq!(result, vec!["x=hello world"]);
    }

    #[test]
    fn test_shell_parse_tab_separator() {
        let result = shell_parse("a\tb\tc");
        assert_eq!(result, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_utility_command_variants() {
        let _cmd1 = UtilityCommand::Setup;
        let _cmd2 = UtilityCommand::Shell;
    }

    #[test]
    fn test_shell_parse_with_dash_args() {
        let result = shell_parse("account balance -v");
        assert_eq!(result, vec!["account", "balance", "-v"]);
    }
}