scope-bca-cli 0.7.0

Scope Blockchain Analysis - Command-line interface library
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
//! # Command Dispatch
//!
//! Routes a parsed [`Commands`] value to its handler. The `scope` binary and
//! the TUI both call [`dispatch`], so a command gives the same result in
//! both places. Process concerns (the version line, error display, the exit
//! code) stay with the caller.

use crate::cli::output::Output;
use crate::cli::{Cli, Commands};
use crate::{note, out};
use clap::CommandFactory;
use clap_complete::generate;
use scope::Config;
use scope::chains::{ChainClientFactory, DefaultClientFactory};
use scope::error::{Result, ScopeError};
use scope::http::HttpClient;
use std::sync::Arc;

/// Routes one command to its handler.
///
/// Creates the HTTP transport and client factory, then runs the handler
/// with `out` as its output. Returns the process exit code: 0, or the
/// TUI's code (128+N after signal N ended it).
///
/// # Errors
///
/// Returns the handler's error. `Commands::Web` is an error here: the web
/// server lives in the `scope-bca` crate, and its binary starts it before
/// dispatch.
pub async fn dispatch(command: Commands, config: &Config, out: &Output) -> Result<i32> {
    let http: Arc<dyn HttpClient> = create_http_client(config, out)?;
    let factory = DefaultClientFactory {
        chains_config: config.chains.clone(),
        http,
    };
    // Only the TUI can end with a code other than 0, so it starts here.
    if let Commands::Interactive(args) = command {
        let exit = crate::cli::interactive::run(args, config, &factory).await?;
        return Ok(exit.code);
    }
    dispatch_with(command, config, &factory, out)
        .await
        .map(|()| 0)
}

/// Routes one command to its handler, using the given client factory.
///
/// The TUI and the tests call this with their own factory (for example a
/// mock). [`dispatch`] calls it with the default factory.
///
/// # Errors
///
/// Returns the handler's error. See [`dispatch`]. `Commands::Interactive`
/// is an error here: the TUI starts only from [`dispatch`], which returns
/// its exit code.
pub async fn dispatch_with(
    command: Commands,
    config: &Config,
    clients: &dyn ChainClientFactory,
    out: &Output,
) -> Result<()> {
    match command {
        Commands::Completions(args) => {
            let mut cmd = Cli::command();
            let mut buf = Vec::new();
            generate(args.shell, &mut cmd, "scope", &mut buf);
            out!(out, "{}", String::from_utf8_lossy(&buf))?;
            Ok(())
        }
        Commands::Address(args) => crate::cli::address::run(args, config, clients, out).await,
        Commands::Tx(args) => crate::cli::tx::run(args, config, clients, out).await,
        Commands::Crawl(args) => crate::cli::crawl::run(args, config, clients, out).await,
        Commands::AddressBook(args) => {
            crate::cli::address_book::run(args, config, clients, out).await
        }
        Commands::Export(args) => crate::cli::export::run(args, config, clients, out).await,
        // The TUI calls dispatch_with and refuses a nested `interactive`
        // before it gets here (exec::route).
        Commands::Interactive(_) => Err(ScopeError::Other(
            "the TUI cannot start from here; start it with `scope tui`".into(),
        )),
        Commands::Monitor(args) => {
            crate::cli::monitor::run_direct(args, config, clients, out).await
        }
        Commands::Setup(args) => crate::cli::setup::run(args, config, out).await,
        Commands::Compliance(compliance_cmd) => {
            dispatch_compliance(compliance_cmd, config, out).await
        }
        Commands::Market(cmd) => crate::cli::market::run(cmd, config, clients, out).await,
        Commands::TokenHealth(args) => {
            crate::cli::token_health::run(args, config, clients, out).await
        }
        Commands::Venues(cmd) => crate::cli::venues::run(cmd, out),
        Commands::Report(cmd) => crate::cli::report::run(cmd, config, clients, out).await,
        Commands::Discover(args) => crate::cli::discover::run(args, config.output.format, out)
            .await
            .map_err(|e| match e {
                // An I/O error keeps its kind (a closed pipe exits quietly).
                ScopeError::IoError(_) => e,
                other => ScopeError::Discovery(other.to_string()),
            }),
        Commands::Insights(args) => crate::cli::insights::run(args, config, clients, out).await,
        Commands::Contract(ref args) => crate::cli::contract::run(args, config, clients, out).await,
        Commands::Web(_) => Err(ScopeError::Other(
            "the web server cannot run from here; start it with `scope web`".into(),
        )),
    }
}

/// Routes a compliance subcommand. `@label` inputs resolve through the
/// address book first.
async fn dispatch_compliance(
    cmd: crate::cli::compliance::ComplianceCommands,
    config: &Config,
    out: &Output,
) -> Result<()> {
    use crate::cli::address_book::resolve_address_book_input;
    use crate::cli::compliance::{self, ComplianceCommands};

    let result = match cmd {
        ComplianceCommands::Risk(mut args) => {
            if let Some((addr, chain)) = resolve_address_book_input(&args.address, config)? {
                args.address = addr;
                if args.chain.is_none() {
                    args.chain = Some(chain);
                }
            }
            compliance::handle_risk(args, out).await
        }
        ComplianceCommands::Trace(args) => compliance::handle_trace(args, out).await,
        ComplianceCommands::Analyze(mut args) => {
            if let Some((addr, _chain)) = resolve_address_book_input(&args.address, config)? {
                args.address = addr;
            }
            compliance::handle_analyze(args, out).await
        }
        ComplianceCommands::ComplianceReport(mut args) => {
            if !std::path::Path::new(&args.target).exists()
                && let Some((addr, _chain)) = resolve_address_book_input(&args.target, config)?
            {
                args.target = addr;
            }
            compliance::handle_compliance_report(args, out).await
        }
    };
    result.map_err(|e| from_anyhow(e, ScopeError::Compliance))
}

/// A command error from an `anyhow` handler. An I/O error keeps its kind
/// (a closed pipe stays a closed pipe) and a `ScopeError` stays itself;
/// anything else is wrapped by `kind` with its message.
fn from_anyhow(e: anyhow::Error, kind: fn(String) -> ScopeError) -> ScopeError {
    match e.downcast::<std::io::Error>() {
        Ok(io) => ScopeError::IoError(io),
        Err(e) => match e.downcast::<ScopeError>() {
            Ok(scope) => scope,
            Err(e) => kind(e.to_string()),
        },
    }
}

/// Installs the process transport on the first call (see `scope::http::shared`)
/// and prints the notices. Later calls return the same transport.
///
/// # Errors
///
/// Returns the error when the transport cannot be built.
pub fn create_http_client(config: &Config, out: &Output) -> Result<Arc<dyn HttpClient>> {
    let built = scope::http::init(config)?;
    for notice in &built.notices {
        note!(out, "{notice}");
    }
    Ok(built.client)
}

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

#[cfg(test)]
mod tests {
    #[test]
    fn test_anyhow_io_errors_keep_their_kind() {
        // A closed pipe in `compliance … | head` must still read as a
        // closed pipe, so the CLI exits quietly.
        let pipe = std::io::Error::new(std::io::ErrorKind::BrokenPipe, "closed");
        let e = super::from_anyhow(pipe.into(), ScopeError::Compliance);
        assert!(
            matches!(&e, ScopeError::IoError(io) if io.kind() == std::io::ErrorKind::BrokenPipe)
        );
        let scope = super::from_anyhow(
            ScopeError::NotFound("x".into()).into(),
            ScopeError::Compliance,
        );
        assert!(matches!(scope, ScopeError::NotFound(_)));
        let other = super::from_anyhow(anyhow::anyhow!("bad"), ScopeError::Compliance);
        assert_eq!(
            other.to_string(),
            ScopeError::Compliance("bad".into()).to_string()
        );
    }

    use super::*;
    use clap::Parser;
    use scope::http::shared::Kind;

    fn quiet() -> Output {
        Output::capture().0
    }

    #[test]
    fn test_create_http_client_returns_the_installed_transport() {
        // Two calls must give the same transport: one process, one transport.
        // Default config only: `init` installs for the whole test binary, and
        // a non-native transport would reach the mockito tests too.
        let config = Config::default();
        let (out, captured) = Output::capture();
        let a = create_http_client(&config, &out).unwrap();
        let b = create_http_client(&config, &out).unwrap();
        assert!(Arc::ptr_eq(&a, &b));
        // Default config selects native, which has nothing to report.
        assert!(captured.err().is_empty(), "{}", captured.err());
    }

    /// Selection for a Ghola config, without installing it for the process.
    /// The test machine may or may not run a Ghola sidecar: the result must
    /// be Ghola with no notice, or native with notices that say so.
    fn assert_ghola_selection(stealth: bool) {
        let mut config = Config::default();
        config.ghola.enabled = true;
        config.ghola.stealth = stealth;
        let built = scope::http::shared::build_with(&config, &|_| None).unwrap();
        match built.kind {
            Kind::Ghola => assert!(built.notices.is_empty(), "{:?}", built.notices),
            Kind::Native => {
                let all = built.notices.join("\n");
                assert!(all.contains("Ghola"), "{all}");
                assert!(all.contains("Falling back"), "{all}");
            }
            other => panic!("unexpected kind {other:?}"),
        }
    }

    #[test]
    fn test_transport_selection_default_config_is_native() {
        let built = scope::http::shared::build_with(&Config::default(), &|_| None).unwrap();
        assert_eq!(built.kind, Kind::Native);
        assert!(built.notices.is_empty(), "{:?}", built.notices);
    }

    #[test]
    fn test_transport_selection_ghola_enabled() {
        assert_ghola_selection(true);
    }

    #[test]
    fn test_transport_selection_ghola_no_stealth() {
        assert_ghola_selection(false);
    }

    #[tokio::test]
    async fn test_dispatch_writes_completions_to_output() {
        // The TUI shows dispatch output in a pane: completions must go to
        // the injected writer, not straight to the process stdout.
        let cli = Cli::try_parse_from(["scope", "completions", "bash"]).unwrap();
        let (o, cap) = Output::capture();
        dispatch(cli.command, &Config::default(), &o).await.unwrap();
        assert!(cap.out().contains("_scope()"));
    }

    #[tokio::test]
    async fn test_dispatch_fails_when_output_cannot_be_written() {
        // `scope completions zsh > /full/disk` must exit non-zero, not
        // report success with no file content.
        let cli = Cli::try_parse_from(["scope", "completions", "zsh"]).unwrap();
        let o = Output::from_writers(
            crate::cli::output::tests::ClosedPipe,
            crate::cli::output::tests::ClosedPipe,
        );
        let err = dispatch(cli.command, &Config::default(), &o)
            .await
            .unwrap_err();
        assert!(
            matches!(err, ScopeError::IoError(ref e) if e.kind() == std::io::ErrorKind::BrokenPipe)
        );
    }

    #[tokio::test]
    async fn test_dispatch_rejects_web() {
        // `web` needs the scope-bca crate; dispatch must fail, not panic.
        let cli = Cli::try_parse_from(["scope", "web"]).unwrap();
        let err = dispatch(cli.command, &Config::default(), &quiet())
            .await
            .unwrap_err();
        assert!(err.to_string().contains("scope web"));
    }

    // ---- dispatch_with routes to the real handlers (offline, mocks) ----

    const ADDR: &str = "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2";

    async fn run_line(args: &[&str]) -> (Result<()>, String) {
        let mut argv = vec!["scope"];
        argv.extend_from_slice(args);
        let cli = Cli::try_parse_from(argv).unwrap();
        let (o, cap) = Output::capture_merged();
        let factory = scope::chains::mocks::MockClientFactory::new();
        let res = dispatch_with(cli.command, &Config::default(), &factory, &o).await;
        (res, cap.out())
    }

    #[tokio::test]
    async fn test_dispatch_with_crawl_by_address() {
        let (res, out) = run_line(&["crawl", ADDR, "--yes", "--no-charts"]).await;
        res.unwrap();
        assert!(!out.trim().is_empty());
    }

    #[tokio::test]
    async fn test_dispatch_with_token_health() {
        let (res, out) = run_line(&["token-health", ADDR]).await;
        res.unwrap();
        assert!(!out.trim().is_empty());
    }

    #[tokio::test]
    async fn test_dispatch_with_report_batch_writes_the_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("batch.md");
        let (res, _) = run_line(&[
            "report",
            "batch",
            "--addresses",
            ADDR,
            "--output",
            path.to_str().unwrap(),
        ])
        .await;
        res.unwrap();
        assert!(std::fs::read_to_string(&path).unwrap().contains(ADDR));
    }

    #[tokio::test]
    async fn test_dispatch_with_refuses_the_tui() {
        // Only `dispatch` carries the TUI's exit code, so dispatch_with
        // (which the TUI itself calls) must refuse `interactive`.
        let (res, _) = run_line(&["interactive"]).await;
        assert!(res.unwrap_err().to_string().contains("scope tui"));
    }

    #[tokio::test]
    async fn test_compliance_errors_are_labelled_as_compliance_errors() {
        // Scripts match on the error kind, so a handler failure must come
        // back as ScopeError::Compliance, not as the handler's own error.
        let dir = tempfile::tempdir().unwrap();
        let empty = dir.path().join("none.txt");
        std::fs::write(&empty, "# no addresses\n").unwrap();
        let out = dir.path().join("report.txt");
        let (res, _) = run_line(&[
            "compliance",
            "compliance-report",
            empty.to_str().unwrap(),
            "--jurisdiction",
            "us",
            "--output",
            out.to_str().unwrap(),
        ])
        .await;
        let err = res.unwrap_err();
        assert!(matches!(err, ScopeError::Compliance(_)), "{err:?}");
        assert!(err.to_string().contains("No addresses to analyze"));

        let (res, _) = run_line(&["compliance", "risk", "not-an-address"]).await;
        assert!(matches!(res.unwrap_err(), ScopeError::Compliance(_)));
    }

    #[tokio::test]
    async fn test_compliance_unknown_label_fails_before_any_lookup() {
        // A typo in `@label` must stop at the address book (a NotFound
        // error that lists the labels), never reach a handler.
        let dir = tempfile::tempdir().unwrap();
        let mut config = Config::default();
        config.address_book.data_dir = Some(dir.path().to_path_buf());
        let factory = scope::chains::mocks::MockClientFactory::new();
        for args in [
            vec!["compliance", "risk", "@nobody"],
            vec!["compliance", "analyze", "@nobody"],
            vec![
                "compliance",
                "compliance-report",
                "@nobody",
                "--jurisdiction",
                "eu",
                "--output",
                "unused.txt",
            ],
        ] {
            let mut argv = vec!["scope"];
            argv.extend_from_slice(&args);
            let cli = Cli::try_parse_from(argv).unwrap();
            let (o, cap) = Output::capture_merged();
            let err = dispatch_with(cli.command, &config, &factory, &o)
                .await
                .unwrap_err();
            assert!(matches!(err, ScopeError::NotFound(_)), "{args:?}: {err:?}");
            assert!(err.to_string().contains("@nobody"), "{args:?}");
            assert!(!cap.out().contains("Analyzing"), "handler must not run");
        }
    }
}