Swordsman

4.6K posts

Swordsman banner
Swordsman

Swordsman

@swordsmanwork

Hongkong Katılım Kasım 2021
2.4K Takip Edilen2.2K Takipçiler
Swordsman retweetledi
Powerpei🦅
Powerpei🦅@PWenzhen76938·
我花了一个半月,从零做了一个Web3监控软件 开头先说结论 我是一个独立开发者(虽然不是很高级那种)。我花了一个半月时间,从零开始做了一套Web3 资产监控软件,名字叫“powerpei Web3 哨兵”。 这个软件能监控EVM链和Solana链 它集成了AI交易解读、多渠道推送、链上数据聚合等功能。 我特别喜欢的功能:它可以监控ETH和SOL链上的土狗项目,还能追踪聪明钱包的动向 这个功能让我能实时捕捉到链上的早期机会。 软件已经稳定运行了好1个月 我之前写过一篇技术概述 但是我总觉得那篇文章对核心实现的讲解还不够深入 所以我决定写这篇深度复盘。我会从进程架构、I/O模型、数据一致性、AI工程化等角度,毫无保留地分享那些藏在代码深处的设计决策和实现细节。 我希望这篇文章能帮到那些也在 Web3领域探索的开发者。 --- 一、进程架构:我为什么选择“主进程 + 多子进程”? 市面上很多Python监控脚本都是单进程asyncio一把梭 但是我在设计之初就选了“主进程(GUI)+ 独立子进程(EVM/SOL)”的架构 ➤ 隔离性和稳定性最重要 WebSocket长连接在网络波动时很容易触发异常重连。甚至底层库的C扩展可能因为未知原因崩溃。 如果你把GUI和监控逻辑混在一个进程里,任何未捕获的异常或内存访问违规都可能导致整个桌面应用闪退。 我通过 `subprocess.Popen` 把EVM和Solana监控逻辑独立成子进程 这样做有两个好处: 物理级隔离:`Evm.py` 崩溃或被强制Kill,主窗口依然正常运行。托盘图标不会消失,用户可以点击“启动”重新拉起来。 日志透传:主进程通过管道捕获子进程的stdout 我用 `_forward_output` 线程逐行读取、清洗ANSI 颜色码 然后通过 `window.evaluate_js` 注入前端DOM。这样就实现了日志实时刷新,而且UI线程还保持轻量。 ➤生命周期管理的细节 在 `core_process.py` 中,停止子进程不是简单的 `terminate()`。我实现了一套强杀兜底机制: ```python proc.terminate() proc.wait(timeout=3) if proc.poll() is None: proc.kill() proc.wait(timeout=2) if proc.poll() is None: os.system(f'taskkill /F /PID {proc.pid}') ``` 这套组合拳确保了即使Python解释器卡死,Windows底层也能彻底清理进程树 这样就避免了残留进程占用端口或数据库锁,导致下次启动失败。 --- 二、I/O 模型和高可用连接:不止是asyncio ➢ 混合监控模式:WSS实时 + RPC补偿 EVM链的原生币没有标准的Transfer事件日志 你无法通过WSS订阅。 我设计了一个轮询补偿器 它每60秒通过RPC获取 `eth_getBalance`,然后和内存快照对比。差值超过 1e-18就触发推送。 这个机制看起来很简单 但是它其实是WSS订阅失活时的最后一道防线。 对于代币和NFT,系统订阅 `logs`。我精细处理了 ERC1155 的 `TransferSingle` 和 `TransferBatch` 事件 特别是 `TransferBatch`,它的 `data` 字段包含动态数组。我实现了基于 ABI 规范的手动偏移量解析,而不是依赖重型库 这极大降低了解析开销。 ➢ WSS的指数退避和节点热切换 在生产环境中,公共 RPC/WSS节点随时可能限流或宕机。 我在 `chain_wss_monitor_direction` 中实现了节点轮换和重连策略: →节点池:配置文件中为每条链配置多个 `WSS_NODES` 启动时随机或顺序选择一个。 →退避算法:连接断开后,重试间隔从5秒开始,每次翻倍直到60秒 这样就避免了在节点恢复前造成DDoS式的重连风暴。 →国内网络环境适配:系统支持配置本地代理软件的 HTTP 地址 通过 `websockets_proxy` 库把WSS流量转发到代理,恢复和境外节点的稳定通信。 ➢Solana的异步解析流水线 Solana的出块速度极快,而且交易结构复杂 为了避免Helius API调用阻塞WSS消息接收,我设计了一个生产者-消费者解耦模型: →生产者:WSS `logsSubscribe` 收到签名后,立即把它扔进 `asyncio.Queue` 或直接触发一个后台 `asyncio.create_task` →消费者:独立的异步任务负责调用 Helius `/v0/transactions` 接口,解析 `nativeTransfers`、`tokenTransfers`、`events.nft` 等字段。 这保证了WSS连接的 `recv()` 循环永远不会被慢速HTTP 请求卡住 这确保了超高TPS环境下消息的实时性。 --- 三、数据一致性:从内存去重到SQLite约束 ➤ EVM 侧:数据库唯一索引 EVM监控中,同一笔交易可能因为WSS重连、轮询补偿等原因被多次处理。 单纯依赖内存 `set` 无法应对进程重启。所以我设计了 `tx_history` 表的复合唯一约束: ```sql UNIQUE(tx_hash, log_index, address) ``` 任何重复插入都会被SQLite的 `ON CONFLICT IGNORE` 静默丢弃。这从数据库内核层面保证了幂等性。 对于没有 `log_index` 的原生币转账,我降级使用 `tx_hash + address` 作为组合键。 ➤ Solana侧:时间窗口内的签名去重 Solana交易没有 `log_index` 概念。而且Helius解析可能产生多条记录。 我使用了内存 `set` 存储最近处理的签名 我利用 `LimitedSizeDict` 的变体思想,在签名集合超过1000个时,自动清空一半(或利用 `OrderedDict` 弹出最旧条目)。 这种滑动窗口去重在性能和准确性之间取得了良好平衡。 --- 四、AI 工程化:多提供商容错和JSON解析的艺术 ➢特征驱动的动态调度 `MultiAIClient` 是 AI模块的核心 它不是简单的if-else分支,而是一个基于特征标志的调度器。 配置文件中定义了每个提供商支持的功能(比如 `transaction_insight`、`daily_report` 等) 当请求解读时,系统会筛选出支持该特征的提供商列表,按优先级发起请求 超时或失败就自动降级到下一个。 ➢ LLM 输出的防御性解析 大模型输出 JSON不稳定是常态。我的处理流程远比 `json.loads` 复杂: 清洗:移除Markdown代码块标记 ```` ```json ```` 和 ```` ``` ````。 正则提取:如果解析失败,我直接用正则表达式 `r'"insight"\s*:\s*"([^"]*)"'` 暴力提取字段。这是最后一道防线。 字段映射:兼容 `insight` / `Insight` / `解读` 等多种Key 命名 这套机制确保了即使Moonshot或DeepSeek返回了“半个 JSON”,前端依然能展示有效解读 它不会抛出 `JSONDecodeError` 导致白屏。 --- 五、内存和性能:LimitedSizeDict和异步队列 ➢ 自定义有限容量字典 Python标准库没有内置LRU而且限制大小的字典 我基于 `collections.OrderedDict` 实现了 `LimitedSizeDict`: ```python def __setitem__(self, key, value): if len(self) >= self.max_size: self.popitem(last=False) # 淘汰最早插入的项 super().__setitem__(key, value) ``` 这个简单的数据结构被用于Token信息缓存、价格缓存、NFT元数据缓存。 它确保了长时间运行时,内存占用不会随着监控地址增多而线性膨胀 内存占用稳定在一个极低水平 ➢Solana 日志的异步串行写入 Solana的详细交易日志需要写入JSON文件 如果多个协程同时 `json.dump`,很容易导致文件格式损坏。 我引入了 `asyncio.Queue`: - 所有写日志请求把数据 `put` 进队列。 - 唯一的一个后台协程 `_file_writer` 阻塞等待队列,取出数据后执行文件I/O。 这既避免了复杂的线程锁,又利用异步特性保证了高并发下的数据安全。 --- 六、前端和后端的双向通信:pywebview的深度集成 ➤ JS API 注入 `pywebview` 允许你把Python对象的方法直接暴露给前端 JavaScript。 我的 `Api` 类继承自多个Mixin 所有以 `def` 开头的公有方法都自动成为 `window.pywebview.api` 的成员。 这让我能以极低成本实现前后端分离。前端只需要关注 UI 交互。 ➤悬浮窗的独立实例和通信 悬浮窗不是主窗口的子DIV,而是 `pywebview` 创建的第二个独立窗口。 我通过 `FloatingWindowManager` 管理它的生命周期。我利用主进程的 `js_api` 实例向悬浮窗注入JS代码(`evaluate_js`) 这实现了主窗口日志向悬浮窗的实时推送。 这种设计保证了悬浮窗即使被关闭,也不会影响主监控任务的运行。 --- 七、桌面应用打包:PyInstaller的深坑和工程化实践 把 Python项目交付给没有技术背景的最终用户,你必须打包成独立EXE PyInstaller看起来是一条命令搞定。但是在复杂项目中,它背后隐藏着无数足以让开发者崩溃的细节。 这一节我分享我在打包“powerpei Web3 哨兵”过程中遇到的几个典型深坑和解决方案。 ➤ 隐式导入和 --hidden-import PyInstaller通过静态分析入口文件的 `import` 语句来构建依赖树。 但是很多库(比如 `pystray`、`websockets`)使用了 `importlib.import_module` 或 `__import__` 动态加载子模块。这导致打包后的 EXE 运行时抛出 `ModuleNotFoundError` 解决这个问题的关键在于根据报错信息反向定位缺失模块 然后在打包命令中显式声明 `--hidden-import`。 比如,这个项目中托盘图标功能必须添加: ```bash --hidden-import pystray._win32 --hidden-import pystray._util --hidden-import win32event --hidden-import win32api ``` 这要求开发者对依赖库的内部结构有一定了解 通常需要结合源码阅读和反复试错才能完整列出所有隐式依赖。 ➤ --collect-all 和资源文件陷阱 `pywebview` 库不仅包含 Python代码 还依赖前端 HTML/JS 以及Edge WebView2 运行时文件。 PyInstaller的默认分析无法感知这些非代码资源 如果你不加处理,打包后程序会因为找不到 `index.html` 或 `webview.js` 而白屏。 正确的处理方式是使用 `--collect-all pywebview` 这个参数强制PyInstaller把 `pywebview` 包目录下的所有文件(包括二进制和静态资源)完整复制到打包目录。 这是处理这类“重型”GUI库的标准操作。 ➤ 二进制依赖和UPX压缩 项目依赖的 `pywin32`、`Pillow` 等库包含 `.pyd` 和 `.dll` 二进制文件。 这些文件体积比较大,而且在PyInstaller打包后不会被自动压缩。 通过集成UPX 工具并在打包命令中指定 `--upx-dir`,你可以对最终 EXE内的二进制文件进行高比率压缩(通常可以缩减 30%-50%体积)。 需要注意的是,极少数老旧杀毒软件可能对UPX加壳的程序产生误报 但是对于技术型用户群体,这种概率极低而且可以通过提交样本解除。 ➤ 路径“冻结”和 sys._MEIPASS 这是PyInstaller打包中最核心的概念 开发阶段,程序通过 `__file__` 或相对路径访问配置文件、图片资源。 打包成单文件EXE 后,所有资源被解压到一个临时目录 这个目录的路径存储在 `sys._MEIPASS` 变量中。 开发者必须在代码中全局替换所有文件访问逻辑。典型范式如下: ```python def get_resource_path(relative_path): if getattr(sys, 'frozen', False): base = sys._MEIPASS else: base = os.path.abspath(".") return os.path.join(base, relative_path) ``` 忽略这个适配会导致程序运行时找不到任何外部文件 这是新手打包时遇到最多的路径地狱 我的做法是把这个函数封装在 `utils.py` 中,全项目统一调用。这确保了打包前后路径行为一致。 ➤子进程的特殊处理 这个系统采用主进程启动子进程的架构。 在打包后,子进程脚本 `Evm.py` 和 `Sol.py` 也被封装在 EXE内部。 如果主进程仍然尝试用 `python.exe Evm.py` 启动,会因为找不到文件而失败。 我的解决方案是在主进程启动子进程时,动态检测是否处于打包模式 然后传递正确的 `--main-exe-dir` 参数,使子进程能定位到配置文件所在的外部目录。 这部分逻辑细节我已经在进程架构章节中讲过了,这里不再重复。 --- 八、最后说几句 我回顾整个开发历程 从单脚本到多进程架构,从裸WebSocket到高可用节点池,从简单的 print日志到结构化 SQLite存储,每一步都是对工程化理解的深化。 打包环节的探索更是让我深刻体会到:能让软件稳定跑起来只是第一步,能让用户轻松用起来才是真正的交付。 这不仅是一个监控工具,更是我在异步编程、进程管理、AI集成、桌面软件开发等领域实践经验的集合。 如果你对文中的任何技术细节感兴趣,欢迎访问我的 GitHub(我在掘金 电鸭 知乎的笔名是 潇楠) --- 作者:Powerpei 全栈 & Web3独立开发者,专注于Python桌面应用、区块链数据分析和AI工程化落地
中文
127
77
529
238.4K
Konnex
Konnex@konnex_world·
Konnex Autonomous Units Mint opens March 16 — exclusively on @opensea The first robotic identities entering the Konnex network. Built to operate. Designed to evolve. Each unit is a gateway into the Konnex ecosystem. opensea.io/collection/kon…
English
107.9K
31.1K
59.2K
420.8K
Swordsman
Swordsman@swordsmanwork·
@PerleLabs left The fuzzy feeling of the right sea wave edge: the white foam in the right photo of the sea wave hitting the beach lacks the texture of splashing water, and looks more like a layer of fuzzy white paint.
English
0
0
0
23
Perle Labs
Perle Labs@PerleLabs·
Perle Human CAPTCHA #5 📸 Let’s keep your captcha streaks alive. One of these vacation photos is real, and one was generated by AI. Which one is real? Reply "left" or "right" and explain why ↓ This week's submissions close Sat, Feb 21th at 11:59pm UTC. Both answers will be revealed on Sunday.
Perle Labs tweet media
English
42.1K
1.6K
5.9K
227.9K
Swordsman retweetledi
RAX Finance
RAX Finance@RaxFinance·
RAX SPARK: Day 4 with @OrTradeX 🎆🧨 PerpDEX is a decentralized perpetual trading layer within the Origins ecosystem, featuring AI trading bots and copy trading tools. Excited to have them join the Spark! To complete today’s check-in: 1️⃣ Follow @RaxFinance & @OrTradeX 2️⃣ Like & RT 3️⃣ Drop your EVM address below Stay consistent to share the $1,100 Prize Pool 🔥 Don’t break the chain. See you tomorrow ⚡️
RAX Finance tweet media
English
715
307
360
13.4K
Swordsman retweetledi
RAX Finance
RAX Finance@RaxFinance·
RAX SPARK: Day 3 with @Phnx_fi 🎆🧨 Phoenix is building an RWA-driven yield-bearing stablecoin ecosystem that turns idle on-chain assets into active capital. Excited to have them join the Spark! To complete today’s check-in: 1️⃣ Follow @RaxFinance & @Phnx_fi 2️⃣ Like & RT 3️⃣ Drop your EVM address below Stay consistent to share the $1,100 Prize Pool 🔥 Don’t break the chain. See you tomorrow ⚡️
RAX Finance tweet media
English
724
352
433
16.5K
Swordsman retweetledi
RAX Finance
RAX Finance@RaxFinance·
RAX SPARK: Day 2 with @haven_rwa 🎆🧨 Haven brings real-world Treasury yield on-chain — bridging traditional fixed income with Web3 accessibility. We’re excited to ignite the Spark together and expand real asset infrastructure in the AI economy! To complete today’s check-in: 1️⃣ Follow @RaxFinance & @haven_rwa 2️⃣ Like & RT 3️⃣ Drop your EVM address in the comments Stay consistent to share the $1,100 Prize Pool 🔥 Don’t break the chain! See you tomorrow ⚡️
RAX Finance tweet media
RAX Finance@RaxFinance

RAX Spark: Ignite the AI Awakening! 🎆🧨 We’re celebrating the Lunar New Year with 10 strategic partners to revolutionize AI infrastructure. Big rewards are waiting for the early sparks! ⚡️ 📅 Feb 10 - Feb 28  🎁 $1,100 USD + Exclusive NFT Fragments To Enter: 1️⃣ Follow all partners, Like & RT. 2️⃣ Complete tasks on RAX Waitlist & Partner pages. 3️⃣ Drop your EVM address in the comments. @ENI__Official @haven_rwa @_Salvo_Official @DeAgentAI @OriginsNetwork_ @DDEX__Official @itplaysout @MoonnFun  @OrTradeX @Phnx_fi @BlockSec_Arena Join the spark and stay tuned for daily tasks. ⚡️

English
646
282
344
13.6K
Swordsman retweetledi
RAX Finance
RAX Finance@RaxFinance·
RAX SPARK: Day 1 with @_Salvo_Official 🎆🧨 Salvo powers next-gen Web3 games with AI-driven assets & immersive gameplay. We are hyped to join forces to power the future of AI infrastructure! To complete today’s check-in: 1️⃣ Follow @RaxFinance & @_Salvo_Official 2️⃣ Like & RT. 3️⃣ Drop your EVM Address in the comments Stay consistent to share the $1,100 Prize Pool🔥 Don't break the chain! See you tomorrow. ⚡️
RAX Finance tweet media
RAX Finance@RaxFinance

RAX Spark: Ignite the AI Awakening! 🎆🧨 We’re celebrating the Lunar New Year with 10 strategic partners to revolutionize AI infrastructure. Big rewards are waiting for the early sparks! ⚡️ 📅 Feb 10 - Feb 28  🎁 $1,100 USD + Exclusive NFT Fragments To Enter: 1️⃣ Follow all partners, Like & RT. 2️⃣ Complete tasks on RAX Waitlist & Partner pages. 3️⃣ Drop your EVM address in the comments. @ENI__Official @haven_rwa @_Salvo_Official @DeAgentAI @OriginsNetwork_ @DDEX__Official @itplaysout @MoonnFun  @OrTradeX @Phnx_fi @BlockSec_Arena Join the spark and stay tuned for daily tasks. ⚡️

English
725
327
425
20.4K
Perle Labs
Perle Labs@PerleLabs·
Perle Human CAPTCHA #4 It's time to put your human judgement to the test again. One of these images of a tiger is a real photograph, one was generated by AI. Which one is real? Reply "left" or "right" and tell us why ↓ This week's submissions close Sat, Feb 14th at 11:59pm UTC. Both answers will be revealed on Sunday 👀
Perle Labs tweet media
English
45.5K
1.6K
6.4K
266.6K
Swordsman retweetledi
RAX Finance
RAX Finance@RaxFinance·
10 NFTs will be given away to users who experience the RAX waitlist. NICE, in collaboration with @RaxFinance !🔥 To enter: -> Follow @RaxFinance & @NICE_NicKSe -> Like and RT -> Try waitlist : rax.finance/waitlist/ -> Drop your EVM address Will pick winners in 3 days!
NicKSe by NICE@NICE_NicKSe

🤝 Partnership Announcement | RAX Finance × NICE ⚡️ Excited to collaborate with @RaxFinance — building the full-stack RWA layer for AI infrastructure, turning real GPU + data-center capacity into verifiable, insured, yield-bearing on-chain assets. Together, we’re connecting real compute with structure-first, execution-verifiable on-chain distribution — bringing long-term capital coordination to the AI economy. ✅ More activations ahead. 🚀 #NICE #RAXFinance #RWA #AI #DePIN #Web3

English
271
132
192
16.6K
Swordsman retweetledi
RAX Finance
RAX Finance@RaxFinance·
RAX Spark: Ignite the AI Awakening! 🎆🧨 We’re celebrating the Lunar New Year with 10 strategic partners to revolutionize AI infrastructure. Big rewards are waiting for the early sparks! ⚡️ 📅 Feb 10 - Feb 28  🎁 $1,100 USD + Exclusive NFT Fragments To Enter: 1️⃣ Follow all partners, Like & RT. 2️⃣ Complete tasks on RAX Waitlist & Partner pages. 3️⃣ Drop your EVM address in the comments. @ENI__Official @haven_rwa @_Salvo_Official @DeAgentAI @OriginsNetwork_ @DDEX__Official @itplaysout @MoonnFun  @OrTradeX @Phnx_fi @BlockSec_Arena Join the spark and stay tuned for daily tasks. ⚡️
RAX Finance tweet media
English
1.6K
735
1K
139K
Perle Labs
Perle Labs@PerleLabs·
Perle Human CAPTCHA #3 📷 One of these images of fruit is a real photograph, one was generated by AI. Which one is real? Reply "left" or "right" and why 👇 You have until Sat, Feb 14th at 11:59pm UTC. This week's answers will be revealed on Sunday.
Perle Labs tweet media
English
57.9K
1.7K
6.7K
299K
Swordsman
Swordsman@swordsmanwork·
@PerleLabs AI AI often only generates a blurry texture that looks like a reflection, rather than rendering it based on the principles of physical reflection.
English
0
0
0
8
Perle Labs
Perle Labs@PerleLabs·
Perle Human CAPTCHA Round 2 ✌️ Was this landscape art created by a real artist, or AI generated? Reply with "Human" or "AI" and tell us why! Deadline is Sat, Feb 7th at 11:59pm UTC. This week's answers will be revealed on Sunday. PS: Use your own judgement and trust your instincts!
Perle Labs tweet media
English
53.2K
2.2K
8.9K
504.1K