摘要
本系统是一款面向 EVM 兼容链(Ethereum、BSC、Base、Polygon、Arbitrum)与 Solana 链的实时资产监控与智能分析平台。通过 WebSocket 长连接与 RPC 轮询混合架构,实现对指定钱包地址的原生币、代币、NFT 的全方位监控,并集成 Telegram、Discord、邮件、语音播报等多渠道推送。系统内置多 AI 提供商(DeepSeek、Moonshot)的智能解读能力,可对每笔交易进行风险评分、资金流向分析与投资建议。此外还提供链上项目追踪(CryptoRank、GeckoTerminal)、新项目发现(RootData 数据集成)、Web3 AI 聊天助手、交易仪表盘、悬浮窗实时通知等高级功能。本文将从系统架构、核心模块、关键技术实现、性能优化、安全体系等维度进行全面深度剖析,揭示企业级区块链监控系统的工程实践。
1. 系统总体架构
主进程 (main.py)
- PyWebView 窗口 (HTML/JS 前端)
- 系统托盘图标 + 悬浮窗管理
- 子进程生命周期管理 (启动/停止/重启)
- 配置文件读写 (JSON) 与热加载
▼
Evm.py
- EVM WSS 订阅 (多节点轮换)
- RPC 余额轮询 (原生币)
- NFTScan 集成 (元数据)
- SQLite 持久化 (唯一约束去重)
Sol.py
- Solana WSS 订阅 (logsSubscribe)
- Helius DAS API 解析
- SPL 代币元数据与价格缓存
- 详细日志 JSON 归档 (异步队列)
设计要点:单实例互斥 (Windows全局互斥体) · UTF-8全链路 · 代理透明 (HTTP/Socks) · 异步非阻塞 I/O
2. 核心功能模块
🔷 EVM 链监控
原生币 RPC 轮询(60s),代币/NFT 通过 WSS 订阅 logs,支持 ERC20/721/1155 事件解析。自动获取代币 symbol/decimals,集成 NFTScan 元数据增强。
☀️ Solana 链监控
logsSubscribe 实时捕获签名,通过 Helius DAS API 解析 nativeTransfers、tokenTransfers、NFT 事件。支持 SPL 代币价格与元数据查询。
🧠 AI 智能解读
MultiAIClient 支持 DeepSeek/Moonshot 轮换,自动分析交易意图、风险评分、生成投资建议与幽默评语。日报/周报定时推送。
📡 多渠道推送
Telegram、Discord、Email、语音播报,大额交易特殊标记。桌面悬浮窗实时滚动通知,支持通知导出。
📊 链上数据聚合
CryptoRank 项目列表、GeckoTerminal 新交易对雷达、RootData 新项目监控(官方 API + 公开数据解析)。
⚙️ 可视化配置
前端在线编辑 JSON 配置,保存后自动重启子进程。代理配置、节点轮换、阈值调整无需重启主程序。
3. EVM 深度技术实现
3.1 事件日志解析的完整处理
通过 topic0 精确区分事件类型:0xddf252ad... (ERC20 Transfer)、0xc3d58168... (ERC1155 TransferSingle)、0x4a39dc06... (ERC1155 TransferBatch)。对于 ERC1155 批量转账,需要从 data 字段中按 ABI 编码解析出 tokenId 和 value 数组,并分别处理每个元素。系统实现了完整的动态数组解析逻辑,确保不会遗漏任何子转账。
3.2 原生币监控的混合模式
由于 EVM 原生币转账没有标准事件,系统采用 RPC 轮询 + 余额快照对比 的方式:每隔 60 秒调用 eth_getBalance 获取当前余额,与上次快照比较,差值超过极小阈值(1e-18)则触发通知。此方式无法捕获轮询间隔内的多次小额转账,但针对大额资产变动(用户主要关注点)已足够。未来可结合区块头时间戳优化轮询频率。
3.3 代币信息与价格的多级缓存策略
代币 symbol 和 decimals 通过 eth_call 调用合约的 symbol() 和 decimals() 方法获取,失败时回退为“未知代币”。价格源优先级:Binance(主流币)→ DexScreener(长尾代币)→ 本地缓存(5分钟有效期)。所有缓存使用 LimitedSizeDict 限制大小(token 1000 条、价格 500 条),防止内存无限增长。
3.4 WSS 连接的高可用架构
每条链可配置多个 WSS 节点,当前节点异常时自动切换至下一个,并记录日志。重连采用指数退避策略(5s → 60s),避免频繁重试对节点造成压力。通过 websockets_proxy 库实现 WSS over HTTP 代理,解决国内网络直连困难。
3.5 交易去重的可靠机制
数据库表 tx_history 设置 UNIQUE(tx_hash, log_index, address) 约束,天然防止重复插入。原生币变动没有 log_index,使用 tx_hash + address 作为组合键,但仍可能因链重组产生重复,系统暂时依赖数据库约束过滤,未来可增加区块高度校验实现回滚处理。
3.6 链重组(Reorg)的应对策略
当前版本未实现主动回滚,但通过数据库唯一约束保证了不会重复存储。未来可监听 newHeads 检测链高度变化,结合区块哈希校验实现交易状态修正。该设计已在架构中预留扩展点。
4. Solana 深度技术实现
4.1 Helius DAS API 的全面解析
通过 POST /v0/transactions 批量获取签名对应的完整交易数据,包含 nativeTransfers、tokenTransfers、events.nft、accountData。当 nativeTransfers 不存在时,降级使用 preBalances 和 postBalances 计算余额差值,并反推对方地址。
4.2 SPL 代币信息获取
使用 Helius getAsset 方法查询 mint 地址,返回 token_info.symbol 和 token_info.price_info.price_per_token。缓存策略将 symbol 和 price 分离,有效期 5 分钟。若 Helius 无价格,则调用 DexScreener API(/tokens/{mint})作为回退。
4.3 NFT 元数据的深度获取
结合链上 onChainMetadata(名称)和链下 offChainMetadata(图片 URL)获得完整 NFT 信息。为避免阻塞主解析,NFT 元数据请求在后台异步完成,不影响推送速度。
4.4 WSS 订阅与交易解析的解耦
使用 logsSubscribe 订阅 mentions 过滤器,实时获取涉及监控地址的交易签名。收到签名后,通过 Helius HTTP API 异步获取详情,避免 WSS 线程阻塞。去重集合 processed_sigs 使用 set 存储最近 1000 个签名,自动淘汰旧数据。
4.5 Solana 特有的交易类型解析
支持识别 NFT 销售事件(从 events.nft 提取 seller、buyer、mint、price),以及代币授权转账(通过 tokenTransfers 中的 authority 字段)。
4.6 文件日志的异步队列写入
每日生成 detailed_transactions_{date}.json 归档完整交易记录。使用 asyncio.Queue 串行化写入,避免多个协程同时写文件导致数据错乱。每个 JSON 文件最多保留 1000 条记录,超出则截断。
5. 通用技术难点与突破
子进程日志的实时捕获与转发
- 主进程通过
subprocess.PIPE 读取子进程 stdout,使用独立线程 _forward_output 逐行读取。
- 使用正则
\x1B\[[0-?]*[ -/]*[@-~] 移除 ANSI 颜色控制码,保证前端纯文本显示。
- 通过
window.evaluate_js 调用前端日志函数,实现实时显示。
AI 多提供商轮换与容错
- 特征开关机制:根据配置文件中的
features 字段,仅调用支持该功能的提供商。
- JSON 修复:对 LLM 返回的非标准 JSON(如缺少引号、多余换行)进行正则提取,确保解读不丢失。
- 超时控制:为每个 AI 请求设置独立超时(15 秒),超时则跳过该提供商。
配置热加载与子进程重启
- 前端编辑配置后调用
save_evm_config,后端保存文件后自动执行 evm_stop() → evm_start()。
- 重启前检查子进程是否正在运行,若运行则先停止,再启动新进程,确保配置立即生效。
悬浮窗实时推送与通知导出
- 主窗口和悬浮窗共享同一个
js_api 实例,通过 evaluate_js 互相调用。
- 悬浮窗内部维护
notifications 数组,支持用户导出为 JSON 文件。
单实例互斥锁与进程残留清理
- 使用
win32event.CreateMutex 创建全局互斥,防止多开。
- 强制清理:
quit_app() 中调用 taskkill 确保子进程被彻底终止,避免残留进程占用互斥锁。
代理配置的动态生效
- 修改代理配置后,立即更新
os.environ['HTTP_PROXY'] 并重启子进程,新代理无需重启主程序。
- EVM 和 Solana 均通过
websockets_proxy 库实现代理连接。
6. 性能优化与稳定性保障
内存控制
LimitedSizeDict 限制 token/price/NFT 缓存大小;processed_logs 定期截断;Solana 签名集合自动淘汰。
异步写入
文件写入使用 asyncio.Queue + 专用协程,避免阻塞事件循环;数据库短连接 + WAL 模式。
日志轮转
TimedRotatingFileHandler 每日午夜轮转,自动删除过期日志;Solana 详细日志按日期 JSON 归档。
WSS 心跳
设置 ping_interval=10 保持连接活跃,防止被服务端断开。
节点健康检查
自动检测 WSS 节点响应超时,失败后立即切换至备用节点,并记录故障日志。
前端渲染优化
日志区域仅保留最近 500 条,超出自动滚动截断,避免 DOM 节点过多导致卡顿。
7. 安全与隐私
所有监控数据(交易记录、余额快照)仅存储于本地 SQLite 数据库,不上传任何服务器。激活机制基于机器码(硬盘序列号+主板UUID)的 HMAC 签名验证,激活信息加密存储于 %APPDATA%。子进程与主进程隔离,单实例互斥防止重复运行。前端界面支持禁用在线编辑功能(已加固),用户可完全控制数据流向。
8. 部署与运维
使用 PyInstaller 打包为单个 EXE,内置 Python 运行时。配置文件外置于 EXE 同级目录,用户可随时修改。日志按天轮转(EVM),Solana 详细日志按日期 JSON 归档。子进程异常退出时,用户可通过 UI 手动重启,不影响其他链监控。支持代理可视化配置,无需用户手动修改环境变量。
9. 未来演进方向
增加 Aptos、Sui 等非 EVM 链;接入 GPT-4o 实现多模态解读(交易截图识别);云端协同降低本地资源占用;移动端适配(WebSocket 推送);链上事件实时预警系统(基于 ML 的异常检测)。
10. 总结
本系统是一个工程化程度高、功能全面、技术深度扎实的 Web3 桌面应用。它不仅实现了多链、多资产、多渠道的实时监控,更通过 AI 赋能、链上数据聚合、配置热更新等特性,为用户提供了超越传统区块浏览器的智能体验。系统的架构设计充分考虑了稳定性、可扩展性与易用性,是个人开发者独立完成的高质量商业级作品。本文从底层事件解析、高可用 WSS、去重机制、AI 容错、性能优化等角度详细阐述了实现细节,希望能为 Web3 开发者提供有价值的参考。
技术关键词:异步 I/O、WebSocket 长连接、多链异构解析、AI 多提供商轮换、缓存策略、进程隔离、热配置、数据持久化、多渠道推送、链重组应对。
Abstract
This system is a real‑time asset monitoring and intelligent analysis platform for EVM‑compatible chains (Ethereum, BSC, Base, Polygon, Arbitrum) and Solana. It uses a hybrid WebSocket + RPC polling architecture to track native coins, tokens, and NFTs for specified wallet addresses, and integrates multi‑channel push (Telegram, Discord, Email, voice). Built‑in multi‑AI provider (DeepSeek, Moonshot) delivers transaction insights, risk scoring, and investment suggestions. Additional features include on‑chain project tracking (CryptoRank, GeckoTerminal), new project discovery (RootData integration), Web3 AI chat assistant, dashboard, and floating widget. This report provides a comprehensive technical analysis covering system architecture, core modules, key implementations, performance optimizations, and security.
1. System Architecture
Main Process (main.py)
- PyWebView Window (HTML/JS Frontend)
- System Tray + Floating Widget
- Child Process Lifecycle (Start/Stop/Restart)
- JSON Config Read/Write & Hot‑loading
▼
Evm.py
- EVM WSS Subscription (multi‑node rotation)
- RPC Balance Polling (native coins)
- NFTScan Integration (metadata)
- SQLite Persistence (unique constraint dedup)
Sol.py
- Solana WSS Subscription (logsSubscribe)
- Helius DAS API Parsing
- SPL Token Metadata & Price Cache
- Detailed JSON Log Archiving (async queue)
Design Highlights: Single Instance Mutex · UTF-8 Full Chain · Proxy Transparent (HTTP/Socks) · Async Non‑blocking I/O
2. Core Modules
🔷 EVM Monitoring
Native coin RPC polling (60s), token/NFT via WSS logs (ERC20/721/1155). Auto‑fetch symbol/decimals, NFTScan metadata.
☀️ Solana Monitoring
logsSubscribe for signatures, Helius DAS API parsing nativeTransfers, tokenTransfers, NFT events. SPL token price & metadata.
🧠 AI Insights
MultiAIClient (DeepSeek/Moonshot) for transaction analysis, risk scoring, suggestions, daily/weekly reports.
📡 Multi‑Channel Push
Telegram, Discord, Email, voice, floating widget. Large transactions highlighted.
📊 On‑Chain Data
CryptoRank projects, GeckoTerminal new pairs, RootData new projects (official API + public data).
⚙️ Visual Config
Edit JSON configs from frontend, auto‑restart child processes. Proxy, node rotation, thresholds adjustable without restarting main program.
3. EVM Deep Dive
3.1 Complete Event Log Parsing
Event types are distinguished by topic0: 0xddf252ad... (ERC20 Transfer), 0xc3d58168... (ERC1155 TransferSingle), 0x4a39dc06... (ERC1155 TransferBatch). For ERC1155 batch transfers, the data field is ABI‑decoded to extract tokenId and value arrays, handling each element individually.
3.2 Hybrid Native Coin Monitoring
Native coin transfers have no standard event, so the system uses RPC polling + balance snapshot comparison: calls eth_getBalance every 60 seconds, compares with previous snapshot, triggers notification on difference >1e-18.
3.3 Multi‑Level Token Info & Price Caching
Token symbol and decimals fetched via eth_call to symbol() and decimals(), fallback to "Unknown". Price priority: Binance → DexScreener → cache (5 min TTL). All caches use LimitedSizeDict to bound memory.
3.4 High‑Availability WSS
Multiple WSS nodes per chain, automatic failover, exponential backoff (5s→60s). Proxy support via websockets_proxy.
3.5 Reliable Deduplication
Database table tx_history enforces UNIQUE(tx_hash, log_index, address). Native coin changes use tx_hash + address as key. Future improvement: block hash validation for reorg handling.
3.6 Reorg Handling Strategy
Current version does not implement rollback, but deduplication prevents duplicate storage. Future: listen to newHeads to detect chain height changes and validate block hashes.
4. Solana Deep Dive
4.1 Helius DAS API Parsing
Uses POST /v0/transactions to fetch full transaction details including nativeTransfers, tokenTransfers, events.nft, accountData. Falls back to balance difference calculation when nativeTransfers missing.
4.2 SPL Token Information
Helius getAsset returns token_info.symbol and price_info.price_per_token. Caches separated for symbol and price (5 min TTL). Fallback to DexScreener API if Helius price unavailable.
4.3 NFT Metadata Retrieval
Combines on‑chain metadata (name) and off‑chain metadata (image URL) via Helius. Fetched asynchronously to avoid blocking main parsing.
4.4 Decoupled WSS Subscription & Parsing
Uses logsSubscribe with mentions filter to receive transaction signatures. Details are fetched via Helius HTTP API asynchronously, preventing WSS thread blocking. Deduplication set processed_sigs stores last 1000 signatures.
4.5 Solana‑Specific Transaction Types
Supports NFT sale events (extracts seller, buyer, mint, price from events.nft) and token delegated transfers (via authority field in tokenTransfers).
4.6 Asynchronous File Logging Queue
Daily JSON archives detailed_transactions_{date}.json. Uses asyncio.Queue to serialise writes, avoiding corruption. Each file retains max 1000 entries.
5. General Technical Challenges & Solutions
Real‑time Child Process Log Forwarding
- Main process reads stdout via
subprocess.PIPE with dedicated thread _forward_output.
- ANSI escape codes removed by regex to ensure clean frontend display.
- Logs injected into frontend via
window.evaluate_js.
AI Provider Rotation & Fault Tolerance
- Feature‑based provider selection: only providers supporting required features are called.
- JSON repair: regex extraction of insight/risk/suggestion from malformed LLM responses.
- Timeout per request (15s) – skip provider on timeout.
Hot‑Config & Child Process Restart
- Frontend calls
save_evm_config → backend saves file → auto restart child process.
- Checks if child is running before restart to ensure smooth transition.
Floating Widget & Notification Export
- Main window and floating widget share same
js_api instance; communicate via evaluate_js.
- Widget maintains
notifications array for JSON export.
Single Instance Mutex & Process Cleanup
- Global mutex via
win32event.CreateMutex prevents multiple instances.
quit_app() calls taskkill to ensure child processes are terminated, avoiding mutex lock leftovers.
Dynamic Proxy Activation
- Proxy config change updates
os.environ['HTTP_PROXY'] and restarts child processes without restarting main program.
- Both EVM and Solana support proxy via
websockets_proxy.
6. Performance & Stability
Memory Control
LimitedSizeDict for token/price/NFT caches; periodic truncation of processed_logs; auto‑eviction of Solana signature set.
Async Writes
File writes via asyncio.Queue + dedicated coroutine; SQLite short connections + WAL.
Log Rotation
TimedRotatingFileHandler daily rotation; Solana detailed logs archived by date.
WSS Heartbeat
ping_interval=10 keeps connection alive.
Node Health Check
Automatic detection of timeout/failure, immediate switch to backup node with logging.
Frontend Rendering
Log area retains last 500 entries, auto‑truncation to avoid DOM overload.
7. Security & Privacy
All monitoring data stored locally in SQLite, never uploaded. Activation uses HMAC signature based on machine code (disk serial + motherboard UUID), license encrypted in %APPDATA%. Child processes isolated, single instance mutex. Frontend editing can be disabled to prevent tampering.
8. Deployment & Operations
Packaged as single EXE with PyInstaller, embedded Python runtime. Config files external, editable. Log rotation (EVM daily), Solana detailed JSON archives. Child process crashes can be manually restarted via UI without affecting other chains. Proxy configurable via visual interface.
9. Future Roadmap
Add Aptos, Sui; integrate GPT‑4o for multimodal insights; cloud coordination to reduce local resource usage; mobile adaptation via WebSocket push; ML‑based anomaly detection for on‑chain events.
10. Conclusion
This system is a highly engineered, feature‑rich, technically deep Web3 desktop application. It provides real‑time monitoring across multiple chains and assets, AI‑powered analysis, on‑chain data aggregation, and hot‑configurable UX – surpassing traditional block explorers. The architecture emphasizes stability, scalability, and ease of use, representing a commercial‑grade work by an independent developer. This deep dive covers event parsing, high‑availability WSS, deduplication, AI fault tolerance, and performance optimizations, offering valuable insights for Web3 developers.
Keywords: Async I/O, WebSocket long‑polling, multi‑chain heterogeneous parsing, multi‑AI provider rotation, caching strategies, process isolation, hot‑reload, data persistence, multi‑channel push, reorg handling.