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
//! # Scope Blockchain Analysis
//!
//! A command-line tool and library for blockchain data analysis,
//! address book management, and transaction investigation.
//!
//! ## Features
//!
//! - **Address Analysis**: Query balances (with USD valuation), transaction history,
//! and token holdings (ERC-20, SPL, TRC-20) for blockchain addresses across
//! multiple chains. Chain auto-detection from address format.
//!
//! - **Transaction Analysis**: Look up and decode blockchain transactions across
//! EVM chains (via Etherscan proxy API), Solana (via `getTransaction` RPC),
//! and Tron (via TronGrid). Includes receipt data, gas usage, and status.
//!
//! - **Token Crawling**: Crawl DEX data for any token with price, volume,
//! liquidity, holder analysis, and risk scoring. Markdown report generation.
//!
//! - **Token Discovery**: Browse trending and boosted tokens from DexScreener
//! (`scope discover`) — featured profiles, recent boosts, top boosts. No API key.
//!
//! - **Live Monitoring**: Real-time TUI dashboard with price/volume/candlestick
//! charts, buy/sell gauges, activity logs, and Unicode-rich visualization.
//!
//! - **Address Book**: Track multiple addresses (wallets, contracts) across chains with
//! labels, tags, and aggregated balance views including ERC-20, SPL, and
//! TRC-20 token balances.
//!
//! - **Data Export**: Export transaction history in JSON or CSV with date range
//! filtering. Chain auto-detection for addresses.
//!
//! - **Market Health**: Peg and order book health for stablecoin markets. Fetches
//! level-2 depth from Binance, Biconomy, or DEX liquidity (Ethereum/Solana via DexScreener).
//! Configurable health checks (peg safety, bid/ask ratio, depth thresholds).
//!
//! - **Token Health Suite**: Composite command (`scope token-health`) combining DEX analytics
//! with optional market/order book summary. Venues: binance, biconomy, eth, solana.
//!
//! - **Unified Insights**: Auto-detect addresses, transaction hashes, or tokens
//! and run the appropriate analyses (`scope insights`).
//!
//! - **Compliance & Risk**: Risk scoring, transaction pattern detection, taint
//! analysis, and compliance reporting (`scope compliance`).
//!
//! - **Shell Completion**: Tab-completion for bash, zsh, and fish
//! (`scope completions <shell>`).
//!
//! - **Progress Indicators**: Spinners and progress bars for all long-running
//! operations. Non-TTY aware (hidden in pipes).
//!
//! - **Error Remediation**: Actionable hints for common errors (invalid address,
//! missing config, network failures, auth issues).
//!
//! - **USD Valuation**: Native token prices via DexScreener for all supported
//! chains (ETH, SOL, BNB, MATIC, etc.).
//!
//! ## Supported Chains
//!
//! ### EVM-Compatible
//!
//! - Ethereum Mainnet
//! - Polygon
//! - Arbitrum
//! - Optimism
//! - Base
//! - BSC (BNB Smart Chain)
//!
//! ### Non-EVM
//!
//! - Solana
//! - Tron
//!
//! ## Quick Start (CLI)
//!
//! ```bash
//! # Analyze an address
//! scope address 0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2
//!
//! # Analyze a transaction
//! scope tx 0xabc123...
//!
//! # Auto-detect and analyze any target
//! scope insights 0xabc123...
//!
//! # Token DEX data
//! scope crawl USDC --chain ethereum
//!
//! # Manage address book
//! scope address-book add 0x742d... --label "Main Wallet"
//! scope address-book list
//!
//! # Export data
//! scope export --address 0x742d... --output history.json
//!
//! # Shell tab-completion
//! scope completions zsh > ~/.zfunc/_scope
//! ```
//!
//! ## Library Usage
//!
//! The Scope library can be used programmatically in your Rust applications:
//!
//! ```rust,no_run
//! use scope::{Config, chains::EthereumClient};
//!
//! #[tokio::main]
//! async fn main() -> scope::Result<()> {
//! // Load configuration
//! let config = Config::load(None)?;
//!
//! // Create a chain client
//! let client = EthereumClient::new(&config.chains)?;
//!
//! // Query an address balance (with USD valuation)
//! let mut balance = client.get_balance("0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2").await?;
//! client.enrich_balance_usd(&mut balance).await;
//! println!("Balance: {} (${:.2})", balance.formatted, balance.usd_value.unwrap_or(0.0));
//!
//! // Look up a transaction
//! let tx = client.get_transaction("0xabc123...").await?;
//! println!("From: {}, Status: {:?}", tx.from, tx.status);
//!
//! // Fetch ERC-20 token balances
//! let tokens = client.get_erc20_balances("0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2").await?;
//! for token in &tokens {
//! println!("{}: {}", token.token.symbol, token.formatted_balance);
//! }
//!
//! Ok(())
//! }
//! ```
//!
//! ## Configuration
//!
//! Scope reads configuration from `~/.config/scope/config.yaml`:
//!
//! ```yaml
//! chains:
//! # EVM chains
//! ethereum_rpc: "https://mainnet.infura.io/v3/YOUR_KEY"
//! bsc_rpc: "https://bsc-dataseed.binance.org"
//!
//! # Non-EVM chains
//! solana_rpc: "https://api.mainnet-beta.solana.com"
//! tron_api: "https://api.trongrid.io"
//!
//! api_keys:
//! etherscan: "YOUR_ETHERSCAN_KEY"
//! polygonscan: "YOUR_POLYGONSCAN_KEY"
//! bscscan: "YOUR_BSCSCAN_KEY"
//! solscan: "YOUR_SOLSCAN_KEY"
//! tronscan: "YOUR_TRONSCAN_KEY"
//!
//! output:
//! format: table # table, json, csv, markdown
//! color: true
//!
//! address_book:
//! data_dir: "~/.local/share/scope"
//! ```
//!
//! ## Error Handling
//!
//! All fallible operations return [`Result<T>`], which uses [`ScopeError`]
//! as the error type. This provides detailed error context for debugging
//! and user-friendly error messages.
//!
//! ```rust
//! use scope::{ScopeError, Result};
//!
//! fn validate_address(addr: &str) -> Result<()> {
//! if !addr.starts_with("0x") || addr.len() != 42 {
//! return Err(ScopeError::InvalidAddress(addr.to_string()));
//! }
//! Ok(())
//! }
//! ```
//!
//! ## Modules
//!
//! - [`chains`]: Blockchain client implementations (Ethereum/EVM, Solana, Tron, DexScreener)
//! - [`config`]: Configuration management
//! - [`market`]: Peg and order book health for stablecoin markets
//! - [`display`]: Terminal output utilities and markdown report generation
//! - [`error`]: Error types and result aliases
//! - [`tokens`]: Token alias storage for friendly name lookups
//! - [`domain`]: Shared domain logic (address book, resolution)
// Re-export commonly used types at crate root
pub use Config;
pub use ;
/// Blockchain client implementations.
///
/// Provides abstractions and concrete clients for interacting with
/// blockchain networks. See `ChainClient` for the common
/// interface and `EthereumClient` for EVM chain support.
/// Shared domain logic used by both CLI and web delivery mechanisms.
///
/// Contains core data types and business logic (e.g. address book
/// storage, label resolution) that are independent of any particular
/// delivery mechanism.
/// Configuration management.
///
/// Handles loading, merging, and validation of configuration from
/// multiple sources (CLI args, environment variables, config files).
/// Display utilities for terminal output and reports.
///
/// Provides ASCII chart rendering and markdown report generation
/// for token analytics data.
/// Diagnostics sink for library warnings.
///
/// Routes warnings to stderr, or to a TUI pane while a redirect is active.
/// Error types and result aliases.
///
/// Defines [`ScopeError`] for all error conditions and provides a
/// convenient [`Result`] type alias.
/// Token alias storage for saving token lookups.
///
/// Allows users to reference tokens by friendly names instead
/// of full contract addresses.
/// Compliance and risk analysis module.
///
/// Provides risk scoring, transaction taint analysis, pattern detection,
/// and compliance reporting for blockchain addresses.
/// Smart contract analysis module.
///
/// Provides contract source retrieval, ABI decoding, proxy detection,
/// access control mapping, vulnerability scanning, DeFi protocol checks,
/// and external intelligence (GitHub linking, audit reports).
/// HTTP transport abstraction.
///
/// Provides a trait-based abstraction over HTTP clients, enabling
/// transparent switching between direct `reqwest` calls and the
/// Ghola sidecar proxy for stealth analysis.
/// Market module for peg and order book health analysis.
///
/// Fetches level-2 order book data from exchange APIs and runs
/// configurable health checks for stablecoin markets.
/// The user's directories, resolved in one place (sandboxed in tests).
/// Library version string.
pub const VERSION: &str = env!;
/// Returns the library version.
///
/// # Examples
///
/// ```rust
/// let version = scope::version();
/// println!("Scope version: {}", version);
/// ```
// ============================================================================
// Integration Tests for Library API
// ============================================================================