惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Cisco Blogs
NISL@THU
NISL@THU
G
GRAHAM CLULEY
T
Threatpost
I
Intezer
D
Darknet – Hacking Tools, Hacker News & Cyber Security
P
Proofpoint News Feed
L
Lohrmann on Cybersecurity
Cisco Talos Blog
Cisco Talos Blog
P
Privacy & Cybersecurity Law Blog
Security Latest
Security Latest
P
Palo Alto Networks Blog
L
LINUX DO - 热门话题
Cyberwarzone
Cyberwarzone
AI
AI
Help Net Security
Help Net Security
Forbes - Security
Forbes - Security
T
The Exploit Database - CXSecurity.com
月光博客
月光博客
The GitHub Blog
The GitHub Blog
aimingoo的专栏
aimingoo的专栏
C
CERT Recently Published Vulnerability Notes
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
News and Events Feed by Topic
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Scott Helme
Scott Helme
A
About on SuperTechFans
N
Netflix TechBlog - Medium
TaoSecurity Blog
TaoSecurity Blog
V
V2EX
MongoDB | Blog
MongoDB | Blog
AWS News Blog
AWS News Blog
Google DeepMind News
Google DeepMind News
Google Online Security Blog
Google Online Security Blog
O
OpenAI News
Y
Y Combinator Blog
S
Securelist
GbyAI
GbyAI
D
Docker
SecWiki News
SecWiki News
The Hacker News
The Hacker News
有赞技术团队
有赞技术团队
T
Tenable Blog
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
P
Privacy International News Feed
S
Security Affairs
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Hacker News - Newest:
Hacker News - Newest: "LLM"
H
Hackread – Cybersecurity News, Data Breaches, AI and More

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building an on-chain alerts bot in Python without any blockchain library
Слава Жулано · 2026-05-25 · via DEV Community

PolySignal — my Telegram bot that watches Polymarket — has a small subsystem called chain_watcher. It does one thing: cross-check every trade Polymarket's API reports against what actually happened on Polygon, and complain (via Sentry) when the API is wrong.

It's about 280 lines of Python with one dependency — httpx. No web3.py, no eth-account, no eth-abi. I'm going to walk through how to read public on-chain events from Python with nothing but the standard library and an HTTP client, because (a) I needed to and (b) most tutorials reach for the SDK as the first step when you genuinely don't need it for a read-only watcher.

This isn't an anti-SDK argument. If you're signing transactions, sending funds, or doing serious ABI work, use web3.py. The case here is narrower: for reading specific events from a known contract, you can do it cleanly with httpx + JSON-RPC.

What "watching the chain" actually means

A blockchain node exposes a JSON-RPC API. You can ask it questions:

  • "What block are you on?" → eth_blockNumber
  • "Give me all logs matching this filter from blocks N to M" → eth_getLogs
  • "What's the transaction at this hash?" → eth_getTransactionByHash

For an alerts bot you only need the first two. You repeatedly poll the head of the chain and ask: "any logs from contract X, with this event signature, since the last block I checked?" When new logs come back, decode them and act.

That's it. Forty lines for the polling loop, ten for the JSON-RPC client, twenty for the event decoder, the rest is glue.

The JSON-RPC client

A node listens for HTTP POSTs to its RPC URL. Each call is a single JSON body. You don't need an SDK; you need an HTTP client and a little patience.

class _ChainRPC:
    def __init__(self, url: str, timeout: float = 15.0) -> None:
        self._url = url
        self._client = httpx.AsyncClient(timeout=timeout)
        self._id = 0

    async def _call(self, method: str, params: list) -> object:
        for attempt in range(3):
            self._id += 1
            try:
                resp = await self._client.post(
                    self._url,
                    json={
                        "jsonrpc": "2.0",
                        "id": self._id,
                        "method": method,
                        "params": params,
                    },
                )
                resp.raise_for_status()
                body = resp.json()
                if body.get("error"):
                    raise RuntimeError(f"RPC {method} failed: {body['error']}")
                return body["result"]
            except (httpx.HTTPError, RuntimeError):
                if attempt == 2:
                    raise
                await asyncio.sleep(0.5 * (attempt + 1))
        raise RuntimeError("unreachable")

Enter fullscreen mode Exit fullscreen mode

That's the whole client. Two convenience methods on top:

    async def block_number(self) -> int:
        result = await self._call("eth_blockNumber", [])
        return int(result, 16)  # the node returns hex strings

    async def get_logs(self, address, from_block, to_block, topics):
        return await self._call("eth_getLogs", [{
            "address": address,
            "fromBlock": hex(from_block),
            "toBlock": hex(to_block),
            "topics": topics,
        }])

Enter fullscreen mode Exit fullscreen mode

Why the retries? Public Polygon RPCs (the polygon-rpc.com family and similar) return sporadic 5xx errors. A couple of half-second retries inside one tick smooths that out without stalling.

Filtering the events you actually want

A contract emits events with a known signature. For Polymarket's CTF Exchange V2, the event that matters is OrderFilled:

OrderFilled(
    bytes32 indexed orderHash,
    address indexed maker,
    address indexed taker,
    uint256 side,
    uint256 tokenId,
    uint256 makerAmountFilled,
    uint256 takerAmountFilled,
    uint256 fee
)

Enter fullscreen mode Exit fullscreen mode

The topics field of an Ethereum log carries up to four things:

  1. The Keccak hash of the event signature (topics[0]).
  2. Each indexed parameter, padded to 32 bytes.

For OrderFilled, topics[0] is a known constant, and topics[2] / topics[3] are the maker and taker addresses (left-padded to 32 bytes). To find "any fill involving a watched wallet," I make two eth_getLogs calls — one filtering by the maker topic, one by the taker:

for filter_topics in (
    [ORDER_FILLED_TOPIC, None, watched_address_topics],         # as maker
    [ORDER_FILLED_TOPIC, None, None, watched_address_topics],   # as taker
):
    raw_logs += await rpc.get_logs(CONTRACT, from_block, to_block, filter_topics)

Enter fullscreen mode Exit fullscreen mode

watched_address_topics is a list of 32-byte left-padded addresses. The node does the heavy lifting; you receive only matching logs.

Decoding a log

A log looks like {topics: [...], data: "0x...", transactionHash: "0x...", ...}. Topics are 32-byte hex; the data field is the concatenation of all non-indexed parameters, each padded to 32 bytes. Decoding doesn't need an ABI library for a known fixed-layout event — slice the hex.

def decode_order_filled(raw: dict) -> OrderFill:
    topics = raw["topics"]
    data = raw["data"].removeprefix("0x")
    words = [data[i : i + 64] for i in range(0, len(data), 64)]
    return OrderFill(
        tx_hash=raw["transactionHash"].lower(),
        order_hash=topics[1],
        maker="0x" + topics[2][-40:].lower(),
        taker="0x" + topics[3][-40:].lower(),
        side=int(words[0], 16),
        token_id=int(words[1], 16),
        maker_amount_filled=int(words[2], 16),
        taker_amount_filled=int(words[3], 16),
    )

Enter fullscreen mode Exit fullscreen mode

That's it. A struct-shaped tuple per event.

Defensive bits worth keeping

Two production realities I built into the watcher:

1. Bounded block span. After an RPC outage, the "from last seen block to now" span can be thousands of blocks. Public nodes reject overlong eth_getLogs queries; the watcher gets stuck. So each tick caps the span at a fixed maximum (1000 blocks for me — about 30 minutes at Polygon's ~2s/block) and the watcher catches up in chunks across successive ticks.

2. Cross-check loop, not duplicate ingestion. I'm not using the chain as my primary data source; I'm using it to verify the API. The watcher records on-chain fills, waits a few minutes for the API to report the same trade, and complains via Sentry if the API never did. A single buggy API response throws a signal I'll see; if the chain were silent and the API were silent, neither layer would notice.

This is the part where SDK-less actually beats SDK: there's no library between me and the bytes. When something goes wrong, the trace is short.

When NOT to skip the SDK

To be honest about the trade:

  • Don't skip if you're sending transactions. Nonce management, gas estimation, signing — that's exactly what web3.py is for.
  • Don't skip if you need ABI introspection. Dynamic ABI parsing is genuinely a library-grade problem.
  • Don't skip if you want one client that handles ETH + several L2s with their quirks. A library normalises that.

For a passive watcher of a single event on a single chain, none of those apply. Eight imports, one HTTP client, ~280 lines.

The watcher in the wild

This runs inside PolySignal, my Telegram bot that alerts users when top wallets on Polymarket make a trade. The chain_watcher is the part that lets me sleep at night when Polymarket's API has its periodic moments.

If you want to read the full module, it's about 280 lines including comments and the cross-check loop. Happy to paste a Gist or answer questions in the comments.