scope-bca-cli 0.8.6

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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! A watchlist run: ticks on the watchlist's schedule, through the one
//! repeat runner, with the CSV trail and the final report.

use super::fetch::Tick;
use super::{Ready, Sources, tick};
use crate::cli::output::Output;
use crate::cli::repeat::{self, RunOutput, Schedule};
use scope::error::{Result, ScopeError};
use scope::metrics::Sample;
use scope::watch::{Event, History, Snapshot, Watchlist, diff};
use std::io::Write as _;
use std::path::Path;

/// The CSV header of a watchlist run (one row per cell per tick).
pub fn csv_header() -> &'static str {
    "ts,target,metric,value,op,threshold,status,source,error,detail\n"
}

/// The CSV rows of one tick: every cell of every target. `source` is
/// `preset` for a preset check and the metric's group for a rule.
pub fn csv_rows(at: &str, snapshot: &Snapshot) -> String {
    let mut rows = String::new();
    for t in &snapshot.targets {
        for c in &t.cells {
            let (metric, op, threshold, source) = match &c.rule {
                Some(r) => (
                    r.metric.name().to_string(),
                    r.op.symbol().to_string(),
                    r.value.to_string(),
                    format!("{:?}", r.metric.group()).to_lowercase(),
                ),
                None => (
                    c.label.clone(),
                    String::new(),
                    String::new(),
                    "preset".into(),
                ),
            };
            let value = c.value.map(|v| v.to_string()).unwrap_or_default();
            let error = match &c.status {
                scope::watch::RuleStatus::Error(e) => e.as_str(),
                _ => "",
            };
            let fields = [
                at,
                &t.target,
                &metric,
                &value,
                &op,
                &threshold,
                c.status.name(),
                &source,
                error,
                // A preset check's text: it keeps the numbers of a check
                // that passed, too.
                c.detail.as_deref().unwrap_or(""),
            ];
            let cells: Vec<String> = fields.iter().map(|f| csv_field(f)).collect();
            rows.push_str(&cells.join(","));
            rows.push('\n');
        }
    }
    rows
}

/// A CSV field, quoted when it holds a comma, a quote or a line break.
fn csv_field(s: &str) -> String {
    if s.contains([',', '"', '\n', '\r']) {
        format!("\"{}\"", s.replace('"', "\"\""))
    } else {
        s.to_string()
    }
}

/// The report of a run: one `market summary --report` section per row
/// with a summary (one per venue), then every cell's last value.
pub fn report_text(w: &Watchlist, last: &Tick) -> String {
    let mut md = format!("# Watchlist Report: {}\n\n", w.name);
    // The tick's rows, and so its summaries, follow each target's rows.
    let rows = w
        .targets
        .iter()
        .flat_map(|t| t.rows().into_iter().map(move |venue| (t, venue)));
    for ((t, venue), summary) in rows.zip(&last.summaries) {
        if let (Some(summary), Some(venue)) = (summary, venue) {
            md.push_str(&crate::cli::market::market_summary_to_markdown(
                summary, venue, &t.id,
            ));
            md.push('\n');
        }
    }
    md.push_str(
        "## Last values\n\n| Target | Check | Value | Status | Detail |\n|---|---|---|---|---|\n",
    );
    for t in &last.snapshot.targets {
        for c in &t.cells {
            let value = c.value.map(|v| v.to_string()).unwrap_or_else(|| "-".into());
            let detail = c.status.message().unwrap_or("").replace('|', "\\|");
            md.push_str(&format!(
                "| {} | {} | {} | {} | {} |\n",
                t.target,
                c.label.replace('|', "\\|"),
                value,
                c.status.name(),
                detail
            ));
        }
    }
    md
}

/// Writes the report of `last` to `path`.
pub fn write_report(path: &Path, w: &Watchlist, last: &Tick) -> Result<()> {
    std::fs::write(path, report_text(w, last))
        .map_err(|e| ScopeError::io_context(e, format!("cannot write {}", path.display())))
}

/// The run's schedule; a run with no duration goes until cancelled.
pub fn schedule(w: &Watchlist) -> Result<Schedule> {
    match w.duration {
        Some(d) => Schedule::new(w.interval, d),
        None => Schedule::until_cancelled(w.interval),
    }
}

/// Runs `ready` on its schedule. After each tick, `on_tick` gets the run
/// number, the tick and the events since the tick before. The CSV gets one
/// row per cell per tick; at the end of the duration, the report is
/// written. A CSV or report write error ends the run and is returned.
///
/// Returns the last tick.
pub async fn run(
    ready: &Ready,
    src: Sources<'_>,
    out: &Output,
    mut on_tick: impl FnMut(u64, &Tick, &[Event]),
) -> Result<Tick> {
    let w = &ready.list;
    if let Some(path) = &w.outputs.csv {
        std::fs::write(path, csv_header())
            .map_err(|e| ScopeError::io_context(e, format!("cannot write {}", path.display())))?;
    }
    // The step closure is called once per tick and its future outlives
    // the call, so the state it changes is shared through cells.
    let prev = std::cell::RefCell::new(Snapshot::default());
    let history = std::cell::RefCell::new(History::default());
    let on_tick = std::cell::RefCell::new(&mut on_tick);
    let (prev, history, on_tick) = (&prev, &history, &on_tick);
    let last = repeat::run(&schedule(w)?, &[], None, out, |n| async move {
        // Taken out for the tick, so no borrow is held across its awaits.
        let mut memory = history.take();
        let t = tick(ready, src, out, &mut memory).await;
        history.replace(memory);
        let events = diff(&prev.borrow(), &t.snapshot);
        if let Some(path) = &w.outputs.csv {
            let at = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
            append(path, &csv_rows(&at, &t.snapshot))?;
        }
        (on_tick.borrow_mut())(n, &t, &events);
        *prev.borrow_mut() = t.snapshot.clone();
        let failed: Vec<String> = events
            .iter()
            .filter(|e| matches!(e, Event::BreachStarted { .. }))
            .map(Event::banner)
            .collect();
        Ok(RunOutput {
            sample: Sample {
                values: Vec::new(),
                healthy: t.snapshot.breaches() == 0,
                failed_checks: failed,
            },
            snapshot: String::new(),
            view: None,
            value: t,
        })
    })
    .await?
    .unwrap_or_default();
    if let Some(path) = &w.outputs.report {
        write_report(path, w, &last)?;
        out.note_saved("Report", path.display());
    }
    Ok(last)
}

fn append(path: &Path, rows: &str) -> Result<()> {
    let context = || format!("cannot append to {}", path.display());
    let mut file = std::fs::OpenOptions::new()
        .append(true)
        .open(path)
        .map_err(|e| ScopeError::io_context(e, context()))?;
    file.write_all(rows.as_bytes())
        .map_err(|e| ScopeError::io_context(e, context()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use scope::chains::mocks::MockClientFactory;
    use scope::watch::{Cell, Rule, RuleStatus, Target, TargetKind, TargetSnapshot};
    use std::time::Duration;

    #[test]
    fn csv_rows_hold_every_cell_and_quote_commas() {
        let snapshot = Snapshot {
            targets: vec![TargetSnapshot::new(
                "USDC@binance",
                vec![
                    Cell {
                        label: "Spread".into(),
                        rule: None,
                        value: Some(3.4),
                        status: RuleStatus::Fail("Spread: 3.4%, max 3%".into()),
                        detail: Some("Spread: 3.4%, max 3%".into()),
                    },
                    // A passing check keeps its value and text (the 0.8.0
                    // smoke test found them empty).
                    Cell {
                        label: "Bid depth".into(),
                        rule: None,
                        value: Some(4200.0),
                        status: RuleStatus::Pass,
                        detail: Some("Bid depth: 4200 USDT (min 3000)".into()),
                    },
                    Cell {
                        label: "holders >= 10".into(),
                        rule: Some(Rule::parse("holders >= 10").unwrap()),
                        value: None,
                        status: RuleStatus::Error("timeout, retry".into()),
                        detail: None,
                    },
                ],
            )],
        };
        let rows = csv_rows("2026-10-16T12:00:00Z", &snapshot);
        let lines: Vec<&str> = rows.lines().collect();
        assert_eq!(lines.len(), 3);
        assert_eq!(
            lines[0],
            "2026-10-16T12:00:00Z,USDC@binance,Spread,3.4,,,fail,preset,,\"Spread: 3.4%, max 3%\""
        );
        assert_eq!(
            lines[1],
            "2026-10-16T12:00:00Z,USDC@binance,Bid depth,4200,,,pass,preset,,Bid depth: 4200 USDT (min 3000)"
        );
        assert_eq!(
            lines[2],
            "2026-10-16T12:00:00Z,USDC@binance,holders,,>=,10,error,token,\"timeout, retry\","
        );
        assert_eq!(csv_header().split(',').count(), 10);
    }

    #[tokio::test]
    async fn a_run_ticks_writes_the_csv_and_the_report() {
        let dir = tempfile::tempdir().unwrap();
        let csv = dir.path().join("w.csv");
        let report = dir.path().join("w.md");
        let mut t = Target::new(
            TargetKind::Token,
            "0x1234567890123456789012345678901234567890",
        );
        t.rules = vec![Rule::parse("price_usd > 0").unwrap()];
        let mut w = Watchlist::new("test");
        // Room for several ticks even when a tick is slow (a coverage build
        // runs instrumented): 15 ms left room for one, and the test needs
        // two.
        w.interval = Duration::from_millis(50);
        w.duration = Some(Duration::from_millis(500));
        w.outputs.csv = Some(csv.clone());
        w.outputs.report = Some(report.clone());
        w.targets = vec![t];
        let ready = Ready {
            list: w,
            contracts: vec![None],
        };
        let factory = MockClientFactory::new();
        let config = scope::config::Config::default();
        let src = Sources {
            config: &config,
            clients: &factory,
        };
        let mut ticks = Vec::new();
        let (out, _cap) = Output::capture();
        let last = run(&ready, src, &out, |n, _, events| {
            ticks.push((n, events.len()))
        })
        .await
        .unwrap();
        // The tick count depends on timing; the runs are numbered from 1.
        let runs: Vec<u64> = ticks.iter().map(|t| t.0).collect();
        assert!(runs.len() >= 2, "{runs:?}");
        assert_eq!(runs, (1..=runs.len() as u64).collect::<Vec<_>>());
        assert!(ticks.iter().all(|t| t.1 == 0), "a pass starts no event");
        assert_eq!(last.snapshot.targets.len(), 1);
        let text = std::fs::read_to_string(&csv).unwrap();
        assert_eq!(
            text.lines().count(),
            1 + runs.len(),
            "header and one row per tick"
        );
        let md = std::fs::read_to_string(&report).unwrap();
        assert!(md.contains("# Watchlist Report: test"), "{md}");
        assert!(md.contains("| price_usd > 0 |"), "{md}");
    }

    #[test]
    fn the_report_has_a_market_section_per_target_with_a_summary_and_a_venue() {
        use scope::market::{BookSource, HealthThresholds, MarketSummary, OrderBook};
        let level = |price, quantity| scope::market::OrderBookLevel { price, quantity };
        let book = OrderBook {
            pair: "USDC/USDT".into(),
            source: BookSource::Exchange,
            bids: vec![level(0.999, 5_000.0)],
            asks: vec![level(1.001, 5_000.0)],
        };
        let summary = MarketSummary::from_order_book(&book, &HealthThresholds::default(), None);
        let mut on_venue = Target::new(TargetKind::Pair, "USDC");
        on_venue.venues = vec!["binance".into()];
        // A summary with no venue to name has no section.
        let no_venue = Target::new(TargetKind::Pair, "DAI");
        let mut w = Watchlist::new("pegs");
        w.targets = vec![on_venue, no_venue];
        let last = Tick {
            snapshot: Snapshot {
                targets: vec![TargetSnapshot::new(
                    "USDC@binance",
                    vec![Cell {
                        label: "a|b".into(),
                        rule: None,
                        value: None,
                        status: RuleStatus::Error("x|y".into()),
                        detail: None,
                    }],
                )],
            },
            summaries: vec![Some(summary.clone()), Some(summary)],
        };
        let md = report_text(&w, &last);
        assert!(md.starts_with("# Watchlist Report: pegs\n\n"), "{md}");
        assert_eq!(md.matches("# Market Health Report:").count(), 1, "{md}");
        let section = md.find("# Market Health Report: USDC").unwrap();
        assert!(section < md.find("## Last values").unwrap(), "{md}");
        assert!(!md.contains("Market Health Report: DAI"), "{md}");
        // A pipe in a label or an error would split the table cell.
        assert!(
            md.contains("| USDC@binance | a\\|b | - | error | x\\|y |"),
            "{md}"
        );
    }

    // Design 2026-11-04, section 2.6: a target on two venues gives a
    // market section and a set of CSV rows per venue.
    #[test]
    fn two_venues_give_two_sections_and_two_labelled_row_sets() {
        use scope::market::{BookSource, HealthThresholds, MarketSummary, OrderBook};
        let level = |price, quantity| scope::market::OrderBookLevel { price, quantity };
        let book = OrderBook {
            pair: "USDN/USDT".into(),
            source: BookSource::Exchange,
            bids: vec![level(0.999, 5_000.0)],
            asks: vec![level(1.001, 5_000.0)],
        };
        let summary = MarketSummary::from_order_book(&book, &HealthThresholds::default(), None);
        let mut t = Target::new(TargetKind::Pair, "USDN");
        t.venues = vec!["weex".into(), "binance".into()];
        t.rules = vec![scope::watch::Rule::parse("spread_pct < 1").unwrap()];
        let mut w = Watchlist::new("pegs");
        w.targets = vec![t];
        let row = |venue: &str| {
            TargetSnapshot::new(
                format!("USDN@{venue}"),
                vec![Cell {
                    label: "spread_pct < 1".into(),
                    rule: scope::watch::Rule::parse("spread_pct < 1").ok(),
                    value: Some(0.2),
                    status: RuleStatus::Pass,
                    detail: None,
                }],
            )
            .on_venue(Some(venue))
        };
        let last = Tick {
            snapshot: Snapshot {
                targets: vec![row("weex"), row("binance")],
            },
            summaries: vec![Some(summary.clone()), Some(summary)],
        };
        let md = report_text(&w, &last);
        assert_eq!(
            md.matches("# Market Health Report: USDN").count(),
            2,
            "{md}"
        );
        assert!(
            md.contains("| USDN@weex |") && md.contains("| USDN@binance |"),
            "{md}"
        );
        let csv = csv_rows("t0", &last.snapshot);
        let targets: Vec<&str> = csv.lines().map(|l| l.split(',').nth(1).unwrap()).collect();
        assert_eq!(targets, ["USDN@weex", "USDN@binance"]);
    }

    #[tokio::test]
    async fn a_report_that_cannot_be_written_is_an_error() {
        let dir = tempfile::tempdir().unwrap();
        let mut w = Watchlist::new("test");
        w.interval = Duration::from_millis(5);
        w.duration = Some(Duration::from_millis(1));
        // A folder cannot be written as a file.
        w.outputs.report = Some(dir.path().to_path_buf());
        let ready = Ready {
            list: w,
            contracts: vec![],
        };
        let factory = MockClientFactory::new();
        let config = scope::config::Config::default();
        let src = Sources {
            config: &config,
            clients: &factory,
        };
        let (out, _cap) = Output::capture();
        let err = run(&ready, src, &out, |_, _, _| {}).await.unwrap_err();
        assert!(err.to_string().contains("cannot write"), "{err}");
    }
}