web3-systemic-agent 1.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- scripts/active_contract_hunter.py +262 -0
- scripts/block_contract_scanner.py +887 -0
- scripts/client_agent_x402.py +584 -0
- scripts/dex_pool_monitor.py +1418 -0
- scripts/governance_daemon.py +683 -0
- scripts/governance_listener.py +201 -0
- scripts/register_erc8004_agent.py +297 -0
- scripts/setup_buyer_wallet.py +193 -0
- src/api.py +5094 -0
- src/chain_inspector.py +256 -0
- src/discovery_hunter.py +1000 -0
- src/engine.py +281 -0
- src/governance_connector.py +548 -0
- src/mcp_server.py +2048 -0
- src/preflight_firewall.py +603 -0
- src/report.py +142 -0
- src/schemas.py +330 -0
- src/semantic_evaluator.py +981 -0
- src/source_resolver.py +792 -0
- src/storage.py +863 -0
- src/task_worker.py +325 -0
- src/test_cache_and_telemetry.py +488 -0
- src/x402_payment.py +1540 -0
- web3_systemic_agent-1.0.2.dist-info/METADATA +511 -0
- web3_systemic_agent-1.0.2.dist-info/RECORD +29 -0
- web3_systemic_agent-1.0.2.dist-info/WHEEL +5 -0
- web3_systemic_agent-1.0.2.dist-info/entry_points.txt +3 -0
- web3_systemic_agent-1.0.2.dist-info/licenses/LICENSE +201 -0
- web3_systemic_agent-1.0.2.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,1418 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Autonomous DEX Liquidity Pool Monitor & Honeypot Auditor for Base Mainnet.
|
|
3
|
+
|
|
4
|
+
Engine 3 of the Web3 Condition-Action Trigger Agent.
|
|
5
|
+
Monitors the creation of new liquidity pools on Aerodrome Finance and Uniswap v3
|
|
6
|
+
on Base Mainnet (Chain ID 8453), decodes PoolCreated events via RPC logs at zero extra cost,
|
|
7
|
+
identifies target unverified tokens vs canonical base assets (WETH, USDC, USDbC, cbBTC),
|
|
8
|
+
inspects EVM bytecode for honeypot signatures (blacklist, arbitrary 100% tax, trading pause, selfdestruct),
|
|
9
|
+
executes deterministic and semantic evaluations via ConditionAgentEngine,
|
|
10
|
+
persists audit records to SQLite (data/agent.db with source="dex_pool_monitor"),
|
|
11
|
+
renders an ASCII audit report table, and dispatches webhook alerts.
|
|
12
|
+
|
|
13
|
+
Factory Contracts Monitored on Base Mainnet (Chain ID 8453):
|
|
14
|
+
1. Aerodrome Factory: 0x420DD381b31aEf6683db6B902084cB0FFECe40Da
|
|
15
|
+
Event: PoolCreated(address indexed token0, address indexed token1, bool stable, address pool, uint256)
|
|
16
|
+
Topic0: 0x2128d88fa89c09c2a26569145610817c7621c172bc97d919a3b6805175e53303
|
|
17
|
+
2. Uniswap v3 Factory: 0x33128a8fC17869897dcE68Ed026d694621f6FDfD
|
|
18
|
+
Event: PoolCreated(address indexed token0, address indexed token1, uint24 fee, int24 tickSpacing, address pool)
|
|
19
|
+
Topic0: 0x783cca1c041e8d94974f7875ce418c7bc05524c2b19bb87934f716002bc0ffab
|
|
20
|
+
|
|
21
|
+
Usage Examples:
|
|
22
|
+
# 1. Dry-run simulation (offline, zero RPC calls, zero LLM cost):
|
|
23
|
+
python scripts/dex_pool_monitor.py --dry-run
|
|
24
|
+
|
|
25
|
+
# 2. Single scan across recent 100 blocks on Base Mainnet:
|
|
26
|
+
python scripts/dex_pool_monitor.py --blocks 100 --limit 5
|
|
27
|
+
|
|
28
|
+
# 3. Continuous polling daemon mode:
|
|
29
|
+
python scripts/dex_pool_monitor.py --continuous --poll-interval 15
|
|
30
|
+
|
|
31
|
+
# 4. Custom RPC endpoint and webhook alerts:
|
|
32
|
+
python scripts/dex_pool_monitor.py --rpc-url https://mainnet.base.org --webhook-url https://discord.com/api/webhooks/...
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
import argparse
|
|
36
|
+
import asyncio
|
|
37
|
+
from datetime import datetime, timezone
|
|
38
|
+
import inspect
|
|
39
|
+
import json
|
|
40
|
+
import logging
|
|
41
|
+
import os
|
|
42
|
+
import re
|
|
43
|
+
import sys
|
|
44
|
+
import time
|
|
45
|
+
from typing import Dict, Any, Optional, List, Tuple, Union
|
|
46
|
+
from unittest.mock import AsyncMock, MagicMock
|
|
47
|
+
|
|
48
|
+
# Guarded dotenv loading: skipped during pytest execution or if python-dotenv not installed
|
|
49
|
+
if "pytest" not in sys.modules:
|
|
50
|
+
try:
|
|
51
|
+
import dotenv
|
|
52
|
+
_CURRENT_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
53
|
+
_PARENT_ROOT = os.path.abspath(os.path.join(_CURRENT_SCRIPT_DIR, ".."))
|
|
54
|
+
_env_file = os.path.join(_PARENT_ROOT, ".env")
|
|
55
|
+
if os.path.exists(_env_file):
|
|
56
|
+
dotenv.load_dotenv(_env_file, override=False)
|
|
57
|
+
dotenv.load_dotenv(override=False)
|
|
58
|
+
except ImportError:
|
|
59
|
+
pass
|
|
60
|
+
|
|
61
|
+
# Ensure module search paths support running directly or as a package
|
|
62
|
+
_CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
63
|
+
_ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, ".."))
|
|
64
|
+
_SRC_DIR = os.path.join(_ROOT_DIR, "src")
|
|
65
|
+
for _p in (_ROOT_DIR, _SRC_DIR):
|
|
66
|
+
if _p not in sys.path:
|
|
67
|
+
sys.path.insert(0, _p)
|
|
68
|
+
|
|
69
|
+
try:
|
|
70
|
+
import httpx
|
|
71
|
+
except ImportError:
|
|
72
|
+
httpx = None # type: ignore
|
|
73
|
+
|
|
74
|
+
from web3 import AsyncWeb3, AsyncHTTPProvider, Web3
|
|
75
|
+
from web3.exceptions import Web3Exception
|
|
76
|
+
|
|
77
|
+
try:
|
|
78
|
+
from src.schemas import (
|
|
79
|
+
ChainId,
|
|
80
|
+
ConditionRulePayload,
|
|
81
|
+
DeterministicCondition,
|
|
82
|
+
SemanticCondition,
|
|
83
|
+
FinalAgentResponse,
|
|
84
|
+
)
|
|
85
|
+
from src.chain_inspector import ChainInspector
|
|
86
|
+
from src.engine import ConditionAgentEngine
|
|
87
|
+
from src.semantic_evaluator import (
|
|
88
|
+
MockSemanticEvaluator,
|
|
89
|
+
get_semantic_evaluator,
|
|
90
|
+
)
|
|
91
|
+
from src.storage import AgentStorage
|
|
92
|
+
except ImportError:
|
|
93
|
+
from schemas import (
|
|
94
|
+
ChainId,
|
|
95
|
+
ConditionRulePayload,
|
|
96
|
+
DeterministicCondition,
|
|
97
|
+
SemanticCondition,
|
|
98
|
+
FinalAgentResponse,
|
|
99
|
+
)
|
|
100
|
+
from chain_inspector import ChainInspector
|
|
101
|
+
from engine import ConditionAgentEngine
|
|
102
|
+
from semantic_evaluator import (
|
|
103
|
+
MockSemanticEvaluator,
|
|
104
|
+
get_semantic_evaluator,
|
|
105
|
+
)
|
|
106
|
+
from storage import AgentStorage
|
|
107
|
+
|
|
108
|
+
logger = logging.getLogger("dex_pool_monitor")
|
|
109
|
+
|
|
110
|
+
# Base Mainnet Network Parameters
|
|
111
|
+
CHAIN_ID_BASE_MAINNET = 8453
|
|
112
|
+
DEFAULT_BASE_RPC = "https://mainnet.base.org"
|
|
113
|
+
|
|
114
|
+
# DEX Factory Contracts on Base Mainnet
|
|
115
|
+
AERODROME_FACTORY_ADDRESS = Web3.to_checksum_address("0x420DD381b31aEf6683db6B902084cB0FFECe40Da")
|
|
116
|
+
UNISWAP_V3_FACTORY_ADDRESS = Web3.to_checksum_address("0x33128a8fC17869897dcE68Ed026d694621f6FDfD")
|
|
117
|
+
|
|
118
|
+
# PoolCreated Event Topics
|
|
119
|
+
# Aerodrome: PoolCreated(address indexed token0, address indexed token1, bool stable, address pool, uint256)
|
|
120
|
+
AERODROME_POOL_CREATED_TOPIC0 = "0x2128d88fa89c09c2a26569145610817c7621c172bc97d919a3b6805175e53303"
|
|
121
|
+
# Uniswap v3: PoolCreated(address indexed token0, address indexed token1, uint24 fee, int24 tickSpacing, address pool)
|
|
122
|
+
UNISWAP_V3_POOL_CREATED_TOPIC0 = "0x783cca1c041e8d94974f7875ce418c7bc05524c2b19bb87934f716002bc0ffab"
|
|
123
|
+
|
|
124
|
+
# Canonical Base Mainnet Liquid Assets
|
|
125
|
+
BASE_TOKENS: Dict[str, str] = {
|
|
126
|
+
Web3.to_checksum_address("0x4200000000000000000000000000000000000006"): "WETH",
|
|
127
|
+
Web3.to_checksum_address("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"): "USDC",
|
|
128
|
+
Web3.to_checksum_address("0xd9aAEc86B65D86f6A7B5B1b0c42FFA531710b6CA"): "USDbC",
|
|
129
|
+
Web3.to_checksum_address("0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf"): "cbBTC",
|
|
130
|
+
}
|
|
131
|
+
BASE_TOKENS_LOWER: Dict[str, Tuple[str, str]] = {
|
|
132
|
+
addr.lower(): (addr, sym) for addr, sym in BASE_TOKENS.items()
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
# Critical Honeypot, Rugpull, and Malicious Smart Contract Selectors
|
|
136
|
+
HONEYPOT_SELECTORS: Dict[str, Dict[str, str]] = {
|
|
137
|
+
# 1. Blacklist Manipulation
|
|
138
|
+
"0xf9f02b01": {
|
|
139
|
+
"signature": "isBlacklisted(address)",
|
|
140
|
+
"category": "blacklist",
|
|
141
|
+
"description": "Blacklist query function (used to selectively block transfers)",
|
|
142
|
+
"severity": "CRITICAL",
|
|
143
|
+
},
|
|
144
|
+
"0x40af1275": {
|
|
145
|
+
"signature": "setBlacklist(address,bool)",
|
|
146
|
+
"category": "blacklist",
|
|
147
|
+
"description": "Blacklist modification (can prevent users from selling/transferring)",
|
|
148
|
+
"severity": "CRITICAL",
|
|
149
|
+
},
|
|
150
|
+
"0x4433766a": {
|
|
151
|
+
"signature": "addToBlacklist(address)",
|
|
152
|
+
"category": "blacklist",
|
|
153
|
+
"description": "Arbitrary blacklist addition",
|
|
154
|
+
"severity": "CRITICAL",
|
|
155
|
+
},
|
|
156
|
+
"0xfa4526f8": {
|
|
157
|
+
"signature": "blacklist(address)",
|
|
158
|
+
"category": "blacklist",
|
|
159
|
+
"description": "Blacklist trigger function",
|
|
160
|
+
"severity": "CRITICAL",
|
|
161
|
+
},
|
|
162
|
+
"0x5a54e565": {
|
|
163
|
+
"signature": "isBlackList(address)",
|
|
164
|
+
"category": "blacklist",
|
|
165
|
+
"description": "Blacklist status verification",
|
|
166
|
+
"severity": "CRITICAL",
|
|
167
|
+
},
|
|
168
|
+
# 2. Arbitrary Transfer Fee & 100% Tax Traps
|
|
169
|
+
"0x8a92d475": {
|
|
170
|
+
"signature": "setFee(uint256)",
|
|
171
|
+
"category": "fee_tax",
|
|
172
|
+
"description": "Arbitrary transfer fee configuration",
|
|
173
|
+
"severity": "HIGH",
|
|
174
|
+
},
|
|
175
|
+
"0x1e3dd19f": {
|
|
176
|
+
"signature": "setTax(uint256)",
|
|
177
|
+
"category": "fee_tax",
|
|
178
|
+
"description": "Arbitrary transaction tax configuration (honeypot risk)",
|
|
179
|
+
"severity": "CRITICAL",
|
|
180
|
+
},
|
|
181
|
+
"0x4a7e9375": {
|
|
182
|
+
"signature": "setBuyFee(uint256)",
|
|
183
|
+
"category": "fee_tax",
|
|
184
|
+
"description": "Buy tax modification",
|
|
185
|
+
"severity": "MEDIUM",
|
|
186
|
+
},
|
|
187
|
+
"0x4b7890ec": {
|
|
188
|
+
"signature": "setSellFee(uint256)",
|
|
189
|
+
"category": "fee_tax",
|
|
190
|
+
"description": "Sell tax modification (allows setting 99-100% honeypot sell tax)",
|
|
191
|
+
"severity": "CRITICAL",
|
|
192
|
+
},
|
|
193
|
+
"0x1f56a319": {
|
|
194
|
+
"signature": "setFeeRate(uint256)",
|
|
195
|
+
"category": "fee_tax",
|
|
196
|
+
"description": "Transfer fee rate modification",
|
|
197
|
+
"severity": "HIGH",
|
|
198
|
+
},
|
|
199
|
+
"0x32e54143": {
|
|
200
|
+
"signature": "setMaxTax(uint256)",
|
|
201
|
+
"category": "fee_tax",
|
|
202
|
+
"description": "Max tax modification",
|
|
203
|
+
"severity": "MEDIUM",
|
|
204
|
+
},
|
|
205
|
+
"0x8c6d1d78": {
|
|
206
|
+
"signature": "setTaxFeePercent(uint256)",
|
|
207
|
+
"category": "fee_tax",
|
|
208
|
+
"description": "Tax fee percentage manipulation",
|
|
209
|
+
"severity": "HIGH",
|
|
210
|
+
},
|
|
211
|
+
# 3. Trading Freeze & Pause Mechanisms
|
|
212
|
+
"0x4fbee1e3": {
|
|
213
|
+
"signature": "pause()",
|
|
214
|
+
"category": "pause_trading",
|
|
215
|
+
"description": "Contract execution freeze (can halt trading indefinitely)",
|
|
216
|
+
"severity": "HIGH",
|
|
217
|
+
},
|
|
218
|
+
"0x8456cb59": {
|
|
219
|
+
"signature": "unpause()",
|
|
220
|
+
"category": "pause_trading",
|
|
221
|
+
"description": "Contract execution unpause",
|
|
222
|
+
"severity": "LOW",
|
|
223
|
+
},
|
|
224
|
+
"0x8a8c523c": {
|
|
225
|
+
"signature": "enableTrading()",
|
|
226
|
+
"category": "pause_trading",
|
|
227
|
+
"description": "Trading enablement gate (can be kept permanently closed)",
|
|
228
|
+
"severity": "HIGH",
|
|
229
|
+
},
|
|
230
|
+
"0x34468f9b": {
|
|
231
|
+
"signature": "setTrading(bool)",
|
|
232
|
+
"category": "pause_trading",
|
|
233
|
+
"description": "Arbitrary trading toggle (can disable selling after launch)",
|
|
234
|
+
"severity": "CRITICAL",
|
|
235
|
+
},
|
|
236
|
+
"0xc9567bf9": {
|
|
237
|
+
"signature": "openTrading()",
|
|
238
|
+
"category": "pause_trading",
|
|
239
|
+
"description": "Trading opening trigger",
|
|
240
|
+
"severity": "HIGH",
|
|
241
|
+
},
|
|
242
|
+
"0xd8eb23cf": {
|
|
243
|
+
"signature": "setTradingEnabled(bool)",
|
|
244
|
+
"category": "pause_trading",
|
|
245
|
+
"description": "Trading status override",
|
|
246
|
+
"severity": "CRITICAL",
|
|
247
|
+
},
|
|
248
|
+
# 4. Contract Destruction & Draining
|
|
249
|
+
"0x00f714ce": {
|
|
250
|
+
"signature": "selfdestruct()",
|
|
251
|
+
"category": "destruct_drain",
|
|
252
|
+
"description": "Contract self-destruction (permanently bricks token and sweeps funds)",
|
|
253
|
+
"severity": "CRITICAL",
|
|
254
|
+
},
|
|
255
|
+
"0x41c0e1b5": {
|
|
256
|
+
"signature": "kill()",
|
|
257
|
+
"category": "destruct_drain",
|
|
258
|
+
"description": "Emergency kill switch",
|
|
259
|
+
"severity": "CRITICAL",
|
|
260
|
+
},
|
|
261
|
+
"0x83197ef0": {
|
|
262
|
+
"signature": "destroy(address)",
|
|
263
|
+
"category": "destruct_drain",
|
|
264
|
+
"description": "Contract destroy and balance sweep",
|
|
265
|
+
"severity": "CRITICAL",
|
|
266
|
+
},
|
|
267
|
+
# 5. Privileged Admin & Minting Backdoors
|
|
268
|
+
"0xf2fde38b": {
|
|
269
|
+
"signature": "transferOwnership(address)",
|
|
270
|
+
"category": "privileged",
|
|
271
|
+
"description": "Centralized ownership transfer",
|
|
272
|
+
"severity": "MEDIUM",
|
|
273
|
+
},
|
|
274
|
+
"0x3659cfe6": {
|
|
275
|
+
"signature": "upgradeTo(address)",
|
|
276
|
+
"category": "privileged",
|
|
277
|
+
"description": "Proxy contract upgradability (logic can be swapped to honeypot)",
|
|
278
|
+
"severity": "HIGH",
|
|
279
|
+
},
|
|
280
|
+
"0x40c10f19": {
|
|
281
|
+
"signature": "mint(address,uint256)",
|
|
282
|
+
"category": "privileged",
|
|
283
|
+
"description": "Arbitrary token minting (unlimited inflation / dump risk)",
|
|
284
|
+
"severity": "HIGH",
|
|
285
|
+
},
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
# Standard ERC-20 Selectors for Reference
|
|
289
|
+
STANDARD_ERC20_SELECTORS: Dict[str, str] = {
|
|
290
|
+
"0xa9059cbb": "transfer(address,uint256)",
|
|
291
|
+
"0x095ea7b3": "approve(address,uint256)",
|
|
292
|
+
"0x23b872dd": "transferFrom(address,address,uint256)",
|
|
293
|
+
"0x70a08231": "balanceOf(address)",
|
|
294
|
+
"0x18160ddd": "totalSupply()",
|
|
295
|
+
"0x313ce567": "decimals()",
|
|
296
|
+
"0x06fdde03": "name()",
|
|
297
|
+
"0x95d89b41": "symbol()",
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
DISPATCHER_REGEX = re.compile(r"(?:63|8063|8263)([0-9a-fA-F]{8})14", re.IGNORECASE)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def decode_address_from_topic(topic: Union[bytes, str]) -> str:
|
|
304
|
+
"""Decodes a 20-byte EVM address from a 32-byte log topic."""
|
|
305
|
+
if isinstance(topic, (bytes, bytearray)):
|
|
306
|
+
topic_hex = topic.hex()
|
|
307
|
+
else:
|
|
308
|
+
topic_hex = str(topic)
|
|
309
|
+
if topic_hex.startswith("0x"):
|
|
310
|
+
topic_hex = topic_hex[2:]
|
|
311
|
+
raw_addr = "0x" + topic_hex[-40:]
|
|
312
|
+
return Web3.to_checksum_address(raw_addr)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def decode_aerodrome_pool_data(data: Union[bytes, str]) -> Tuple[str, bool]:
|
|
316
|
+
"""
|
|
317
|
+
Decodes unindexed parameters from Aerodrome PoolCreated event:
|
|
318
|
+
Event data layout: (bool stable, address pool, uint256 index)
|
|
319
|
+
Word 0 (0..64): bool stable
|
|
320
|
+
Word 1 (64..128): address pool (last 40 hex chars)
|
|
321
|
+
"""
|
|
322
|
+
if isinstance(data, (bytes, bytearray)):
|
|
323
|
+
data_hex = data.hex()
|
|
324
|
+
else:
|
|
325
|
+
data_hex = str(data)
|
|
326
|
+
if data_hex.startswith("0x"):
|
|
327
|
+
data_hex = data_hex[2:]
|
|
328
|
+
|
|
329
|
+
if len(data_hex) < 128:
|
|
330
|
+
return ("0x0000000000000000000000000000000000000000", False)
|
|
331
|
+
|
|
332
|
+
stable_word = data_hex[0:64]
|
|
333
|
+
pool_word = data_hex[64:128]
|
|
334
|
+
|
|
335
|
+
stable = int(stable_word, 16) != 0
|
|
336
|
+
pool_address = Web3.to_checksum_address("0x" + pool_word[-40:])
|
|
337
|
+
return (pool_address, stable)
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def decode_univ3_pool_data(data: Union[bytes, str]) -> Tuple[str, int, int]:
|
|
341
|
+
"""
|
|
342
|
+
Decodes unindexed parameters from Uniswap v3 PoolCreated event:
|
|
343
|
+
Event data layout: (uint24 fee, int24 tickSpacing, address pool)
|
|
344
|
+
Word 0 (0..64): uint24 fee
|
|
345
|
+
Word 1 (64..128): int24 tickSpacing
|
|
346
|
+
Word 2 (128..192): address pool (last 40 hex chars)
|
|
347
|
+
"""
|
|
348
|
+
if isinstance(data, (bytes, bytearray)):
|
|
349
|
+
data_hex = data.hex()
|
|
350
|
+
else:
|
|
351
|
+
data_hex = str(data)
|
|
352
|
+
if data_hex.startswith("0x"):
|
|
353
|
+
data_hex = data_hex[2:]
|
|
354
|
+
|
|
355
|
+
if len(data_hex) < 192:
|
|
356
|
+
return ("0x0000000000000000000000000000000000000000", 3000, 60)
|
|
357
|
+
|
|
358
|
+
fee_word = data_hex[0:64]
|
|
359
|
+
tick_spacing_word = data_hex[64:128]
|
|
360
|
+
pool_word = data_hex[128:192]
|
|
361
|
+
|
|
362
|
+
fee = int(fee_word, 16)
|
|
363
|
+
raw_tick_bytes = bytes.fromhex(tick_spacing_word)
|
|
364
|
+
tick_spacing = int.from_bytes(raw_tick_bytes, byteorder="big", signed=True)
|
|
365
|
+
pool_address = Web3.to_checksum_address("0x" + pool_word[-40:])
|
|
366
|
+
return (pool_address, fee, tick_spacing)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def identify_target_token(token0: str, token1: str) -> Tuple[str, str, str]:
|
|
370
|
+
"""
|
|
371
|
+
Identifies the unverified target token vs the known base token (WETH, USDC, USDbC, cbBTC).
|
|
372
|
+
|
|
373
|
+
Returns:
|
|
374
|
+
(target_token, base_token, pair_name)
|
|
375
|
+
"""
|
|
376
|
+
t0_cs = Web3.to_checksum_address(token0)
|
|
377
|
+
t1_cs = Web3.to_checksum_address(token1)
|
|
378
|
+
|
|
379
|
+
t0_lower = t0_cs.lower()
|
|
380
|
+
t1_lower = t1_cs.lower()
|
|
381
|
+
|
|
382
|
+
t0_is_base = t0_lower in BASE_TOKENS_LOWER
|
|
383
|
+
t1_is_base = t1_lower in BASE_TOKENS_LOWER
|
|
384
|
+
|
|
385
|
+
if t0_is_base and not t1_is_base:
|
|
386
|
+
base_addr, base_sym = BASE_TOKENS_LOWER[t0_lower]
|
|
387
|
+
target_token = t1_cs
|
|
388
|
+
base_token = base_addr
|
|
389
|
+
pair_name = f"{t1_cs[:6]}.../{base_sym}"
|
|
390
|
+
elif t1_is_base and not t0_is_base:
|
|
391
|
+
base_addr, base_sym = BASE_TOKENS_LOWER[t1_lower]
|
|
392
|
+
target_token = t0_cs
|
|
393
|
+
base_token = base_addr
|
|
394
|
+
pair_name = f"{t0_cs[:6]}.../{base_sym}"
|
|
395
|
+
elif t0_is_base and t1_is_base:
|
|
396
|
+
base_addr0, base_sym0 = BASE_TOKENS_LOWER[t0_lower]
|
|
397
|
+
base_addr1, base_sym1 = BASE_TOKENS_LOWER[t1_lower]
|
|
398
|
+
target_token = t1_cs
|
|
399
|
+
base_token = base_addr0
|
|
400
|
+
pair_name = f"{base_sym0}/{base_sym1}"
|
|
401
|
+
else:
|
|
402
|
+
# Both tokens are unverified new assets
|
|
403
|
+
target_token = t0_cs
|
|
404
|
+
base_token = t1_cs
|
|
405
|
+
pair_name = f"{t0_cs[:6]}.../{t1_cs[:6]}..."
|
|
406
|
+
|
|
407
|
+
return (target_token, base_token, pair_name)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def extract_selectors_from_bytecode(
|
|
411
|
+
bytecode: Union[bytes, str],
|
|
412
|
+
) -> List[Dict[str, Any]]:
|
|
413
|
+
"""
|
|
414
|
+
Extracts 4-byte EVM function selectors and maps known signatures from bytecode.
|
|
415
|
+
"""
|
|
416
|
+
if isinstance(bytecode, bytes):
|
|
417
|
+
bytecode_hex = bytecode.hex()
|
|
418
|
+
else:
|
|
419
|
+
bytecode_hex = bytecode[2:] if bytecode.startswith("0x") else bytecode
|
|
420
|
+
|
|
421
|
+
found: Dict[str, Dict[str, Any]] = {}
|
|
422
|
+
bytecode_lower = bytecode_hex.lower()
|
|
423
|
+
|
|
424
|
+
# Search for all Honeypot and Standard Selectors directly
|
|
425
|
+
all_known = {**STANDARD_ERC20_SELECTORS, **{k: v["signature"] for k, v in HONEYPOT_SELECTORS.items()}}
|
|
426
|
+
for sel_hex, sig in all_known.items():
|
|
427
|
+
clean_sel = sel_hex[2:].lower()
|
|
428
|
+
if clean_sel in bytecode_lower:
|
|
429
|
+
found[sel_hex] = {
|
|
430
|
+
"selector": sel_hex,
|
|
431
|
+
"signature": sig,
|
|
432
|
+
"known": True,
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
# Extract selectors matching standard EVM dispatcher pattern
|
|
436
|
+
for m in DISPATCHER_REGEX.findall(bytecode_hex):
|
|
437
|
+
sel_hex = f"0x{m.lower()}"
|
|
438
|
+
if sel_hex not in found:
|
|
439
|
+
sig = all_known.get(sel_hex, f"unknown({sel_hex})")
|
|
440
|
+
found[sel_hex] = {
|
|
441
|
+
"selector": sel_hex,
|
|
442
|
+
"signature": sig,
|
|
443
|
+
"known": sel_hex in all_known,
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
return list(found.values())
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def has_selfdestruct_opcode(bytecode: Union[bytes, str]) -> bool:
|
|
450
|
+
"""
|
|
451
|
+
Scans EVM runtime bytecode for the SELFDESTRUCT opcode (0xff), stripping
|
|
452
|
+
Solidity CBOR metadata suffixes and skipping PUSH1..PUSH32 immediate operands
|
|
453
|
+
to prevent false positives on bitmasks (e.g., 0xff..ff) or compiler hashes.
|
|
454
|
+
"""
|
|
455
|
+
if not bytecode:
|
|
456
|
+
return False
|
|
457
|
+
|
|
458
|
+
if isinstance(bytecode, (bytes, bytearray)):
|
|
459
|
+
code = bytes(bytecode)
|
|
460
|
+
elif isinstance(bytecode, str):
|
|
461
|
+
clean_hex = bytecode.strip()
|
|
462
|
+
if clean_hex.startswith(("0x", "0X")):
|
|
463
|
+
clean_hex = clean_hex[2:]
|
|
464
|
+
if not clean_hex:
|
|
465
|
+
return False
|
|
466
|
+
try:
|
|
467
|
+
code = bytes.fromhex(clean_hex)
|
|
468
|
+
except ValueError:
|
|
469
|
+
return False
|
|
470
|
+
else:
|
|
471
|
+
return False
|
|
472
|
+
|
|
473
|
+
if not code:
|
|
474
|
+
return False
|
|
475
|
+
|
|
476
|
+
# Strip Solidity compiler CBOR metadata suffix if present
|
|
477
|
+
if len(code) >= 2:
|
|
478
|
+
meta_len = int.from_bytes(code[-2:], "big")
|
|
479
|
+
if 0 < meta_len and meta_len + 2 <= len(code):
|
|
480
|
+
meta_block = code[-(meta_len + 2):-2]
|
|
481
|
+
if meta_block and meta_block[0] in (0xA1, 0xA2) and any(
|
|
482
|
+
tag in meta_block for tag in (b"ipfs", b"bzzr", b"solc")
|
|
483
|
+
):
|
|
484
|
+
code = code[:-(meta_len + 2)]
|
|
485
|
+
|
|
486
|
+
pc = 0
|
|
487
|
+
code_len = len(code)
|
|
488
|
+
while pc < code_len:
|
|
489
|
+
op = code[pc]
|
|
490
|
+
if op == 0xFF:
|
|
491
|
+
return True
|
|
492
|
+
if 0x60 <= op <= 0x7F:
|
|
493
|
+
pc += 1 + (op - 0x5F)
|
|
494
|
+
else:
|
|
495
|
+
pc += 1
|
|
496
|
+
|
|
497
|
+
return False
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def analyze_bytecode_honeypot(bytecode: Union[bytes, str]) -> Dict[str, Any]:
|
|
501
|
+
"""
|
|
502
|
+
Performs comprehensive static bytecode analysis for honeypot indicators:
|
|
503
|
+
- Blacklist manipulation (0xf9f02b01, 0x40af1275, etc.)
|
|
504
|
+
- Arbitrary transfer tax / 100% sell fee traps (setTax, setFee, setSellFee)
|
|
505
|
+
- Trading freeze / pause backdoors (pause, setTrading, enableTrading)
|
|
506
|
+
- Contract self-destruction / drainage (selfdestruct, kill, destroy)
|
|
507
|
+
"""
|
|
508
|
+
selectors = extract_selectors_from_bytecode(bytecode)
|
|
509
|
+
sel_map = {s["selector"].lower(): s for s in selectors}
|
|
510
|
+
|
|
511
|
+
if isinstance(bytecode, bytes):
|
|
512
|
+
bytecode_hex = bytecode.hex().lower()
|
|
513
|
+
else:
|
|
514
|
+
bytecode_hex = (bytecode[2:] if bytecode.startswith("0x") else bytecode).lower()
|
|
515
|
+
|
|
516
|
+
honeypot_flags: List[str] = []
|
|
517
|
+
categories: Dict[str, List[str]] = {
|
|
518
|
+
"blacklist": [],
|
|
519
|
+
"fee_tax": [],
|
|
520
|
+
"pause_trading": [],
|
|
521
|
+
"destruct_drain": [],
|
|
522
|
+
"privileged": [],
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
# Check for Honeypot function selectors
|
|
526
|
+
for sel_hex, info in HONEYPOT_SELECTORS.items():
|
|
527
|
+
clean_sel = sel_hex[2:].lower()
|
|
528
|
+
matched = False
|
|
529
|
+
if sel_hex.lower() in sel_map:
|
|
530
|
+
matched = True
|
|
531
|
+
elif clean_sel in bytecode_hex:
|
|
532
|
+
matched = True
|
|
533
|
+
|
|
534
|
+
if matched:
|
|
535
|
+
cat = info["category"]
|
|
536
|
+
sig = info["signature"]
|
|
537
|
+
categories[cat].append(sig)
|
|
538
|
+
honeypot_flags.append(f"{cat.replace('_', ' ').title()}: {sig} ({sel_hex})")
|
|
539
|
+
|
|
540
|
+
# Opcode detection for EVM SELFDESTRUCT (0xff)
|
|
541
|
+
if has_selfdestruct_opcode(bytecode):
|
|
542
|
+
# 0xff is present as an actual opcode outside PUSH immediate operands and CBOR metadata
|
|
543
|
+
if "selfdestruct" not in categories["destruct_drain"]:
|
|
544
|
+
categories["destruct_drain"].append("SELFDESTRUCT opcode (0xff)")
|
|
545
|
+
honeypot_flags.append("Destruct Drain: SELFDESTRUCT opcode (0xff)")
|
|
546
|
+
|
|
547
|
+
# Assess overall honeypot severity
|
|
548
|
+
is_honeypot = bool(
|
|
549
|
+
categories["blacklist"]
|
|
550
|
+
or categories["fee_tax"]
|
|
551
|
+
or categories["destruct_drain"]
|
|
552
|
+
or (categories["pause_trading"] and "settrading" in str(categories["pause_trading"]).lower())
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
if categories["destruct_drain"] or categories["blacklist"]:
|
|
556
|
+
severity = "CRITICAL"
|
|
557
|
+
elif categories["fee_tax"] or categories["pause_trading"]:
|
|
558
|
+
severity = "HIGH"
|
|
559
|
+
elif categories["privileged"]:
|
|
560
|
+
severity = "MEDIUM"
|
|
561
|
+
else:
|
|
562
|
+
severity = "CLEAN"
|
|
563
|
+
|
|
564
|
+
# Brief table summary
|
|
565
|
+
active_threats = []
|
|
566
|
+
if categories["blacklist"]:
|
|
567
|
+
active_threats.append("Blacklist")
|
|
568
|
+
if categories["fee_tax"]:
|
|
569
|
+
active_threats.append("Arbitrary Tax")
|
|
570
|
+
if categories["pause_trading"]:
|
|
571
|
+
active_threats.append("Trading Pause")
|
|
572
|
+
if categories["destruct_drain"]:
|
|
573
|
+
active_threats.append("Selfdestruct")
|
|
574
|
+
if categories["privileged"] and not active_threats:
|
|
575
|
+
active_threats.append("Privileged Admin")
|
|
576
|
+
|
|
577
|
+
summary_display = ", ".join(active_threats) if active_threats else "CLEAN"
|
|
578
|
+
|
|
579
|
+
return {
|
|
580
|
+
"selectors": selectors,
|
|
581
|
+
"honeypot_flags": honeypot_flags,
|
|
582
|
+
"categories": categories,
|
|
583
|
+
"is_honeypot": is_honeypot,
|
|
584
|
+
"severity": severity,
|
|
585
|
+
"summary_display": summary_display,
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def create_dex_pool_rule_payload(
|
|
590
|
+
pool_item: Dict[str, Any],
|
|
591
|
+
analysis: Dict[str, Any],
|
|
592
|
+
) -> ConditionRulePayload:
|
|
593
|
+
"""
|
|
594
|
+
Constructs a validated ConditionRulePayload for evaluating a DEX liquidity pool.
|
|
595
|
+
"""
|
|
596
|
+
target_token = Web3.to_checksum_address(pool_item["target_token"])
|
|
597
|
+
pool_address = Web3.to_checksum_address(pool_item["pool_address"])
|
|
598
|
+
dex_name = pool_item["dex"]
|
|
599
|
+
pair_name = pool_item["pair_name"]
|
|
600
|
+
block_num = pool_item.get("block_number", 0)
|
|
601
|
+
tx_hash = pool_item.get("tx_hash", "0x")
|
|
602
|
+
honeypot_flags = analysis.get("honeypot_flags", [])
|
|
603
|
+
|
|
604
|
+
# Select representative selector
|
|
605
|
+
matched_selector = "0x"
|
|
606
|
+
matched_signature = "erc20_transfer"
|
|
607
|
+
for s in analysis["selectors"]:
|
|
608
|
+
if s["selector"] in HONEYPOT_SELECTORS:
|
|
609
|
+
matched_selector = s["selector"]
|
|
610
|
+
matched_signature = s["signature"]
|
|
611
|
+
break
|
|
612
|
+
|
|
613
|
+
threat_notes = f"CRITICAL HONEYPOT WARNING: {', '.join(honeypot_flags)}" if honeypot_flags else "Standard token implementation without honeypot patterns."
|
|
614
|
+
|
|
615
|
+
prompt = (
|
|
616
|
+
f"Audit newly created DEX liquidity pool on {dex_name} for pair {pair_name}. "
|
|
617
|
+
f"Pool Contract: {pool_address}, Target Token: {target_token}. "
|
|
618
|
+
f"Honeypot/Risk indicators detected: {', '.join(honeypot_flags) if honeypot_flags else 'None (Clean)'}. "
|
|
619
|
+
f"Evaluate blacklist restrictions, arbitrary 100% transfer tax, trading lockup, and admin selfdestruct risks."
|
|
620
|
+
)
|
|
621
|
+
|
|
622
|
+
rule_id = f"dex-pool-{target_token.lower()[:10]}"
|
|
623
|
+
|
|
624
|
+
return ConditionRulePayload(
|
|
625
|
+
rule_id=rule_id,
|
|
626
|
+
chain_id=ChainId.BASE_MAINNET,
|
|
627
|
+
deterministic=DeterministicCondition(
|
|
628
|
+
target_address=target_token,
|
|
629
|
+
min_value_wei=0,
|
|
630
|
+
required_function_selectors=None,
|
|
631
|
+
check_native_balance=False,
|
|
632
|
+
),
|
|
633
|
+
semantic=SemanticCondition(
|
|
634
|
+
enabled=True,
|
|
635
|
+
policy_prompt=prompt,
|
|
636
|
+
risk_threshold=7.0,
|
|
637
|
+
),
|
|
638
|
+
context_metadata={
|
|
639
|
+
"dex": dex_name,
|
|
640
|
+
"pool_address": pool_address,
|
|
641
|
+
"target_token": target_token,
|
|
642
|
+
"base_token": pool_item.get("base_token"),
|
|
643
|
+
"pair": pair_name,
|
|
644
|
+
"block_number": block_num,
|
|
645
|
+
"tx_hash": tx_hash,
|
|
646
|
+
"honeypot_flags": honeypot_flags,
|
|
647
|
+
"honeypot_count": len(honeypot_flags),
|
|
648
|
+
"is_honeypot_suspect": analysis.get("is_honeypot", False),
|
|
649
|
+
"calldata": matched_selector,
|
|
650
|
+
"calldata_analysis": {
|
|
651
|
+
"selector": matched_selector,
|
|
652
|
+
"signature": matched_signature,
|
|
653
|
+
},
|
|
654
|
+
"proposal_title": f"DEX Pool Audit: {pair_name} on {dex_name}",
|
|
655
|
+
"proposal_description": (
|
|
656
|
+
f"Liquidity pool created at block {block_num} on {dex_name}. "
|
|
657
|
+
f"Pair: {pair_name}. Pool Address: {pool_address}. Target Token: {target_token}. "
|
|
658
|
+
f"{threat_notes}"
|
|
659
|
+
),
|
|
660
|
+
"selectors_found": [s["selector"] for s in analysis["selectors"]],
|
|
661
|
+
"signatures_found": [s["signature"] for s in analysis["selectors"]],
|
|
662
|
+
"bytecode_length": len(pool_item.get("bytecode", b"")),
|
|
663
|
+
},
|
|
664
|
+
)
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
class DexWebhookAlertDispatcher:
|
|
668
|
+
"""
|
|
669
|
+
Dispatches formatted security alert webhooks (Discord / Slack / Generic HTTP POST)
|
|
670
|
+
for high-risk pools or newly detected honeypots.
|
|
671
|
+
"""
|
|
672
|
+
|
|
673
|
+
def __init__(self, webhook_url: Optional[str] = None, timeout: float = 10.0):
|
|
674
|
+
self.webhook_url = webhook_url or os.getenv("WEBHOOK_URL") or os.getenv("DEX_WEBHOOK_URL")
|
|
675
|
+
self.timeout = timeout
|
|
676
|
+
|
|
677
|
+
def format_alert_payload(self, result: Dict[str, Any]) -> Dict[str, Any]:
|
|
678
|
+
"""Formats the result dictionary into a structured webhook alert payload."""
|
|
679
|
+
dex = result.get("dex", "DEX")
|
|
680
|
+
pair = result.get("pair", "N/A")
|
|
681
|
+
pool_addr = result.get("pool_address", "N/A")
|
|
682
|
+
target_token = result.get("target_token", "N/A")
|
|
683
|
+
risk = result.get("risk_honeypot", "CLEAN")
|
|
684
|
+
decision = result.get("decision", "MANUAL_REVIEW")
|
|
685
|
+
score = result.get("risk_score", 0.0)
|
|
686
|
+
block = result.get("block_number", 0)
|
|
687
|
+
|
|
688
|
+
color = 0xFF0000 if decision == "REJECT" else (0xFFA500 if decision == "MANUAL_REVIEW" else 0x00FF00)
|
|
689
|
+
|
|
690
|
+
content = (
|
|
691
|
+
f"🚨 **DEX LIQUIDITY POOL SECURITY AUDIT [{decision}]** 🚨\n"
|
|
692
|
+
f"• **DEX**: `{dex}`\n"
|
|
693
|
+
f"• **Pair**: `{pair}`\n"
|
|
694
|
+
f"• **Pool Address**: `{pool_addr}`\n"
|
|
695
|
+
f"• **Target Token**: `{target_token}`\n"
|
|
696
|
+
f"• **Honeypot / Risk**: `{risk}`\n"
|
|
697
|
+
f"• **Decision**: `{decision}` (Risk Score: `{score:.1f}`)\n"
|
|
698
|
+
f"• **Block**: `{block}`"
|
|
699
|
+
)
|
|
700
|
+
|
|
701
|
+
embeds = [
|
|
702
|
+
{
|
|
703
|
+
"title": f"[{decision}] {dex}: {pair} Liquidity Pool Audit",
|
|
704
|
+
"color": color,
|
|
705
|
+
"fields": [
|
|
706
|
+
{"name": "DEX", "value": dex, "inline": True},
|
|
707
|
+
{"name": "Pair", "value": pair, "inline": True},
|
|
708
|
+
{"name": "Decision", "value": decision, "inline": True},
|
|
709
|
+
{"name": "Risk Score", "value": f"{score:.1f}", "inline": True},
|
|
710
|
+
{"name": "Honeypot / Risk", "value": risk, "inline": False},
|
|
711
|
+
{"name": "Target Token", "value": target_token, "inline": False},
|
|
712
|
+
{"name": "Pool Address", "value": pool_addr, "inline": False},
|
|
713
|
+
],
|
|
714
|
+
}
|
|
715
|
+
]
|
|
716
|
+
|
|
717
|
+
return {
|
|
718
|
+
"content": content,
|
|
719
|
+
"text": content,
|
|
720
|
+
"embeds": embeds,
|
|
721
|
+
"dex": dex,
|
|
722
|
+
"pair": pair,
|
|
723
|
+
"target_token": target_token,
|
|
724
|
+
"decision": decision,
|
|
725
|
+
"risk_score": score,
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
async def dispatch_alert(self, result: Dict[str, Any]) -> bool:
|
|
729
|
+
"""Sends an HTTP POST alert to the configured webhook endpoint."""
|
|
730
|
+
if not self.webhook_url:
|
|
731
|
+
return False
|
|
732
|
+
|
|
733
|
+
payload = self.format_alert_payload(result)
|
|
734
|
+
try:
|
|
735
|
+
if httpx is not None:
|
|
736
|
+
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
737
|
+
resp = await client.post(self.webhook_url, json=payload)
|
|
738
|
+
return resp.status_code in (200, 204)
|
|
739
|
+
else:
|
|
740
|
+
logger.warning("httpx not available; webhook dispatch skipped.")
|
|
741
|
+
return False
|
|
742
|
+
except Exception as exc:
|
|
743
|
+
logger.warning(f"Failed to dispatch webhook alert: {exc}")
|
|
744
|
+
return False
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
async def scan_pool_events(
|
|
748
|
+
w3: AsyncWeb3,
|
|
749
|
+
from_block: int,
|
|
750
|
+
to_block: int,
|
|
751
|
+
limit: int = 10,
|
|
752
|
+
) -> List[Dict[str, Any]]:
|
|
753
|
+
"""
|
|
754
|
+
Discovers newly created liquidity pools on Base Mainnet across Aerodrome and Uniswap v3
|
|
755
|
+
via cost-free eth_getLogs RPC filters.
|
|
756
|
+
|
|
757
|
+
Decodes indexed token0 and token1, identifies unverified target tokens vs base assets,
|
|
758
|
+
retrieves deployed token bytecode, and returns standardized pool discovery dicts.
|
|
759
|
+
"""
|
|
760
|
+
if limit <= 0 or from_block > to_block:
|
|
761
|
+
return []
|
|
762
|
+
|
|
763
|
+
logger.info(
|
|
764
|
+
f"Scanning DEX pool events from block {from_block} to {to_block} (limit {limit})..."
|
|
765
|
+
)
|
|
766
|
+
|
|
767
|
+
# 1. Concurrently query Aerodrome and Uniswap v3 Factory logs
|
|
768
|
+
aero_filter = {
|
|
769
|
+
"fromBlock": from_block,
|
|
770
|
+
"toBlock": to_block,
|
|
771
|
+
"address": AERODROME_FACTORY_ADDRESS,
|
|
772
|
+
"topics": [AERODROME_POOL_CREATED_TOPIC0],
|
|
773
|
+
}
|
|
774
|
+
uni_filter = {
|
|
775
|
+
"fromBlock": from_block,
|
|
776
|
+
"toBlock": to_block,
|
|
777
|
+
"address": UNISWAP_V3_FACTORY_ADDRESS,
|
|
778
|
+
"topics": [UNISWAP_V3_POOL_CREATED_TOPIC0],
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
try:
|
|
782
|
+
aero_res, uni_res = await asyncio.gather(
|
|
783
|
+
w3.eth.get_logs(aero_filter),
|
|
784
|
+
w3.eth.get_logs(uni_filter),
|
|
785
|
+
return_exceptions=True,
|
|
786
|
+
)
|
|
787
|
+
except Exception as exc:
|
|
788
|
+
logger.error(f"Error querying logs from RPC: {exc}")
|
|
789
|
+
return []
|
|
790
|
+
|
|
791
|
+
raw_logs: List[Tuple[str, Any]] = []
|
|
792
|
+
if isinstance(aero_res, list):
|
|
793
|
+
for log in aero_res:
|
|
794
|
+
raw_logs.append(("Aerodrome", log))
|
|
795
|
+
elif isinstance(aero_res, Exception):
|
|
796
|
+
logger.warning(f"Aerodrome logs query failed: {aero_res}")
|
|
797
|
+
|
|
798
|
+
if isinstance(uni_res, list):
|
|
799
|
+
for log in uni_res:
|
|
800
|
+
raw_logs.append(("Uniswap v3", log))
|
|
801
|
+
elif isinstance(uni_res, Exception):
|
|
802
|
+
logger.warning(f"Uniswap v3 logs query failed: {uni_res}")
|
|
803
|
+
|
|
804
|
+
# Sort logs by blockNumber descending, then logIndex descending
|
|
805
|
+
def log_sort_key(item: Tuple[str, Any]) -> Tuple[int, int]:
|
|
806
|
+
log = item[1]
|
|
807
|
+
b_num = log.get("blockNumber", 0) if isinstance(log, dict) else getattr(log, "blockNumber", 0)
|
|
808
|
+
l_idx = log.get("logIndex", 0) if isinstance(log, dict) else getattr(log, "logIndex", 0)
|
|
809
|
+
return (int(b_num or 0), int(l_idx or 0))
|
|
810
|
+
|
|
811
|
+
raw_logs.sort(key=log_sort_key, reverse=True)
|
|
812
|
+
|
|
813
|
+
discovered: List[Dict[str, Any]] = []
|
|
814
|
+
|
|
815
|
+
for dex_name, log in raw_logs:
|
|
816
|
+
if len(discovered) >= limit:
|
|
817
|
+
break
|
|
818
|
+
|
|
819
|
+
topics = log.get("topics", []) if isinstance(log, dict) else getattr(log, "topics", [])
|
|
820
|
+
data = log.get("data", "0x") if isinstance(log, dict) else getattr(log, "data", "0x")
|
|
821
|
+
block_num = log.get("blockNumber", 0) if isinstance(log, dict) else getattr(log, "blockNumber", 0)
|
|
822
|
+
tx_hash_val = log.get("transactionHash", "0x") if isinstance(log, dict) else getattr(log, "transactionHash", "0x")
|
|
823
|
+
tx_hash = tx_hash_val.hex() if hasattr(tx_hash_val, "hex") else str(tx_hash_val)
|
|
824
|
+
|
|
825
|
+
if len(topics) < 3:
|
|
826
|
+
continue
|
|
827
|
+
|
|
828
|
+
try:
|
|
829
|
+
token0 = decode_address_from_topic(topics[1])
|
|
830
|
+
token1 = decode_address_from_topic(topics[2])
|
|
831
|
+
except Exception as exc:
|
|
832
|
+
logger.warning(f"Failed to decode token addresses from topics: {exc}")
|
|
833
|
+
continue
|
|
834
|
+
|
|
835
|
+
if dex_name == "Aerodrome":
|
|
836
|
+
pool_address, stable = decode_aerodrome_pool_data(data)
|
|
837
|
+
extra_meta = {"stable": stable}
|
|
838
|
+
else:
|
|
839
|
+
pool_address, fee, tick_spacing = decode_univ3_pool_data(data)
|
|
840
|
+
extra_meta = {"fee": fee, "tick_spacing": tick_spacing}
|
|
841
|
+
|
|
842
|
+
target_token, base_token, pair_name = identify_target_token(token0, token1)
|
|
843
|
+
|
|
844
|
+
# Retrieve bytecode of the target unverified token
|
|
845
|
+
try:
|
|
846
|
+
bytecode = await w3.eth.get_code(target_token)
|
|
847
|
+
except Exception as exc:
|
|
848
|
+
logger.warning(f"Failed to fetch bytecode for target token {target_token}: {exc}")
|
|
849
|
+
bytecode = b""
|
|
850
|
+
|
|
851
|
+
discovered.append({
|
|
852
|
+
"dex": dex_name,
|
|
853
|
+
"block_number": int(block_num or 0),
|
|
854
|
+
"tx_hash": tx_hash,
|
|
855
|
+
"pool_address": pool_address,
|
|
856
|
+
"token0": token0,
|
|
857
|
+
"token1": token1,
|
|
858
|
+
"target_token": target_token,
|
|
859
|
+
"base_token": base_token,
|
|
860
|
+
"pair_name": pair_name,
|
|
861
|
+
"bytecode": bytecode,
|
|
862
|
+
"extra_meta": extra_meta,
|
|
863
|
+
})
|
|
864
|
+
logger.info(
|
|
865
|
+
f"Discovered {dex_name} pool: {pair_name} ({pool_address}) at block {block_num}"
|
|
866
|
+
)
|
|
867
|
+
|
|
868
|
+
return discovered
|
|
869
|
+
|
|
870
|
+
|
|
871
|
+
class DexSemanticEvaluator(MockSemanticEvaluator):
|
|
872
|
+
"""
|
|
873
|
+
Subclasses MockSemanticEvaluator to simulate Honeypot reasoning and risk scoring
|
|
874
|
+
offline without incurring external LLM API cost.
|
|
875
|
+
"""
|
|
876
|
+
|
|
877
|
+
async def evaluate(
|
|
878
|
+
self,
|
|
879
|
+
condition: SemanticCondition,
|
|
880
|
+
observed_onchain: Dict[str, Any],
|
|
881
|
+
metadata: Optional[Dict[str, Any]] = None,
|
|
882
|
+
context: Optional[Dict[str, Any]] = None,
|
|
883
|
+
):
|
|
884
|
+
result = await super().evaluate(condition, observed_onchain, metadata, context)
|
|
885
|
+
ctx = metadata if metadata is not None else (context or {})
|
|
886
|
+
honeypot_flags = ctx.get("honeypot_flags", [])
|
|
887
|
+
|
|
888
|
+
if honeypot_flags:
|
|
889
|
+
score = max(result.risk_score, 8.5 + min(1.5, len(honeypot_flags) * 0.3))
|
|
890
|
+
score = min(10.0, score)
|
|
891
|
+
flagged = list(result.flagged_issues) + [f"Honeypot Flag: {f}" for f in honeypot_flags]
|
|
892
|
+
return result.model_copy(
|
|
893
|
+
update={
|
|
894
|
+
"risk_score": score,
|
|
895
|
+
"recommended_action": "REJECT",
|
|
896
|
+
"conditions_met": True,
|
|
897
|
+
"flagged_issues": flagged,
|
|
898
|
+
"summary": f"CRITICAL HONEYPOT DETECTED: {', '.join(honeypot_flags)}. " + result.summary,
|
|
899
|
+
}
|
|
900
|
+
)
|
|
901
|
+
return result
|
|
902
|
+
|
|
903
|
+
|
|
904
|
+
async def audit_discovered_pools(
|
|
905
|
+
pools: List[Dict[str, Any]],
|
|
906
|
+
engine: ConditionAgentEngine,
|
|
907
|
+
rpc_url: Optional[str] = None,
|
|
908
|
+
webhook_dispatcher: Optional[DexWebhookAlertDispatcher] = None,
|
|
909
|
+
) -> List[Dict[str, Any]]:
|
|
910
|
+
"""
|
|
911
|
+
Executes honeypot bytecode analysis and two-stage deterministic/semantic risk evaluation
|
|
912
|
+
for all discovered DEX liquidity pools. Persists audit reports to SQLite via AgentStorage.
|
|
913
|
+
"""
|
|
914
|
+
results: List[Dict[str, Any]] = []
|
|
915
|
+
|
|
916
|
+
for item in pools:
|
|
917
|
+
target_token = item["target_token"]
|
|
918
|
+
bytecode = item.get("bytecode", b"")
|
|
919
|
+
bytecode_bytes = bytecode if isinstance(bytecode, bytes) else bytes.fromhex(
|
|
920
|
+
bytecode[2:] if bytecode.startswith("0x") else bytecode
|
|
921
|
+
)
|
|
922
|
+
|
|
923
|
+
# 1. Analyze bytecode for honeypot traps
|
|
924
|
+
analysis = analyze_bytecode_honeypot(bytecode_bytes)
|
|
925
|
+
|
|
926
|
+
# 2. Populate ChainInspector cache to guarantee zero redundant RPC calls
|
|
927
|
+
ChainInspector._set_bytecode_cache(f"{CHAIN_ID_BASE_MAINNET}:{target_token}", bytecode_bytes)
|
|
928
|
+
|
|
929
|
+
# 3. Create validated condition rule payload
|
|
930
|
+
payload = create_dex_pool_rule_payload(item, analysis)
|
|
931
|
+
|
|
932
|
+
# 4. Execute ConditionAgentEngine two-stage audit
|
|
933
|
+
try:
|
|
934
|
+
response = await engine.process_rule(payload, source="dex_pool_monitor")
|
|
935
|
+
except Exception as exc:
|
|
936
|
+
logger.error(f"Audit failed for pool {item['pool_address']} / token {target_token}: {exc}")
|
|
937
|
+
continue
|
|
938
|
+
|
|
939
|
+
sem = response.semantic_Evaluation
|
|
940
|
+
if analysis["is_honeypot"]:
|
|
941
|
+
decision = "REJECT"
|
|
942
|
+
risk_score = max(sem.risk_score if sem else 9.0, 9.0)
|
|
943
|
+
else:
|
|
944
|
+
decision = sem.recommended_action if sem else ("APPROVE" if response.deterministic_check.passed else "REJECT")
|
|
945
|
+
risk_score = sem.risk_score if sem else (2.0 if response.deterministic_check.passed else 10.0)
|
|
946
|
+
|
|
947
|
+
# Response is already recorded in AgentStorage by engine.process_rule(..., source="dex_pool_monitor")
|
|
948
|
+
|
|
949
|
+
audit_entry = {
|
|
950
|
+
"dex": item["dex"],
|
|
951
|
+
"block_number": item["block_number"],
|
|
952
|
+
"pair": item["pair_name"],
|
|
953
|
+
"pool_address": item["pool_address"],
|
|
954
|
+
"target_token": target_token,
|
|
955
|
+
"base_token": item.get("base_token"),
|
|
956
|
+
"risk_honeypot": analysis["summary_display"],
|
|
957
|
+
"honeypot_flags": analysis["honeypot_flags"],
|
|
958
|
+
"decision": decision,
|
|
959
|
+
"risk_score": risk_score,
|
|
960
|
+
"payload": payload,
|
|
961
|
+
"response": response,
|
|
962
|
+
}
|
|
963
|
+
results.append(audit_entry)
|
|
964
|
+
|
|
965
|
+
# Dispatch webhook alert if configured
|
|
966
|
+
if webhook_dispatcher and (decision == "REJECT" or risk_score >= 7.0):
|
|
967
|
+
try:
|
|
968
|
+
await webhook_dispatcher.dispatch_alert(audit_entry)
|
|
969
|
+
except Exception as exc:
|
|
970
|
+
logger.warning(f"Webhook dispatch failed: {exc}")
|
|
971
|
+
|
|
972
|
+
return results
|
|
973
|
+
|
|
974
|
+
|
|
975
|
+
def print_dex_table(results: List[Dict[str, Any]]) -> None:
|
|
976
|
+
"""
|
|
977
|
+
Renders an ASCII table displaying audited DEX liquidity pools:
|
|
978
|
+
DEX | Bloco | Par / Pool | Token Alvo | Risco / Honeypot | Decisão | Score
|
|
979
|
+
"""
|
|
980
|
+
headers = [
|
|
981
|
+
"DEX",
|
|
982
|
+
"Bloco",
|
|
983
|
+
"Par / Pool",
|
|
984
|
+
"Token Alvo",
|
|
985
|
+
"Risco / Honeypot",
|
|
986
|
+
"Decisão",
|
|
987
|
+
"Score",
|
|
988
|
+
]
|
|
989
|
+
rows = []
|
|
990
|
+
for r in results:
|
|
991
|
+
dex = str(r.get("dex", "N/A"))
|
|
992
|
+
block = str(r.get("block_number", "N/A"))
|
|
993
|
+
pair = str(r.get("pair", "N/A"))
|
|
994
|
+
token_target = str(r.get("target_token", "N/A"))
|
|
995
|
+
risk = str(r.get("risk_honeypot", "CLEAN"))
|
|
996
|
+
decision = str(r.get("decision", "N/A"))
|
|
997
|
+
risk_score = r.get("risk_score")
|
|
998
|
+
score_display = f"{float(risk_score):.1f}" if risk_score is not None else "N/A"
|
|
999
|
+
|
|
1000
|
+
if len(risk) > 28:
|
|
1001
|
+
risk = risk[:25] + "..."
|
|
1002
|
+
|
|
1003
|
+
rows.append([
|
|
1004
|
+
dex,
|
|
1005
|
+
block,
|
|
1006
|
+
pair,
|
|
1007
|
+
token_target,
|
|
1008
|
+
risk,
|
|
1009
|
+
decision,
|
|
1010
|
+
score_display,
|
|
1011
|
+
])
|
|
1012
|
+
|
|
1013
|
+
col_widths = [len(h) for h in headers]
|
|
1014
|
+
for row in rows:
|
|
1015
|
+
for idx, val in enumerate(row):
|
|
1016
|
+
col_widths[idx] = max(col_widths[idx], len(val))
|
|
1017
|
+
|
|
1018
|
+
separator = "+" + "+".join("-" * (w + 2) for w in col_widths) + "+"
|
|
1019
|
+
header_str = "|" + "|".join(f" {headers[i].ljust(col_widths[i])} " for i in range(len(headers))) + "|"
|
|
1020
|
+
|
|
1021
|
+
print("\n" + separator)
|
|
1022
|
+
print(header_str)
|
|
1023
|
+
print(separator)
|
|
1024
|
+
if rows:
|
|
1025
|
+
for row in rows:
|
|
1026
|
+
print("|" + "|".join(f" {row[i].ljust(col_widths[i])} " for i in range(len(row))) + "|")
|
|
1027
|
+
else:
|
|
1028
|
+
empty_msg = "No DEX liquidity pool events detected in the scanned block range."
|
|
1029
|
+
print(f"| {empty_msg.ljust(sum(col_widths) + len(col_widths) * 3 - 3)} |")
|
|
1030
|
+
print(separator + "\n")
|
|
1031
|
+
|
|
1032
|
+
|
|
1033
|
+
def get_curated_mock_pools() -> List[Dict[str, Any]]:
|
|
1034
|
+
"""
|
|
1035
|
+
Returns curated mock pools representing diverse token profiles (clean ERC-20, blacklist traps,
|
|
1036
|
+
100% tax traps, pause/kill honeypots, and upgradable proxies) for offline dry-run simulations.
|
|
1037
|
+
"""
|
|
1038
|
+
clean_token_addr = Web3.to_checksum_address("0x1111111111111111111111111111111111111111")
|
|
1039
|
+
blacklist_token_addr = Web3.to_checksum_address("0x2222222222222222222222222222222222222222")
|
|
1040
|
+
tax_token_addr = Web3.to_checksum_address("0x3333333333333333333333333333333333333333")
|
|
1041
|
+
pause_token_addr = Web3.to_checksum_address("0x4444444444444444444444444444444444444444")
|
|
1042
|
+
proxy_token_addr = Web3.to_checksum_address("0x5555555555555555555555555555555555555555")
|
|
1043
|
+
|
|
1044
|
+
weth_addr = Web3.to_checksum_address("0x4200000000000000000000000000000000000006")
|
|
1045
|
+
usdc_addr = Web3.to_checksum_address("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913")
|
|
1046
|
+
cbbtc_addr = Web3.to_checksum_address("0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf")
|
|
1047
|
+
usdbc_addr = Web3.to_checksum_address("0xd9aAEc86B65D86f6A7B5B1b0c42FFA531710b6CA")
|
|
1048
|
+
|
|
1049
|
+
# Bytecodes:
|
|
1050
|
+
# 1. Clean ERC-20 (transfer, balanceOf, approve)
|
|
1051
|
+
clean_code = bytes.fromhex("608060405234801561001057600080fd5b508063a9059cbb1461002057806370a0823114")
|
|
1052
|
+
# 2. Blacklist Honeypot (setBlacklist: 0x40af1275, isBlacklisted: 0xf9f02b01, transferOwnership: 0xf2fde38b)
|
|
1053
|
+
bl_code = bytes.fromhex("6080604052806340af127514610020578063f9f02b0114610040578063f2fde38b14")
|
|
1054
|
+
# 3. Arbitrary Fee / 100% Tax Trap (setTax: 0x1e3dd19f, setSellFee: 0x4b7890ec, setFee: 0x8a92d475)
|
|
1055
|
+
tax_code = bytes.fromhex("608060405280631e3dd19f146100205780634b7890ec146100405780638a92d47514")
|
|
1056
|
+
# 4. Trading Pause + Selfdestruct (setTrading: 0x34468f9b, pause: 0x4fbee1e3, selfdestruct: 0x00f714ce, ff)
|
|
1057
|
+
pause_code = bytes.fromhex("6080604052806334468f9b146100205780634fbee1e31461004057806300f714ce14ff")
|
|
1058
|
+
# 5. Upgradable / Mintable Admin Token (upgradeTo: 0x3659cfe6, mint: 0x40c10f19, transferOwnership: 0xf2fde38b)
|
|
1059
|
+
proxy_code = bytes.fromhex("608060405280633659cfe61461002057806340c10f1914610040578063f2fde38b14")
|
|
1060
|
+
|
|
1061
|
+
return [
|
|
1062
|
+
{
|
|
1063
|
+
"dex": "Aerodrome",
|
|
1064
|
+
"block_number": 21050100,
|
|
1065
|
+
"tx_hash": "0x1111111111111111111111111111111111111111111111111111111111111111",
|
|
1066
|
+
"pool_address": Web3.to_checksum_address("0xae11111111111111111111111111111111111111"),
|
|
1067
|
+
"token0": clean_token_addr,
|
|
1068
|
+
"token1": weth_addr,
|
|
1069
|
+
"target_token": clean_token_addr,
|
|
1070
|
+
"base_token": weth_addr,
|
|
1071
|
+
"pair_name": "CLEAN/WETH",
|
|
1072
|
+
"bytecode": clean_code,
|
|
1073
|
+
"extra_meta": {"stable": False},
|
|
1074
|
+
},
|
|
1075
|
+
{
|
|
1076
|
+
"dex": "Aerodrome",
|
|
1077
|
+
"block_number": 21050102,
|
|
1078
|
+
"tx_hash": "0x2222222222222222222222222222222222222222222222222222222222222222",
|
|
1079
|
+
"pool_address": Web3.to_checksum_address("0xae22222222222222222222222222222222222222"),
|
|
1080
|
+
"token0": usdc_addr,
|
|
1081
|
+
"token1": blacklist_token_addr,
|
|
1082
|
+
"target_token": blacklist_token_addr,
|
|
1083
|
+
"base_token": usdc_addr,
|
|
1084
|
+
"pair_name": "HONEY_BL/USDC",
|
|
1085
|
+
"bytecode": bl_code,
|
|
1086
|
+
"extra_meta": {"stable": True},
|
|
1087
|
+
},
|
|
1088
|
+
{
|
|
1089
|
+
"dex": "Uniswap v3",
|
|
1090
|
+
"block_number": 21050105,
|
|
1091
|
+
"tx_hash": "0x3333333333333333333333333333333333333333333333333333333333333333",
|
|
1092
|
+
"pool_address": Web3.to_checksum_address("0xbb33333333333333333333333333333333333333"),
|
|
1093
|
+
"token0": weth_addr,
|
|
1094
|
+
"token1": tax_token_addr,
|
|
1095
|
+
"target_token": tax_token_addr,
|
|
1096
|
+
"base_token": weth_addr,
|
|
1097
|
+
"pair_name": "TAX100/WETH",
|
|
1098
|
+
"bytecode": tax_code,
|
|
1099
|
+
"extra_meta": {"fee": 10000, "tick_spacing": 200},
|
|
1100
|
+
},
|
|
1101
|
+
{
|
|
1102
|
+
"dex": "Uniswap v3",
|
|
1103
|
+
"block_number": 21050108,
|
|
1104
|
+
"tx_hash": "0x4444444444444444444444444444444444444444444444444444444444444444",
|
|
1105
|
+
"pool_address": Web3.to_checksum_address("0xbb44444444444444444444444444444444444444"),
|
|
1106
|
+
"token0": pause_token_addr,
|
|
1107
|
+
"token1": cbbtc_addr,
|
|
1108
|
+
"target_token": pause_token_addr,
|
|
1109
|
+
"base_token": cbbtc_addr,
|
|
1110
|
+
"pair_name": "RUG_KILL/cbBTC",
|
|
1111
|
+
"bytecode": pause_code,
|
|
1112
|
+
"extra_meta": {"fee": 3000, "tick_spacing": 60},
|
|
1113
|
+
},
|
|
1114
|
+
{
|
|
1115
|
+
"dex": "Uniswap v3",
|
|
1116
|
+
"block_number": 21050110,
|
|
1117
|
+
"tx_hash": "0x5555555555555555555555555555555555555555555555555555555555555555",
|
|
1118
|
+
"pool_address": Web3.to_checksum_address("0xbb55555555555555555555555555555555555555"),
|
|
1119
|
+
"token0": proxy_token_addr,
|
|
1120
|
+
"token1": usdbc_addr,
|
|
1121
|
+
"target_token": proxy_token_addr,
|
|
1122
|
+
"base_token": usdbc_addr,
|
|
1123
|
+
"pair_name": "PROXY/USDbC",
|
|
1124
|
+
"bytecode": proxy_code,
|
|
1125
|
+
"extra_meta": {"fee": 500, "tick_spacing": 10},
|
|
1126
|
+
},
|
|
1127
|
+
]
|
|
1128
|
+
|
|
1129
|
+
|
|
1130
|
+
class AwaitableBlockNumber:
|
|
1131
|
+
"""Supports both direct awaiting (await w3.eth.block_number) and calling (await w3.eth.block_number())."""
|
|
1132
|
+
def __init__(self, value: int):
|
|
1133
|
+
self.value = value
|
|
1134
|
+
|
|
1135
|
+
def __await__(self):
|
|
1136
|
+
async def _gen():
|
|
1137
|
+
return self.value
|
|
1138
|
+
return _gen().__await__()
|
|
1139
|
+
|
|
1140
|
+
def __call__(self, *args, **kwargs):
|
|
1141
|
+
async def _coro():
|
|
1142
|
+
return self.value
|
|
1143
|
+
return _coro()
|
|
1144
|
+
|
|
1145
|
+
def __gt__(self, other):
|
|
1146
|
+
return self.value > (other.value if isinstance(other, AwaitableBlockNumber) else other)
|
|
1147
|
+
|
|
1148
|
+
def __ge__(self, other):
|
|
1149
|
+
return self.value >= (other.value if isinstance(other, AwaitableBlockNumber) else other)
|
|
1150
|
+
|
|
1151
|
+
def __lt__(self, other):
|
|
1152
|
+
return self.value < (other.value if isinstance(other, AwaitableBlockNumber) else other)
|
|
1153
|
+
|
|
1154
|
+
def __le__(self, other):
|
|
1155
|
+
return self.value <= (other.value if isinstance(other, AwaitableBlockNumber) else other)
|
|
1156
|
+
|
|
1157
|
+
def __eq__(self, other):
|
|
1158
|
+
return self.value == (other.value if isinstance(other, AwaitableBlockNumber) else other)
|
|
1159
|
+
|
|
1160
|
+
def __int__(self):
|
|
1161
|
+
return int(self.value)
|
|
1162
|
+
|
|
1163
|
+
|
|
1164
|
+
async def get_latest_block_number(w3: Any) -> int:
|
|
1165
|
+
"""Safely retrieves the latest block number supporting Web3 properties, callables, or mocks."""
|
|
1166
|
+
bn_target = getattr(w3.eth, "block_number", None)
|
|
1167
|
+
if inspect.isawaitable(bn_target):
|
|
1168
|
+
val = await bn_target
|
|
1169
|
+
elif callable(bn_target):
|
|
1170
|
+
res = bn_target()
|
|
1171
|
+
val = await res if inspect.isawaitable(res) else res
|
|
1172
|
+
else:
|
|
1173
|
+
val = bn_target
|
|
1174
|
+
return int(val)
|
|
1175
|
+
|
|
1176
|
+
|
|
1177
|
+
def create_mock_w3(mock_pools: Optional[List[Dict[str, Any]]] = None) -> Any:
|
|
1178
|
+
"""Creates a mock AsyncWeb3 connection preloaded with synthetic event logs."""
|
|
1179
|
+
pools = mock_pools if mock_pools is not None else get_curated_mock_pools()
|
|
1180
|
+
mock_w3 = MagicMock()
|
|
1181
|
+
mock_w3.is_connected = AsyncMock(return_value=True)
|
|
1182
|
+
|
|
1183
|
+
max_block = max((p["block_number"] for p in pools), default=21050110)
|
|
1184
|
+
mock_w3.eth.block_number = AwaitableBlockNumber(max_block + 1)
|
|
1185
|
+
|
|
1186
|
+
async def mock_get_logs(filter_params: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
1187
|
+
target_addr = filter_params.get("address")
|
|
1188
|
+
target_topic0 = filter_params.get("topics", [None])[0]
|
|
1189
|
+
|
|
1190
|
+
res = []
|
|
1191
|
+
for p in pools:
|
|
1192
|
+
is_aero = p["dex"] == "Aerodrome"
|
|
1193
|
+
match_addr = (
|
|
1194
|
+
target_addr.lower() == AERODROME_FACTORY_ADDRESS.lower()
|
|
1195
|
+
if is_aero
|
|
1196
|
+
else target_addr.lower() == UNISWAP_V3_FACTORY_ADDRESS.lower()
|
|
1197
|
+
)
|
|
1198
|
+
match_topic = (
|
|
1199
|
+
target_topic0 == AERODROME_POOL_CREATED_TOPIC0
|
|
1200
|
+
if is_aero
|
|
1201
|
+
else target_topic0 == UNISWAP_V3_POOL_CREATED_TOPIC0
|
|
1202
|
+
)
|
|
1203
|
+
|
|
1204
|
+
if match_addr and match_topic:
|
|
1205
|
+
t0_padded = "0x" + "0" * 24 + p["token0"][2:].lower()
|
|
1206
|
+
t1_padded = "0x" + "0" * 24 + p["token1"][2:].lower()
|
|
1207
|
+
pool_padded = "0" * 24 + p["pool_address"][2:].lower()
|
|
1208
|
+
|
|
1209
|
+
if is_aero:
|
|
1210
|
+
stable_word = "0" * 63 + ("1" if p["extra_meta"].get("stable") else "0")
|
|
1211
|
+
index_word = "0" * 64
|
|
1212
|
+
data = "0x" + stable_word + pool_padded + index_word
|
|
1213
|
+
else:
|
|
1214
|
+
fee_word = hex(p["extra_meta"].get("fee", 3000))[2:].zfill(64)
|
|
1215
|
+
tick_word = hex(p["extra_meta"].get("tick_spacing", 60) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)[2:].zfill(64)
|
|
1216
|
+
data = "0x" + fee_word + tick_word + pool_padded
|
|
1217
|
+
|
|
1218
|
+
res.append({
|
|
1219
|
+
"address": target_addr,
|
|
1220
|
+
"topics": [target_topic0, t0_padded, t1_padded],
|
|
1221
|
+
"data": data,
|
|
1222
|
+
"blockNumber": p["block_number"],
|
|
1223
|
+
"transactionHash": p["tx_hash"],
|
|
1224
|
+
"logIndex": 0,
|
|
1225
|
+
})
|
|
1226
|
+
return res
|
|
1227
|
+
|
|
1228
|
+
mock_w3.eth.get_logs = AsyncMock(side_effect=mock_get_logs)
|
|
1229
|
+
|
|
1230
|
+
code_map = {p["target_token"].lower(): p["bytecode"] for p in pools}
|
|
1231
|
+
|
|
1232
|
+
async def mock_get_code(addr: str) -> bytes:
|
|
1233
|
+
return code_map.get(addr.lower(), b"")
|
|
1234
|
+
|
|
1235
|
+
mock_w3.eth.get_code = AsyncMock(side_effect=mock_get_code)
|
|
1236
|
+
return mock_w3
|
|
1237
|
+
|
|
1238
|
+
|
|
1239
|
+
async def run_dex_monitor(args: argparse.Namespace) -> List[Dict[str, Any]]:
|
|
1240
|
+
"""Executes a single cycle scan and audit for DEX liquidity pools."""
|
|
1241
|
+
db_path = getattr(args, "db_path", None)
|
|
1242
|
+
storage = AgentStorage(db_path=db_path)
|
|
1243
|
+
await storage.initialize()
|
|
1244
|
+
|
|
1245
|
+
# Use simulated semantic evaluator during offline dry-run or when configured
|
|
1246
|
+
evaluator = DexSemanticEvaluator() if getattr(args, "dry_run", False) else get_semantic_evaluator()
|
|
1247
|
+
rpc_url = getattr(args, "rpc_url", None) or os.getenv("RPC_URL_8453", DEFAULT_BASE_RPC)
|
|
1248
|
+
engine = ConditionAgentEngine(
|
|
1249
|
+
rpc_url=rpc_url,
|
|
1250
|
+
semantic_evaluator=evaluator,
|
|
1251
|
+
storage=storage,
|
|
1252
|
+
)
|
|
1253
|
+
|
|
1254
|
+
webhook_url = getattr(args, "webhook_url", None)
|
|
1255
|
+
webhook_dispatcher = DexWebhookAlertDispatcher(webhook_url=webhook_url) if webhook_url else None
|
|
1256
|
+
|
|
1257
|
+
limit = getattr(args, "limit", 5)
|
|
1258
|
+
num_blocks = getattr(args, "blocks", 100)
|
|
1259
|
+
|
|
1260
|
+
if getattr(args, "dry_run", False):
|
|
1261
|
+
logger.info("Executing dry-run DEX monitor simulation with curated mock pools...")
|
|
1262
|
+
mock_pools = get_curated_mock_pools()[:limit]
|
|
1263
|
+
results = await audit_discovered_pools(
|
|
1264
|
+
mock_pools,
|
|
1265
|
+
engine=engine,
|
|
1266
|
+
rpc_url=rpc_url,
|
|
1267
|
+
webhook_dispatcher=webhook_dispatcher,
|
|
1268
|
+
)
|
|
1269
|
+
print_dex_table(results)
|
|
1270
|
+
return results
|
|
1271
|
+
|
|
1272
|
+
# Live RPC Discovery
|
|
1273
|
+
w3 = AsyncWeb3(AsyncHTTPProvider(rpc_url))
|
|
1274
|
+
try:
|
|
1275
|
+
is_conn = await w3.is_connected()
|
|
1276
|
+
if not is_conn:
|
|
1277
|
+
logger.error(f"Cannot connect to RPC endpoint: {rpc_url}")
|
|
1278
|
+
return []
|
|
1279
|
+
latest_block = await get_latest_block_number(w3)
|
|
1280
|
+
except Exception as exc:
|
|
1281
|
+
logger.error(f"Failed connecting to RPC {rpc_url}: {exc}")
|
|
1282
|
+
return []
|
|
1283
|
+
|
|
1284
|
+
from_block = max(0, latest_block - num_blocks + 1)
|
|
1285
|
+
to_block = latest_block
|
|
1286
|
+
|
|
1287
|
+
discovered = await scan_pool_events(w3, from_block=from_block, to_block=to_block, limit=limit)
|
|
1288
|
+
if not discovered:
|
|
1289
|
+
print_dex_table([])
|
|
1290
|
+
return []
|
|
1291
|
+
|
|
1292
|
+
results = await audit_discovered_pools(
|
|
1293
|
+
discovered,
|
|
1294
|
+
engine=engine,
|
|
1295
|
+
rpc_url=rpc_url,
|
|
1296
|
+
webhook_dispatcher=webhook_dispatcher,
|
|
1297
|
+
)
|
|
1298
|
+
print_dex_table(results)
|
|
1299
|
+
return results
|
|
1300
|
+
|
|
1301
|
+
|
|
1302
|
+
async def run_continuous_monitor(args: argparse.Namespace) -> None:
|
|
1303
|
+
"""Runs a continuous polling daemon loop monitoring newly minted DEX liquidity pools."""
|
|
1304
|
+
poll_interval = getattr(args, "poll_interval", 15)
|
|
1305
|
+
num_blocks = getattr(args, "blocks", 100)
|
|
1306
|
+
rpc_url = getattr(args, "rpc_url", None) or os.getenv("RPC_URL_8453", DEFAULT_BASE_RPC)
|
|
1307
|
+
|
|
1308
|
+
logger.info(
|
|
1309
|
+
f"Starting continuous DEX pool monitoring daemon (poll interval: {poll_interval}s, RPC: {rpc_url})..."
|
|
1310
|
+
)
|
|
1311
|
+
|
|
1312
|
+
w3 = AsyncWeb3(AsyncHTTPProvider(rpc_url))
|
|
1313
|
+
try:
|
|
1314
|
+
latest_block = await get_latest_block_number(w3)
|
|
1315
|
+
last_scanned = max(0, latest_block - num_blocks + 1)
|
|
1316
|
+
except (KeyboardInterrupt, asyncio.CancelledError):
|
|
1317
|
+
logger.info("Continuous monitor terminated.")
|
|
1318
|
+
return
|
|
1319
|
+
except Exception:
|
|
1320
|
+
last_scanned = 0
|
|
1321
|
+
|
|
1322
|
+
while True:
|
|
1323
|
+
try:
|
|
1324
|
+
current_block = await get_latest_block_number(w3)
|
|
1325
|
+
if current_block > last_scanned:
|
|
1326
|
+
from_b = last_scanned + 1
|
|
1327
|
+
to_b = current_block
|
|
1328
|
+
logger.info(f"Polling blocks {from_b} to {to_b}...")
|
|
1329
|
+
scan_args = argparse.Namespace(**vars(args))
|
|
1330
|
+
scan_args.blocks = to_b - from_b + 1
|
|
1331
|
+
await run_dex_monitor(scan_args)
|
|
1332
|
+
last_scanned = to_b
|
|
1333
|
+
else:
|
|
1334
|
+
logger.debug(f"No new blocks produced (current: {current_block}). Waiting...")
|
|
1335
|
+
except (KeyboardInterrupt, asyncio.CancelledError):
|
|
1336
|
+
logger.info("Continuous monitor terminated by user.")
|
|
1337
|
+
break
|
|
1338
|
+
except Exception as exc:
|
|
1339
|
+
logger.error(f"Error in continuous monitor iteration: {exc}")
|
|
1340
|
+
|
|
1341
|
+
await asyncio.sleep(poll_interval)
|
|
1342
|
+
|
|
1343
|
+
|
|
1344
|
+
def parse_args(args: Optional[List[str]] = None) -> argparse.Namespace:
|
|
1345
|
+
"""Parses command-line arguments for scripts/dex_pool_monitor.py."""
|
|
1346
|
+
parser = argparse.ArgumentParser(
|
|
1347
|
+
description="Autonomous DEX Liquidity Pool Monitor & Honeypot Auditor for Base Mainnet (Engine 3)"
|
|
1348
|
+
)
|
|
1349
|
+
parser.add_argument(
|
|
1350
|
+
"--blocks",
|
|
1351
|
+
type=int,
|
|
1352
|
+
default=100,
|
|
1353
|
+
help="Number of recent blocks to scan for PoolCreated events (default: 100)",
|
|
1354
|
+
)
|
|
1355
|
+
parser.add_argument(
|
|
1356
|
+
"--limit",
|
|
1357
|
+
type=int,
|
|
1358
|
+
default=5,
|
|
1359
|
+
help="Maximum number of discovered pools to audit per scan (default: 5)",
|
|
1360
|
+
)
|
|
1361
|
+
parser.add_argument(
|
|
1362
|
+
"--continuous",
|
|
1363
|
+
action="store_true",
|
|
1364
|
+
default=False,
|
|
1365
|
+
help="Run continuous polling daemon mode",
|
|
1366
|
+
)
|
|
1367
|
+
parser.add_argument(
|
|
1368
|
+
"--poll-interval",
|
|
1369
|
+
type=int,
|
|
1370
|
+
default=15,
|
|
1371
|
+
help="Polling interval in seconds for continuous mode (default: 15)",
|
|
1372
|
+
)
|
|
1373
|
+
parser.add_argument(
|
|
1374
|
+
"--dry-run",
|
|
1375
|
+
action="store_true",
|
|
1376
|
+
default=False,
|
|
1377
|
+
help="Simulate scan with curated mock pools (zero RPC calls, zero LLM token cost)",
|
|
1378
|
+
)
|
|
1379
|
+
parser.add_argument(
|
|
1380
|
+
"--rpc-url",
|
|
1381
|
+
type=str,
|
|
1382
|
+
default=None,
|
|
1383
|
+
help="Optional RPC endpoint URL override (defaults to https://mainnet.base.org)",
|
|
1384
|
+
)
|
|
1385
|
+
parser.add_argument(
|
|
1386
|
+
"--webhook-url",
|
|
1387
|
+
type=str,
|
|
1388
|
+
default=None,
|
|
1389
|
+
help="Webhook URL for dispatching security alert notifications",
|
|
1390
|
+
)
|
|
1391
|
+
parser.add_argument(
|
|
1392
|
+
"--db-path",
|
|
1393
|
+
type=str,
|
|
1394
|
+
default=None,
|
|
1395
|
+
help="Path to SQLite ledger database (default: data/agent.db)",
|
|
1396
|
+
)
|
|
1397
|
+
return parser.parse_args(args)
|
|
1398
|
+
|
|
1399
|
+
|
|
1400
|
+
def main() -> None:
|
|
1401
|
+
"""Main CLI entrypoint."""
|
|
1402
|
+
logging.basicConfig(
|
|
1403
|
+
level=logging.INFO,
|
|
1404
|
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
|
1405
|
+
)
|
|
1406
|
+
args = parse_args()
|
|
1407
|
+
|
|
1408
|
+
if args.continuous:
|
|
1409
|
+
try:
|
|
1410
|
+
asyncio.run(run_continuous_monitor(args))
|
|
1411
|
+
except KeyboardInterrupt:
|
|
1412
|
+
logger.info("Process halted.")
|
|
1413
|
+
else:
|
|
1414
|
+
asyncio.run(run_dex_monitor(args))
|
|
1415
|
+
|
|
1416
|
+
|
|
1417
|
+
if __name__ == "__main__":
|
|
1418
|
+
main()
|