scope-bca 0.6.0

Scope Blockchain Analysis - A production-grade tool for blockchain data analysis, address management, and transaction investigation
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! # Scope Blockchain Analysis
//!
//! Entry point for the blockchain analysis command-line tool.
//!
//! This binary provides commands for:
//!
//! **Entity lookup:**
//! - Address analysis (`scope address` / `addr`) with `--report` and `--dossier`
//! - Transaction analysis (`scope tx` / `transaction`)
//! - Unified insights (`scope insights` / `insight`) — auto-detects target type
//!
//! **Token analysis:**
//! - Token crawling (`scope crawl` / `token`) with report generation
//! - Token health suite (`scope token-health` / `health`) — DEX + optional market
//! - Token discovery (`scope discover` / `disc`) — trending/boosted from DexScreener
//! - Live monitoring (`scope monitor` / `mon`) — real-time TUI dashboard
//! - Market peg/order book health (`scope market summary`)
//!
//! **Compliance:**
//! - Risk, trace, analyze, and compliance-report (`scope compliance`)
//!
//! **Data & export:**
//! - Address book management (`scope address-book` / `ab`, alias: `portfolio` / `port`)
//! - Data export (`scope export`)
//! - Batch reporting (`scope report batch`)
//!
//! **Config & interactive:**
//! - Interactive mode (`scope interactive` / `shell`)
//! - Setup wizard (`scope setup` / `config`)
//! - Shell completions (`scope completions bash|zsh|fish`)
//!
//! ## UX Features
//!
//! - **Progress indicators** — Spinners and progress bars for long-running operations
//! - **Error remediation hints** — Actionable suggestions for common errors
//! - **Typo suggestions** — "Did you mean?" for misspelled commands
//! - **Shell completion** — Tab-completion for bash, zsh, and fish
//! - **Help with examples** — Example invocations in `--help` for every command
//! - Global `--ai` flag forces markdown output for agent/LLM parsing
//!
//! ## Usage
//!
//! ```bash
//! scope --help
//! scope address 0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2
//! scope tx 0xabc123...
//! scope insights 0xabc123...
//! scope discover --source boosts --chain ethereum
//! scope market summary USDC --format json
//! scope token-health USDC --with-market
//! scope monitor USDC --chain ethereum
//! scope address-book list
//! scope report batch --addresses 0x... --output report.md --with-risk
//! scope completions zsh > ~/.zfunc/_scope
//! ```

use anyhow::Result;
use clap::{CommandFactory, Parser};
use clap_complete::generate;
use scope::Config;
use scope::chains::DefaultClientFactory;
use scope::config::OutputFormat;
use scope::http::HttpClient;
use scope_cli::cli::errors::display_error;
use scope_cli::cli::{Cli, Commands};
use std::io::{self, Write};
use std::sync::Arc;
use tracing_subscriber::EnvFilter;

/// ASCII art banner featuring a Portia jumping spider.
/// Loaded from `assets/banner.txt` at compile time.
const BANNER: &str = include_str!("../assets/banner.txt");

/// Prints the startup banner to stderr.
fn print_banner() {
    eprintln!("{}", BANNER);
}

/// Application entry point.
///
/// Initializes logging, parses CLI arguments, loads configuration,
/// and dispatches to the appropriate command handler.
#[tokio::main]
async fn main() -> Result<()> {
    // Parse CLI arguments
    let cli = Cli::parse();

    // Initialize logging based on verbosity
    init_logging(cli.verbose);

    // Show banner in verbose mode
    if cli.verbose > 0 {
        print_banner();
    }

    tracing::debug!("Scope v{} starting", scope::VERSION);

    // Check if this is a setup command (don't prompt for setup if already running setup)
    let is_setup_command = matches!(cli.command, Commands::Setup(_));

    // Load configuration
    let mut config = Config::load(cli.config.as_deref()).unwrap_or_else(|e| {
        eprintln!("  ⚠ Could not load config, using defaults (use -v for details)");
        tracing::debug!("Failed to load config: {}", e);
        Config::default()
    });

    // --ai forces markdown output to console for agent parsing
    if cli.ai {
        config.output.format = OutputFormat::Markdown;
    }

    // Handle web command early (before setup check and factory creation)
    if let Commands::Web(ref web_args) = cli.command {
        let addr: std::net::SocketAddr = format!("{}:{}", web_args.bind, web_args.port)
            .parse()
            .unwrap_or_else(|_| {
                eprintln!("Invalid bind address: {}:{}", web_args.bind, web_args.port);
                std::process::exit(1);
            });

        if web_args.stop {
            if let Err(e) = scope_web::stop_daemon() {
                eprintln!("Error: {}", e);
                std::process::exit(1);
            }
            return Ok(());
        }

        // If running as daemon child, skip daemon forking
        if scope_web::is_daemon_child() || !web_args.daemon {
            return scope_web::start_server(addr, config)
                .await
                .map_err(|e| anyhow::anyhow!(e));
        }

        // Fork daemon
        if let Err(e) = scope_web::start_daemon(addr, config) {
            eprintln!("Error: {}", e);
            std::process::exit(1);
        }
        return Ok(());
    }

    // Check if config file exists and prompt for setup if needed
    if !is_setup_command && !config_file_exists(&cli) && prompt_for_setup() {
        // Run setup wizard
        let setup_args = scope_cli::cli::setup::SetupArgs {
            status: false,
            key: None,
            reset: false,
        };
        if let Err(e) = scope_cli::cli::setup::run(setup_args, &config).await {
            eprintln!("Setup failed: {}", e);
        }
        // Reload config after setup
        let mut config = Config::load(cli.config.as_deref()).unwrap_or_default();
        if cli.ai {
            config.output.format = OutputFormat::Markdown;
        }
        return dispatch(cli.command, &config).await;
    }

    // Dispatch the command through the unified handler
    dispatch(cli.command, &config).await
}

/// Checks if a configuration file exists.
fn config_file_exists(cli: &Cli) -> bool {
    if let Some(ref path) = cli.config {
        return path.exists();
    }
    Config::config_path().map(|p| p.exists()).unwrap_or(false)
}

/// Prompts the user to run setup.
fn prompt_for_setup() -> bool {
    eprintln!();
    eprintln!("Welcome to Scope Blockchain Analysis!");
    eprintln!();
    eprintln!("No configuration file found. Would you like to run the setup wizard");
    eprintln!("to configure API keys and preferences?");
    eprintln!();
    eprint!("Run setup now? [Y/n]: ");
    io::stderr().flush().ok();

    let mut input = String::new();
    if io::stdin().read_line(&mut input).is_err() {
        return false;
    }

    let response = input.trim().to_lowercase();
    // Default to yes if user just presses Enter
    response.is_empty() || response == "y" || response == "yes"
}

/// Unified command dispatcher.
///
/// Creates the HTTP transport and client factory, then routes the command
/// to the appropriate handler. Called from both the main flow and the
/// post-setup-wizard path.
async fn dispatch(command: Commands, config: &Config) -> Result<()> {
    // Print version on stderr for non-interactive commands
    if !command.is_interactive() {
        eprintln!("Scope v{}", scope::VERSION);
    }

    let http: Arc<dyn HttpClient> = create_http_client(config);
    let factory = DefaultClientFactory {
        chains_config: config.chains.clone(),
        http,
    };

    let result = match command {
        Commands::Completions(args) => {
            let mut cmd = Cli::command();
            generate(args.shell, &mut cmd, "scope", &mut io::stdout());
            Ok(())
        }
        Commands::Address(args) => scope_cli::cli::address::run(args, config, &factory).await,
        Commands::Tx(args) => scope_cli::cli::tx::run(args, config, &factory).await,
        Commands::Crawl(args) => scope_cli::cli::crawl::run(args, config, &factory).await,
        Commands::AddressBook(args) => {
            scope_cli::cli::address_book::run(args, config, &factory).await
        }
        Commands::Export(args) => scope_cli::cli::export::run(args, config, &factory).await,
        Commands::Interactive(args) => {
            scope_cli::cli::interactive::run(args, config, &factory).await
        }
        Commands::Monitor(args) => {
            scope_cli::cli::monitor::run_direct(args, config, &factory).await
        }
        Commands::Setup(args) => scope_cli::cli::setup::run(args, config).await,
        Commands::Compliance(compliance_cmd) => match compliance_cmd {
            scope_cli::cli::compliance::ComplianceCommands::Risk(mut args) => {
                if let Some((addr, chain)) =
                    scope_cli::cli::address_book::resolve_address_book_input(&args.address, config)?
                {
                    args.address = addr;
                    if args.chain.is_none() {
                        args.chain = Some(chain);
                    }
                }
                scope_cli::cli::compliance::handle_risk(args)
                    .await
                    .map_err(|e| scope::error::ScopeError::Compliance(e.to_string()))
            }
            scope_cli::cli::compliance::ComplianceCommands::Trace(args) => {
                scope_cli::cli::compliance::handle_trace(args)
                    .await
                    .map_err(|e| scope::error::ScopeError::Compliance(e.to_string()))
            }
            scope_cli::cli::compliance::ComplianceCommands::Analyze(mut args) => {
                if let Some((addr, _chain)) =
                    scope_cli::cli::address_book::resolve_address_book_input(&args.address, config)?
                {
                    args.address = addr;
                }
                scope_cli::cli::compliance::handle_analyze(args)
                    .await
                    .map_err(|e| scope::error::ScopeError::Compliance(e.to_string()))
            }
            scope_cli::cli::compliance::ComplianceCommands::ComplianceReport(mut args) => {
                if !std::path::Path::new(&args.target).exists()
                    && let Some((addr, _chain)) =
                        scope_cli::cli::address_book::resolve_address_book_input(
                            &args.target,
                            config,
                        )?
                {
                    args.target = addr;
                }
                scope_cli::cli::compliance::handle_compliance_report(args)
                    .await
                    .map_err(|e| scope::error::ScopeError::Compliance(e.to_string()))
            }
        },
        Commands::Market(cmd) => scope_cli::cli::market::run(cmd, config, &factory).await,
        Commands::TokenHealth(args) => {
            scope_cli::cli::token_health::run(args, config, &factory).await
        }
        Commands::Venues(cmd) => scope_cli::cli::venues::run(cmd),
        Commands::Report(cmd) => scope_cli::cli::report::run(cmd, config, &factory).await,
        Commands::Discover(args) => scope_cli::cli::discover::run(args, config.output.format)
            .await
            .map_err(|e| scope::error::ScopeError::Discovery(e.to_string())),
        Commands::Insights(args) => scope_cli::cli::insights::run(args, config, &factory).await,
        Commands::Contract(ref args) => scope_cli::cli::contract::run(args, config, &factory).await,
        // Web command is handled in main() before dispatch
        Commands::Web(_) => unreachable!("Web command handled before dispatch"),
    };

    if let Err(e) = result {
        tracing::debug!("Command failed: {}", e);
        display_error(&e);
        std::process::exit(1);
    }

    Ok(())
}

/// Creates the appropriate HTTP transport based on Ghola configuration.
///
/// When `config.ghola.enabled` is `true`, attempts to create a Ghola
/// sidecar client. Falls back to native `reqwest` if Ghola fails to start
/// or is not installed.
fn create_http_client(config: &Config) -> Arc<dyn HttpClient> {
    if config.ghola.enabled {
        match scope::http::GholaHttpClient::new(config.ghola.stealth, config.ghola.buffer_size) {
            Ok(client) => {
                tracing::info!("Using Ghola sidecar for HTTP transport");
                return Arc::new(client);
            }
            Err(e) => {
                eprintln!("  ⚠ Ghola sidecar enabled but unavailable: {}", e);
                eprintln!("    Install: go install github.com/robot-accomplice/ghola@latest");
                eprintln!("    Falling back to native HTTP transport");
            }
        }
    }

    Arc::new(scope::http::NativeHttpClient::new().expect("Failed to create HTTP client"))
}

/// Initializes the tracing subscriber for logging.
///
/// Configures log level based on the verbosity flag:
/// - 0: WARN (default, minimal output)
/// - 1: INFO (general information)
/// - 2: DEBUG (detailed debugging)
/// - 3+: TRACE (very verbose, all details)
///
/// # Arguments
///
/// * `verbosity` - The number of `-v` flags provided
fn init_logging(verbosity: u8) {
    let level = match verbosity {
        0 => "warn",
        1 => "info",
        2 => "debug",
        _ => "trace",
    };

    // Allow RUST_LOG to override if set
    let filter = EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| EnvFilter::new(format!("scope={},warn", level)));

    let builder = tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_target(false)
        .with_thread_ids(false);

    // At low verbosity, use a compact format without timestamps so output
    // looks like normal CLI messages rather than log entries.
    if verbosity < 2 {
        builder.without_time().with_level(false).init();
    } else {
        builder.init();
    }
}

// ============================================================================
// Unit Tests
// ============================================================================

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

    #[test]
    fn test_verbosity_levels() {
        // Just verify the mapping logic
        assert_eq!(
            match 0u8 {
                0 => "warn",
                1 => "info",
                2 => "debug",
                _ => "trace",
            },
            "warn"
        );
        assert_eq!(
            match 1u8 {
                0 => "warn",
                1 => "info",
                2 => "debug",
                _ => "trace",
            },
            "info"
        );
        assert_eq!(
            match 2u8 {
                0 => "warn",
                1 => "info",
                2 => "debug",
                _ => "trace",
            },
            "debug"
        );
        assert_eq!(
            match 3u8 {
                0 => "warn",
                1 => "info",
                2 => "debug",
                _ => "trace",
            },
            "trace"
        );
    }

    #[test]
    fn test_cli_parsing() {
        // Verify CLI can be parsed (basic smoke test)
        let result = Cli::try_parse_from([
            "scope",
            "address",
            "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
        ]);
        assert!(result.is_ok());
    }

    #[test]
    fn test_cli_help_flag() {
        // Help should cause an error (it exits)
        let result = Cli::try_parse_from(["scope", "--help"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_cli_version_flag() {
        // Version should cause an error (it exits)
        let result = Cli::try_parse_from(["scope", "--version"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_config_file_exists_with_explicit_path() {
        // Create a temp file and point CLI at it
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("test_config.toml");
        std::fs::write(&config_path, "").unwrap();

        let cli = Cli::try_parse_from([
            "scope",
            "--config",
            config_path.to_str().unwrap(),
            "venues",
            "list",
        ])
        .unwrap();
        assert!(config_file_exists(&cli));
    }

    #[test]
    fn test_config_file_exists_nonexistent() {
        let cli = Cli::try_parse_from([
            "scope",
            "--config",
            "/tmp/nonexistent_scope_config_test.toml",
            "venues",
            "list",
        ])
        .unwrap();
        assert!(!config_file_exists(&cli));
    }

    #[test]
    fn test_cli_completions_parsing() {
        let result = Cli::try_parse_from(["scope", "completions", "bash"]);
        assert!(result.is_ok());
    }

    #[test]
    fn test_create_http_client_default_config() {
        let config = Config::default();
        let client = create_http_client(&config);
        // Default config has ghola.enabled = false, so should get NativeHttpClient
        let _: &dyn HttpClient = &*client;
    }

    #[test]
    fn test_create_http_client_ghola_enabled() {
        let mut config = Config::default();
        config.ghola.enabled = true;
        config.ghola.stealth = true;
        let client = create_http_client(&config);
        // Should still succeed (falls back to native if ghola not installed)
        let _: &dyn HttpClient = &*client;
    }

    #[test]
    fn test_create_http_client_ghola_no_stealth() {
        let mut config = Config::default();
        config.ghola.enabled = true;
        config.ghola.stealth = false;
        let client = create_http_client(&config);
        let _: &dyn HttpClient = &*client;
    }
}