Skip to main content

scope/
lib.rs

1//! # Scope Blockchain Analysis
2//!
3//! A command-line tool and library for blockchain data analysis,
4//! address book management, and transaction investigation.
5//!
6//! ## Features
7//!
8//! - **Address Analysis**: Query balances (with USD valuation), transaction history,
9//!   and token holdings (ERC-20, SPL, TRC-20) for blockchain addresses across
10//!   multiple chains. Chain auto-detection from address format.
11//!
12//! - **Transaction Analysis**: Look up and decode blockchain transactions across
13//!   EVM chains (via Etherscan proxy API), Solana (via `getTransaction` RPC),
14//!   and Tron (via TronGrid). Includes receipt data, gas usage, and status.
15//!
16//! - **Token Crawling**: Crawl DEX data for any token with price, volume,
17//!   liquidity, holder analysis, and risk scoring. Markdown report generation.
18//!
19//! - **Token Discovery**: Browse trending and boosted tokens from DexScreener
20//!   (`scope discover`) — featured profiles, recent boosts, top boosts. No API key.
21//!
22//! - **Live Monitoring**: Real-time TUI dashboard with price/volume/candlestick
23//!   charts, buy/sell gauges, activity logs, and Unicode-rich visualization.
24//!
25//! - **Address Book**: Track multiple addresses (wallets, contracts) across chains with
26//!   labels, tags, and aggregated balance views including ERC-20, SPL, and
27//!   TRC-20 token balances.
28//!
29//! - **Data Export**: Export transaction history in JSON or CSV with date range
30//!   filtering. Chain auto-detection for addresses.
31//!
32//! - **Market Health**: Peg and order book health for stablecoin markets. Fetches
33//!   level-2 depth from Binance, Biconomy, or DEX liquidity (Ethereum/Solana via DexScreener).
34//!   Configurable health checks (peg safety, bid/ask ratio, depth thresholds).
35//!
36//! - **Token Health Suite**: Composite command (`scope token-health`) combining DEX analytics
37//!   with optional market/order book summary. Venues: binance, biconomy, eth, solana.
38//!
39//! - **Unified Insights**: Auto-detect addresses, transaction hashes, or tokens
40//!   and run the appropriate analyses (`scope insights`).
41//!
42//! - **Compliance & Risk**: Risk scoring, transaction pattern detection, taint
43//!   analysis, and compliance reporting (`scope compliance`).
44//!
45//! - **Shell Completion**: Tab-completion for bash, zsh, and fish
46//!   (`scope completions <shell>`).
47//!
48//! - **Progress Indicators**: Spinners and progress bars for all long-running
49//!   operations. Non-TTY aware (hidden in pipes).
50//!
51//! - **Error Remediation**: Actionable hints for common errors (invalid address,
52//!   missing config, network failures, auth issues).
53//!
54//! - **USD Valuation**: Native token prices via DexScreener for all supported
55//!   chains (ETH, SOL, BNB, MATIC, etc.).
56//!
57//! ## Supported Chains
58//!
59//! ### EVM-Compatible
60//!
61//! - Ethereum Mainnet
62//! - Polygon
63//! - Arbitrum
64//! - Optimism
65//! - Base
66//! - BSC (BNB Smart Chain)
67//!
68//! ### Non-EVM
69//!
70//! - Solana
71//! - Tron
72//!
73//! ## Quick Start (CLI)
74//!
75//! ```bash
76//! # Analyze an address
77//! scope address 0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2
78//!
79//! # Analyze a transaction
80//! scope tx 0xabc123...
81//!
82//! # Auto-detect and analyze any target
83//! scope insights 0xabc123...
84//!
85//! # Token DEX data
86//! scope crawl USDC --chain ethereum
87//!
88//! # Manage address book
89//! scope address-book add 0x742d... --label "Main Wallet"
90//! scope address-book list
91//!
92//! # Export data
93//! scope export --address 0x742d... --output history.json
94//!
95//! # Shell tab-completion
96//! scope completions zsh > ~/.zfunc/_scope
97//! ```
98//!
99//! ## Library Usage
100//!
101//! The Scope library can be used programmatically in your Rust applications:
102//!
103//! ```rust,no_run
104//! use scope::{Config, chains::EthereumClient};
105//!
106//! #[tokio::main]
107//! async fn main() -> scope::Result<()> {
108//!     // Load configuration
109//!     let config = Config::load(None)?;
110//!     
111//!     // Create a chain client
112//!     // Build the HTTP transport once and pass it to every client
113//!     let http = scope::http::build(&config)?.client;
114//!     let client = EthereumClient::new_with_http(&config.chains, http)?;
115//!     
116//!     // Query an address balance (with USD valuation)
117//!     let mut balance = client.get_balance("0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2").await?;
118//!     client.enrich_balance_usd(&mut balance).await;
119//!     println!("Balance: {} (${:.2})", balance.formatted, balance.usd_value.unwrap_or(0.0));
120//!     
121//!     // Look up a transaction
122//!     let tx = client.get_transaction("0xabc123...").await?;
123//!     println!("From: {}, Status: {:?}", tx.from, tx.status);
124//!     
125//!     // Fetch ERC-20 token balances
126//!     let tokens = client.get_erc20_balances("0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2").await?;
127//!     for token in &tokens {
128//!         println!("{}: {}", token.token.symbol, token.formatted_balance);
129//!     }
130//!     
131//!     Ok(())
132//! }
133//! ```
134//!
135//! ## Configuration
136//!
137//! Scope reads configuration from `~/.scope-bca/config.yaml`:
138//!
139//! ```yaml
140//! chains:
141//!   # EVM chains
142//!   ethereum_rpc: "https://mainnet.infura.io/v3/YOUR_KEY"
143//!   bsc_rpc: "https://bsc-dataseed.binance.org"
144//!
145//!   # Non-EVM chains
146//!   solana_rpc: "https://api.mainnet-beta.solana.com"
147//!   tron_api: "https://api.trongrid.io"
148//!
149//!   api_keys:
150//!     etherscan: "YOUR_ETHERSCAN_KEY"
151//!     polygonscan: "YOUR_POLYGONSCAN_KEY"
152//!     bscscan: "YOUR_BSCSCAN_KEY"
153//!     solscan: "YOUR_SOLSCAN_KEY"
154//!     tronscan: "YOUR_TRONSCAN_KEY"
155//!
156//! output:
157//!   format: table  # table, json, csv, markdown
158//!   color: true
159//!
160//! address_book:
161//!   data_dir: "/Users/me/scope-address-book"  # optional; absolute path
162//! ```
163//!
164//! ## Error Handling
165//!
166//! All fallible operations return [`Result<T>`], which uses [`ScopeError`]
167//! as the error type. This provides detailed error context for debugging
168//! and user-friendly error messages.
169//!
170//! ```rust
171//! use scope::{ScopeError, Result};
172//!
173//! fn validate_address(addr: &str) -> Result<()> {
174//!     if !addr.starts_with("0x") || addr.len() != 42 {
175//!         return Err(ScopeError::InvalidAddress(addr.to_string()));
176//!     }
177//!     Ok(())
178//! }
179//! ```
180//!
181//! ## Modules
182//!
183//! - [`chains`]: Blockchain client implementations (Ethereum/EVM, Solana, Tron, DexScreener)
184//! - [`config`]: Configuration management
185//! - [`market`]: Peg and order book health for stablecoin markets
186//! - [`display`]: Terminal output utilities and markdown report generation
187//! - [`error`]: Error types and result aliases
188//! - [`tokens`]: Token alias storage for friendly name lookups
189//! - [`domain`]: Shared domain logic (address book, resolution)
190
191// Re-export commonly used types at crate root
192pub use config::Config;
193pub use error::{ConfigError, Result, ScopeError};
194
195/// Blockchain client implementations.
196///
197/// Provides abstractions and concrete clients for interacting with
198/// blockchain networks. See `ChainClient` for the common
199/// interface and `EthereumClient` for EVM chain support.
200pub mod chains;
201
202/// Shared domain logic used by both CLI and web delivery mechanisms.
203///
204/// Contains core data types and business logic (e.g. address book
205/// storage, label resolution) that are independent of any particular
206/// delivery mechanism.
207pub mod domain;
208
209/// Configuration management.
210///
211/// Handles loading, merging, and validation of configuration from
212/// multiple sources (CLI args, environment variables, config files).
213pub mod config;
214
215/// Display utilities for terminal output and reports.
216///
217/// Provides ASCII chart rendering and markdown report generation
218/// for token analytics data.
219pub mod display;
220
221/// Diagnostics sink for library warnings.
222///
223/// Routes warnings to stderr, or to a TUI pane while a redirect is active.
224pub mod diag;
225
226/// Error types and result aliases.
227///
228/// Defines [`ScopeError`] for all error conditions and provides a
229/// convenient [`Result`] type alias.
230pub mod error;
231
232/// Token alias storage for saving token lookups.
233///
234/// Allows users to reference tokens by friendly names instead
235/// of full contract addresses.
236pub mod tokens;
237
238/// Compliance and risk analysis module.
239///
240/// Provides risk scoring, transaction taint analysis, pattern detection,
241/// and compliance reporting for blockchain addresses.
242pub mod compliance;
243
244/// Smart contract analysis module.
245///
246/// Provides contract source retrieval, ABI decoding, proxy detection,
247/// access control mapping, vulnerability scanning, DeFi protocol checks,
248/// and external intelligence (GitHub linking, audit reports).
249pub mod contract;
250
251/// HTTP transport abstraction.
252///
253/// Provides a trait-based abstraction over HTTP clients, enabling
254/// transparent switching between direct `reqwest` calls and the
255/// Ghola sidecar proxy for stealth analysis.
256pub mod http;
257
258/// Market module for peg and order book health analysis.
259///
260/// Fetches level-2 order book data from exchange APIs and runs
261/// configurable health checks for stablecoin markets.
262pub mod market;
263
264// The metric catalog: market, token and address key values. The module's
265// own docs link to its items, so it has no outer doc here.
266pub mod metrics;
267
268/// The user's directories, resolved in one place (sandboxed in tests).
269pub mod paths;
270
271// Watchlists: targets, rules and their evaluation (#47). Docs as above.
272pub mod watch;
273
274/// Library version string.
275pub const VERSION: &str = env!("CARGO_PKG_VERSION");
276
277/// Returns the library version.
278///
279/// # Examples
280///
281/// ```rust
282/// let version = scope::version();
283/// println!("Scope version: {}", version);
284/// ```
285pub fn version() -> &'static str {
286    VERSION
287}
288
289// ============================================================================
290// Integration Tests for Library API
291// ============================================================================
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    #[test]
298    fn test_version_not_empty() {
299        assert!(!version().is_empty());
300    }
301
302    #[test]
303    fn test_version_format() {
304        // Version should be semver-like (X.Y.Z)
305        let v = version();
306        let parts: Vec<&str> = v.split('.').collect();
307        assert!(parts.len() >= 2, "Version should have at least major.minor");
308    }
309
310    #[test]
311    fn test_config_reexport() {
312        // Verify Config is accessible from crate root
313        let config = Config::default();
314        assert!(config.chains.api_keys.is_empty());
315    }
316
317    #[test]
318    fn test_error_reexport() {
319        // Verify error types are accessible from crate root
320        let err = ScopeError::InvalidAddress("test".to_string());
321        assert!(err.to_string().contains("test"));
322    }
323
324    #[test]
325    fn test_result_type_alias() {
326        fn test_fn() -> Result<i32> {
327            Ok(42)
328        }
329        assert_eq!(test_fn().unwrap(), 42);
330    }
331
332    #[test]
333    fn test_config_error_reexport() {
334        use std::path::PathBuf;
335        let err = ConfigError::NotFound {
336            path: PathBuf::from("/test"),
337        };
338        assert!(err.to_string().contains("/test"));
339    }
340}