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,683 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Autonomous DAO Governance Proposal Monitor & Security Daemon (Engine 2).
|
|
3
|
+
|
|
4
|
+
Continuously monitors Snapshot/Tally DAO governance proposals across major ecosystems,
|
|
5
|
+
extracts on-chain calldata and execution targets, performs two-stage deterministic
|
|
6
|
+
and semantic risk evaluations via ConditionAgentEngine, logs reports to the SQLite
|
|
7
|
+
ledger (data/agent.db), and dispatches webhook alerts with x402 monetization links.
|
|
8
|
+
|
|
9
|
+
Monitored Default DAOs:
|
|
10
|
+
- uniswap.eth (Uniswap)
|
|
11
|
+
- arbitrumfoundation.eth (Arbitrum)
|
|
12
|
+
- ens.eth (ENS)
|
|
13
|
+
- opcollective.eth (Optimism)
|
|
14
|
+
- aave.eth (Aave)
|
|
15
|
+
- aerodrome.eth (Aerodrome on Base)
|
|
16
|
+
|
|
17
|
+
Usage Examples:
|
|
18
|
+
# 1. Single scan dry-run across default DAOs (offline mock data, 0 LLM cost):
|
|
19
|
+
python scripts/governance_daemon.py --dry-run --once
|
|
20
|
+
|
|
21
|
+
# 2. Single scan live Snapshot across default DAOs:
|
|
22
|
+
python scripts/governance_daemon.py --once --limit 3
|
|
23
|
+
|
|
24
|
+
# 3. Continuous daemon polling every 120 seconds:
|
|
25
|
+
python scripts/governance_daemon.py --poll-interval 120
|
|
26
|
+
|
|
27
|
+
# 4. Monitor specific spaces with custom webhook alerts:
|
|
28
|
+
python scripts/governance_daemon.py --spaces uniswap.eth,aave.eth --webhook-url https://discord.com/api/webhooks/...
|
|
29
|
+
|
|
30
|
+
# 5. Continuous daemon with custom limit and minimum alert severity:
|
|
31
|
+
python scripts/governance_daemon.py --limit 5 --min-alert-level CRITICAL
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
import argparse
|
|
35
|
+
import asyncio
|
|
36
|
+
from datetime import datetime, timezone
|
|
37
|
+
import json
|
|
38
|
+
import logging
|
|
39
|
+
import os
|
|
40
|
+
import sys
|
|
41
|
+
from typing import Dict, Any, Optional, List, Set, Union, Literal
|
|
42
|
+
|
|
43
|
+
# Guarded dotenv loading: skipped during pytest execution or if python-dotenv not installed
|
|
44
|
+
if "pytest" not in sys.modules:
|
|
45
|
+
try:
|
|
46
|
+
import dotenv
|
|
47
|
+
_CURRENT_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
48
|
+
_PARENT_ROOT = os.path.abspath(os.path.join(_CURRENT_SCRIPT_DIR, ".."))
|
|
49
|
+
_env_file = os.path.join(_PARENT_ROOT, ".env")
|
|
50
|
+
if os.path.exists(_env_file):
|
|
51
|
+
dotenv.load_dotenv(_env_file, override=False)
|
|
52
|
+
dotenv.load_dotenv(override=False)
|
|
53
|
+
except ImportError:
|
|
54
|
+
pass
|
|
55
|
+
|
|
56
|
+
# Ensure module search paths support running directly or as a package
|
|
57
|
+
_CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
58
|
+
_ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, ".."))
|
|
59
|
+
_SRC_DIR = os.path.join(_ROOT_DIR, "src")
|
|
60
|
+
for _p in (_ROOT_DIR, _SRC_DIR):
|
|
61
|
+
if _p not in sys.path:
|
|
62
|
+
sys.path.insert(0, _p)
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
import aiosqlite
|
|
66
|
+
except ImportError:
|
|
67
|
+
aiosqlite = None # type: ignore
|
|
68
|
+
|
|
69
|
+
try:
|
|
70
|
+
from src.schemas import ChainId, FinalAgentResponse
|
|
71
|
+
from src.engine import ConditionAgentEngine
|
|
72
|
+
from src.semantic_evaluator import MockSemanticEvaluator
|
|
73
|
+
from src.storage import AgentStorage
|
|
74
|
+
from src.governance_connector import (
|
|
75
|
+
SnapshotGovernanceConnector,
|
|
76
|
+
GovernanceProposal,
|
|
77
|
+
GovernanceAuditReport,
|
|
78
|
+
WebhookAlertDispatcher,
|
|
79
|
+
extract_onchain_hints,
|
|
80
|
+
get_curated_dao_proposals,
|
|
81
|
+
)
|
|
82
|
+
except ImportError:
|
|
83
|
+
from schemas import ChainId, FinalAgentResponse
|
|
84
|
+
from engine import ConditionAgentEngine
|
|
85
|
+
from semantic_evaluator import MockSemanticEvaluator
|
|
86
|
+
from storage import AgentStorage
|
|
87
|
+
from governance_connector import (
|
|
88
|
+
SnapshotGovernanceConnector,
|
|
89
|
+
GovernanceProposal,
|
|
90
|
+
GovernanceAuditReport,
|
|
91
|
+
WebhookAlertDispatcher,
|
|
92
|
+
extract_onchain_hints,
|
|
93
|
+
get_curated_dao_proposals,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
logger = logging.getLogger("governance_daemon")
|
|
97
|
+
|
|
98
|
+
DEFAULT_MONITORED_SPACES: List[str] = [
|
|
99
|
+
"uniswap.eth",
|
|
100
|
+
"arbitrumfoundation.eth",
|
|
101
|
+
"ens.eth",
|
|
102
|
+
"opcollective.eth",
|
|
103
|
+
"aave.eth",
|
|
104
|
+
"aerodrome.eth",
|
|
105
|
+
]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def parse_spaces(spaces_input: Optional[Union[List[str], str]]) -> List[str]:
|
|
109
|
+
"""
|
|
110
|
+
Parses and sanitizes DAO space identifiers from either a list or comma-separated string.
|
|
111
|
+
Falls back to DEFAULT_MONITORED_SPACES when empty.
|
|
112
|
+
"""
|
|
113
|
+
if not spaces_input:
|
|
114
|
+
return list(DEFAULT_MONITORED_SPACES)
|
|
115
|
+
|
|
116
|
+
if isinstance(spaces_input, str):
|
|
117
|
+
parts = [s.strip() for s in spaces_input.split(",") if s.strip()]
|
|
118
|
+
return parts if parts else list(DEFAULT_MONITORED_SPACES)
|
|
119
|
+
|
|
120
|
+
resolved: List[str] = []
|
|
121
|
+
for item in spaces_input:
|
|
122
|
+
for s in item.split(","):
|
|
123
|
+
s_clean = s.strip()
|
|
124
|
+
if s_clean and s_clean not in resolved:
|
|
125
|
+
resolved.append(s_clean)
|
|
126
|
+
return resolved if resolved else list(DEFAULT_MONITORED_SPACES)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def get_mock_daemon_proposals(
|
|
130
|
+
spaces: List[str],
|
|
131
|
+
limit: int = 3,
|
|
132
|
+
chain_id: ChainId = ChainId.BASE_SEPOLIA,
|
|
133
|
+
) -> List[GovernanceProposal]:
|
|
134
|
+
"""
|
|
135
|
+
Generates deterministic, highly realistic mock governance proposals covering
|
|
136
|
+
benign actions, suspicious administrative privilege escalations, and proxy upgrades
|
|
137
|
+
for offline testing and --dry-run simulations.
|
|
138
|
+
"""
|
|
139
|
+
mock_catalog: Dict[str, List[GovernanceProposal]] = {
|
|
140
|
+
"uniswap.eth": [
|
|
141
|
+
GovernanceProposal(
|
|
142
|
+
proposal_id="mock-uni-001",
|
|
143
|
+
space_id="uniswap.eth",
|
|
144
|
+
title="Deploy Uniswap v3 Fee Tier to Base Mainnet",
|
|
145
|
+
body=(
|
|
146
|
+
"Deploy Uniswap v3 pool factory with 1bp fee tier on Base. "
|
|
147
|
+
"Target contract at 0x4200000000000000000000000000000000000006. "
|
|
148
|
+
"Calldata: 0xa9059cbb00000000000000000000000011111111111111111111111111111111111111110000000000000000000000000000000000000000000000000de0b6b3a7640000"
|
|
149
|
+
),
|
|
150
|
+
author="0x1111111111111111111111111111111111111111",
|
|
151
|
+
state="active",
|
|
152
|
+
created=1710000000,
|
|
153
|
+
target_address="0x4200000000000000000000000000000000000006",
|
|
154
|
+
calldata="0xa9059cbb00000000000000000000000011111111111111111111111111111111111111110000000000000000000000000000000000000000000000000de0b6b3a7640000",
|
|
155
|
+
tx_value_wei=0,
|
|
156
|
+
chain_id=chain_id,
|
|
157
|
+
)
|
|
158
|
+
],
|
|
159
|
+
"arbitrumfoundation.eth": [
|
|
160
|
+
GovernanceProposal(
|
|
161
|
+
proposal_id="mock-arb-002",
|
|
162
|
+
space_id="arbitrumfoundation.eth",
|
|
163
|
+
title="Arbitrum Bridge L2 Adapter UUPS Implementation Upgrade",
|
|
164
|
+
body=(
|
|
165
|
+
"Upgrade implementation contract for L2 bridge adapter at 0x4200000000000000000000000000000000000006 using upgradeTo. "
|
|
166
|
+
"Comprehensive security audit completed by OpenZeppelin with zero critical findings. "
|
|
167
|
+
"Calldata: 0x3659cfe6000000000000000000000000deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
|
|
168
|
+
),
|
|
169
|
+
author="0x7777777777777777777777777777777777777777",
|
|
170
|
+
state="active",
|
|
171
|
+
created=1710001000,
|
|
172
|
+
target_address="0x4200000000000000000000000000000000000006",
|
|
173
|
+
calldata="0x3659cfe6000000000000000000000000deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
|
|
174
|
+
tx_value_wei=0,
|
|
175
|
+
chain_id=chain_id,
|
|
176
|
+
)
|
|
177
|
+
],
|
|
178
|
+
"ens.eth": [
|
|
179
|
+
GovernanceProposal(
|
|
180
|
+
proposal_id="mock-ens-003",
|
|
181
|
+
space_id="ens.eth",
|
|
182
|
+
title="Routine DNS Gateway Maintenance & Parameter Update",
|
|
183
|
+
body=(
|
|
184
|
+
"Routine parameter adjustment for ENS DNS gateway and resolver config at 0x4200000000000000000000000000000000000006. "
|
|
185
|
+
"Executing configuration sync without audit. "
|
|
186
|
+
"Calldata: 0xf2fde38b000000000000000000000000deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
|
|
187
|
+
),
|
|
188
|
+
author="0x6666666666666666666666666666666666666666",
|
|
189
|
+
state="active",
|
|
190
|
+
created=1710002000,
|
|
191
|
+
target_address="0x4200000000000000000000000000000000000006",
|
|
192
|
+
calldata="0xf2fde38b000000000000000000000000deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
|
|
193
|
+
tx_value_wei=0,
|
|
194
|
+
chain_id=chain_id,
|
|
195
|
+
)
|
|
196
|
+
],
|
|
197
|
+
"opcollective.eth": [
|
|
198
|
+
GovernanceProposal(
|
|
199
|
+
proposal_id="mock-op-004",
|
|
200
|
+
space_id="opcollective.eth",
|
|
201
|
+
title="Optimism RetroPGF Round 5 Infrastructure Grant",
|
|
202
|
+
body=(
|
|
203
|
+
"Disburse 50,000 OP tokens from treasury to dev tooling guild at 0x4200000000000000000000000000000000000006. "
|
|
204
|
+
"Transfer verified by foundation council. "
|
|
205
|
+
"Calldata: 0xa9059cbb00000000000000000000000011111111111111111111111111111111111111110000000000000000000000000000000000000000000000000de0b6b3a7640000"
|
|
206
|
+
),
|
|
207
|
+
author="0x3333333333333333333333333333333333333333",
|
|
208
|
+
state="active",
|
|
209
|
+
created=1710003000,
|
|
210
|
+
target_address="0x4200000000000000000000000000000000000006",
|
|
211
|
+
calldata="0xa9059cbb00000000000000000000000011111111111111111111111111111111111111110000000000000000000000000000000000000000000000000de0b6b3a7640000",
|
|
212
|
+
tx_value_wei=0,
|
|
213
|
+
chain_id=chain_id,
|
|
214
|
+
)
|
|
215
|
+
],
|
|
216
|
+
"aave.eth": [
|
|
217
|
+
GovernanceProposal(
|
|
218
|
+
proposal_id="mock-aave-005",
|
|
219
|
+
space_id="aave.eth",
|
|
220
|
+
title="Aave v3 Liquidity Pool Incentive Reallocation",
|
|
221
|
+
body=(
|
|
222
|
+
"Allocate 100,000 USDC from community treasury for secondary market liquidity rewards. "
|
|
223
|
+
"Target liquidity vault at 0x4200000000000000000000000000000000000006 via transfer(0x1111111111111111111111111111111111111111, 100000000000). "
|
|
224
|
+
"Calldata: 0xa9059cbb00000000000000000000000011111111111111111111111111111111111111110000000000000000000000000000000000000000000000000de0b6b3a7640000"
|
|
225
|
+
),
|
|
226
|
+
author="0x5555555555555555555555555555555555555555",
|
|
227
|
+
state="active",
|
|
228
|
+
created=1710004000,
|
|
229
|
+
target_address="0x4200000000000000000000000000000000000006",
|
|
230
|
+
calldata="0xa9059cbb00000000000000000000000011111111111111111111111111111111111111110000000000000000000000000000000000000000000000000de0b6b3a7640000",
|
|
231
|
+
tx_value_wei=0,
|
|
232
|
+
chain_id=chain_id,
|
|
233
|
+
)
|
|
234
|
+
],
|
|
235
|
+
"aerodrome.eth": [
|
|
236
|
+
GovernanceProposal(
|
|
237
|
+
proposal_id="mock-aero-006",
|
|
238
|
+
space_id="aerodrome.eth",
|
|
239
|
+
title="Aerodrome Slipstream Concentrated Pool Gauge Creation",
|
|
240
|
+
body=(
|
|
241
|
+
"Create gauge for WETH/USDC slipstream pool at 0x4200000000000000000000000000000000000006 with standard voting weights. "
|
|
242
|
+
"Calldata: 0xa9059cbb00000000000000000000000011111111111111111111111111111111111111110000000000000000000000000000000000000000000000000de0b6b3a7640000"
|
|
243
|
+
),
|
|
244
|
+
author="0x4444444444444444444444444444444444444444",
|
|
245
|
+
state="active",
|
|
246
|
+
created=1710005000,
|
|
247
|
+
target_address="0x4200000000000000000000000000000000000006",
|
|
248
|
+
calldata="0xa9059cbb00000000000000000000000011111111111111111111111111111111111111110000000000000000000000000000000000000000000000000de0b6b3a7640000",
|
|
249
|
+
tx_value_wei=0,
|
|
250
|
+
chain_id=chain_id,
|
|
251
|
+
)
|
|
252
|
+
],
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
results: List[GovernanceProposal] = []
|
|
256
|
+
for sp in spaces:
|
|
257
|
+
props = mock_catalog.get(sp)
|
|
258
|
+
if not props:
|
|
259
|
+
# Dynamically synthesize a clean generic proposal for unknown spaces
|
|
260
|
+
props = [
|
|
261
|
+
GovernanceProposal(
|
|
262
|
+
proposal_id=f"mock-{sp[:6]}-999",
|
|
263
|
+
space_id=sp,
|
|
264
|
+
title=f"Standard Treasury Allocation for {sp}",
|
|
265
|
+
body=(
|
|
266
|
+
f"Routine governance action for {sp} at 0x4200000000000000000000000000000000000006. "
|
|
267
|
+
"Calldata: 0xa9059cbb00000000000000000000000011111111111111111111111111111111111111110000000000000000000000000000000000000000000000000de0b6b3a7640000"
|
|
268
|
+
),
|
|
269
|
+
author="0x8888888888888888888888888888888888888888",
|
|
270
|
+
state="active",
|
|
271
|
+
created=1710006000,
|
|
272
|
+
target_address="0x4200000000000000000000000000000000000006",
|
|
273
|
+
calldata="0xa9059cbb00000000000000000000000011111111111111111111111111111111111111110000000000000000000000000000000000000000000000000de0b6b3a7640000",
|
|
274
|
+
tx_value_wei=0,
|
|
275
|
+
chain_id=chain_id,
|
|
276
|
+
)
|
|
277
|
+
]
|
|
278
|
+
results.extend(props[:limit])
|
|
279
|
+
|
|
280
|
+
return results
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
async def load_audited_proposal_ids(storage: AgentStorage) -> Set[str]:
|
|
284
|
+
"""
|
|
285
|
+
Preloads previously audited proposal IDs and governance rule IDs from the SQLite ledger
|
|
286
|
+
to prevent redundant audits across daemon restarts.
|
|
287
|
+
"""
|
|
288
|
+
seen: Set[str] = set()
|
|
289
|
+
if aiosqlite is None:
|
|
290
|
+
return seen
|
|
291
|
+
|
|
292
|
+
try:
|
|
293
|
+
await storage.initialize()
|
|
294
|
+
if storage.db_path != ":memory:" and not os.path.exists(storage.db_path):
|
|
295
|
+
return seen
|
|
296
|
+
|
|
297
|
+
async with aiosqlite.connect(storage.db_path) as db:
|
|
298
|
+
cursor = await db.execute(
|
|
299
|
+
"SELECT rule_id, request_json FROM evaluations WHERE rule_id LIKE 'gov-%'"
|
|
300
|
+
)
|
|
301
|
+
rows = await cursor.fetchall()
|
|
302
|
+
for rule_id, req_json in rows:
|
|
303
|
+
if rule_id:
|
|
304
|
+
seen.add(rule_id)
|
|
305
|
+
if req_json:
|
|
306
|
+
try:
|
|
307
|
+
data = json.loads(req_json)
|
|
308
|
+
ctx = data.get("context_metadata", {})
|
|
309
|
+
pid = ctx.get("proposal_id")
|
|
310
|
+
if pid:
|
|
311
|
+
seen.add(str(pid))
|
|
312
|
+
except Exception:
|
|
313
|
+
pass
|
|
314
|
+
except Exception as exc:
|
|
315
|
+
logger.debug(f"Unable to preload audited proposals from {storage.db_path}: {exc}")
|
|
316
|
+
|
|
317
|
+
return seen
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def print_audit_table(reports: List[GovernanceAuditReport]) -> None:
|
|
321
|
+
"""
|
|
322
|
+
Renders an ASCII table of audited governance proposals displaying ID, space,
|
|
323
|
+
alert level, semantic decision, risk score, tokens, and USD cost.
|
|
324
|
+
"""
|
|
325
|
+
headers = ["Proposal ID", "Space", "Alert Level", "Decision", "Score", "Tokens", "Cost USD"]
|
|
326
|
+
rows = []
|
|
327
|
+
for r in reports:
|
|
328
|
+
prop_id = r.proposal.proposal_id[:16]
|
|
329
|
+
space = r.proposal.space_id[:22]
|
|
330
|
+
alert = r.alert_level
|
|
331
|
+
sem = r.agent_response.semantic_Evaluation
|
|
332
|
+
decision = sem.recommended_action if sem else "SKIPPED"
|
|
333
|
+
score = f"{sem.risk_score:.1f}" if sem else "N/A"
|
|
334
|
+
tokens = str(sem.input_tokens + sem.output_tokens) if sem else "0"
|
|
335
|
+
cost = f"${sem.estimated_cost_usd:.6f}" if sem else "$0.000000"
|
|
336
|
+
rows.append([prop_id, space, alert, decision, score, tokens, cost])
|
|
337
|
+
|
|
338
|
+
col_widths = [len(h) for h in headers]
|
|
339
|
+
for row in rows:
|
|
340
|
+
for idx, val in enumerate(row):
|
|
341
|
+
col_widths[idx] = max(col_widths[idx], len(val))
|
|
342
|
+
|
|
343
|
+
separator = "+" + "+".join("-" * (w + 2) for w in col_widths) + "+"
|
|
344
|
+
header_str = "|" + "|".join(f" {headers[i].ljust(col_widths[i])} " for i in range(len(headers))) + "|"
|
|
345
|
+
|
|
346
|
+
print("\n" + separator)
|
|
347
|
+
print(header_str)
|
|
348
|
+
print(separator)
|
|
349
|
+
if rows:
|
|
350
|
+
for row in rows:
|
|
351
|
+
row_str = "|" + "|".join(f" {row[i].ljust(col_widths[i])} " for i in range(len(row))) + "|"
|
|
352
|
+
print(row_str)
|
|
353
|
+
else:
|
|
354
|
+
empty_msg = "No new proposals audited."
|
|
355
|
+
total_w = sum(col_widths) + 3 * len(col_widths) - 1
|
|
356
|
+
print(f"| {empty_msg.ljust(total_w - 2)} |")
|
|
357
|
+
print(separator + "\n")
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
async def audit_governance_proposals(
|
|
361
|
+
connector: SnapshotGovernanceConnector,
|
|
362
|
+
engine: ConditionAgentEngine,
|
|
363
|
+
proposals: List[GovernanceProposal],
|
|
364
|
+
source: str = "governance_daemon",
|
|
365
|
+
) -> List[GovernanceAuditReport]:
|
|
366
|
+
"""
|
|
367
|
+
Executes end-to-end security audits across governance proposals, ensuring
|
|
368
|
+
evaluation records are tagged and stored in AgentStorage with the specified source.
|
|
369
|
+
"""
|
|
370
|
+
reports: List[GovernanceAuditReport] = []
|
|
371
|
+
for prop in proposals:
|
|
372
|
+
payload = connector.proposal_to_rule_payload(prop)
|
|
373
|
+
resp = await engine.process_rule(payload, source=source)
|
|
374
|
+
|
|
375
|
+
if resp.semantic_Evaluation is None:
|
|
376
|
+
alert_level: Literal["CRITICAL", "WARNING", "INFO"] = "INFO"
|
|
377
|
+
elif resp.semantic_Evaluation.recommended_action == "REJECT":
|
|
378
|
+
alert_level = "CRITICAL"
|
|
379
|
+
elif resp.semantic_Evaluation.recommended_action == "MANUAL_REVIEW":
|
|
380
|
+
alert_level = "WARNING"
|
|
381
|
+
else:
|
|
382
|
+
alert_level = "INFO"
|
|
383
|
+
|
|
384
|
+
reports.append(
|
|
385
|
+
GovernanceAuditReport(
|
|
386
|
+
proposal=prop,
|
|
387
|
+
rule_id=payload.rule_id,
|
|
388
|
+
agent_response=resp,
|
|
389
|
+
alert_level=alert_level,
|
|
390
|
+
)
|
|
391
|
+
)
|
|
392
|
+
return reports
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
async def run_governance_daemon(
|
|
396
|
+
poll_interval: float = 120.0,
|
|
397
|
+
once: bool = False,
|
|
398
|
+
dry_run: bool = False,
|
|
399
|
+
limit: int = 3,
|
|
400
|
+
spaces: Optional[Union[List[str], str]] = None,
|
|
401
|
+
webhook_url: Optional[str] = None,
|
|
402
|
+
public_api_url: Optional[str] = None,
|
|
403
|
+
min_alert_level: str = "WARNING",
|
|
404
|
+
engine: Optional[ConditionAgentEngine] = None,
|
|
405
|
+
storage: Optional[AgentStorage] = None,
|
|
406
|
+
connector: Optional[SnapshotGovernanceConnector] = None,
|
|
407
|
+
max_iterations: Optional[int] = None,
|
|
408
|
+
db_path: Optional[str] = None,
|
|
409
|
+
) -> List[GovernanceAuditReport]:
|
|
410
|
+
"""
|
|
411
|
+
Autonomous governance daemon loop monitoring DAOs via Snapshot.
|
|
412
|
+
|
|
413
|
+
Parameters:
|
|
414
|
+
poll_interval: Sleep duration in seconds between discovery cycles (default: 120.0).
|
|
415
|
+
once: If True, executes only one scan round and terminates.
|
|
416
|
+
dry_run: If True, uses deterministic mock proposals and MockSemanticEvaluator.
|
|
417
|
+
limit: Maximum number of proposals to inspect per DAO space (default: 3).
|
|
418
|
+
spaces: List or comma-separated string of DAO space identifiers.
|
|
419
|
+
webhook_url: Optional webhook URL for threat alerts (overrides ALERT_WEBHOOK_URL).
|
|
420
|
+
public_api_url: Public API base URL included in x402 alert links.
|
|
421
|
+
min_alert_level: Minimum alert severity to trigger webhook notifications (default: WARNING).
|
|
422
|
+
engine: Optional pre-configured ConditionAgentEngine instance.
|
|
423
|
+
storage: Optional pre-configured AgentStorage instance.
|
|
424
|
+
connector: Optional pre-configured SnapshotGovernanceConnector instance.
|
|
425
|
+
max_iterations: Optional maximum loop iterations before exiting (primarily for testing).
|
|
426
|
+
db_path: Optional SQLite database file path.
|
|
427
|
+
|
|
428
|
+
Returns:
|
|
429
|
+
List of all GovernanceAuditReport instances audited during the run.
|
|
430
|
+
"""
|
|
431
|
+
target_spaces = parse_spaces(spaces)
|
|
432
|
+
active_webhook = webhook_url or os.getenv("ALERT_WEBHOOK_URL")
|
|
433
|
+
|
|
434
|
+
# Storage setup
|
|
435
|
+
storage_instance = storage if storage is not None else AgentStorage(db_path=db_path)
|
|
436
|
+
await storage_instance.initialize()
|
|
437
|
+
|
|
438
|
+
# Preload already audited proposals to ensure deduplication
|
|
439
|
+
seen_proposal_ids: Set[str] = set()
|
|
440
|
+
preloaded = await load_audited_proposal_ids(storage_instance)
|
|
441
|
+
seen_proposal_ids.update(preloaded)
|
|
442
|
+
|
|
443
|
+
# Engine setup
|
|
444
|
+
if engine is not None:
|
|
445
|
+
active_engine = engine
|
|
446
|
+
elif dry_run:
|
|
447
|
+
evaluator = MockSemanticEvaluator()
|
|
448
|
+
active_engine = ConditionAgentEngine(
|
|
449
|
+
semantic_evaluator=evaluator,
|
|
450
|
+
storage=storage_instance,
|
|
451
|
+
)
|
|
452
|
+
else:
|
|
453
|
+
active_engine = ConditionAgentEngine(
|
|
454
|
+
storage=storage_instance,
|
|
455
|
+
)
|
|
456
|
+
|
|
457
|
+
# Connector setup
|
|
458
|
+
active_connector = connector or SnapshotGovernanceConnector(
|
|
459
|
+
default_chain_id=ChainId.BASE_SEPOLIA
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
all_audited_reports: List[GovernanceAuditReport] = []
|
|
463
|
+
iteration = 0
|
|
464
|
+
|
|
465
|
+
print("=" * 72)
|
|
466
|
+
print("Web3 Condition-Action Trigger Agent: DAO Governance Daemon (Engine 2)")
|
|
467
|
+
print("=" * 72)
|
|
468
|
+
print(f"[*] Target Spaces ({len(target_spaces)}): {', '.join(target_spaces)}")
|
|
469
|
+
print(f"[*] Mode: {'DRY-RUN (Simulated)' if dry_run else 'LIVE SNAPSHOT GRAPHQL'}")
|
|
470
|
+
print(f"[*] Execution: {'SINGLE PASS (--once)' if once else f'CONTINUOUS (poll: {poll_interval}s)'}")
|
|
471
|
+
print(f"[*] Limit per space: {limit}")
|
|
472
|
+
if active_webhook:
|
|
473
|
+
print(f"[*] Webhook Dispatch: ENABLED (min_level={min_alert_level})")
|
|
474
|
+
print(f"[*] Ledger Persistence: {storage_instance.db_path}")
|
|
475
|
+
print("=" * 72 + "\n")
|
|
476
|
+
|
|
477
|
+
try:
|
|
478
|
+
while True:
|
|
479
|
+
iteration += 1
|
|
480
|
+
timestamp_str = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
|
|
481
|
+
print(f"[{timestamp_str}] [Iteration #{iteration}] Scanning governance proposals...")
|
|
482
|
+
|
|
483
|
+
cycle_reports: List[GovernanceAuditReport] = []
|
|
484
|
+
|
|
485
|
+
# 1. Discover proposals
|
|
486
|
+
discovered_proposals: List[GovernanceProposal] = []
|
|
487
|
+
if dry_run:
|
|
488
|
+
discovered_proposals = get_mock_daemon_proposals(target_spaces, limit=limit)
|
|
489
|
+
else:
|
|
490
|
+
for space in target_spaces:
|
|
491
|
+
try:
|
|
492
|
+
props = await active_connector.fetch_proposals(
|
|
493
|
+
spaces=[space],
|
|
494
|
+
limit=max(limit * 2, 5),
|
|
495
|
+
state="all",
|
|
496
|
+
use_curated_fallback=True,
|
|
497
|
+
)
|
|
498
|
+
# Prefer active proposals, fallback to most recent if none active
|
|
499
|
+
active_props = [p for p in props if p.state.lower() == "active"]
|
|
500
|
+
selected = active_props[:limit] if active_props else props[:limit]
|
|
501
|
+
|
|
502
|
+
# Apply heuristic on-chain hint extraction
|
|
503
|
+
for p in selected:
|
|
504
|
+
hints = extract_onchain_hints(p.body)
|
|
505
|
+
if hints.get("target_address"):
|
|
506
|
+
p.target_address = hints["target_address"]
|
|
507
|
+
if hints.get("calldata") and hints["calldata"] != "0x":
|
|
508
|
+
p.calldata = hints["calldata"]
|
|
509
|
+
|
|
510
|
+
discovered_proposals.extend(selected)
|
|
511
|
+
except Exception as exc:
|
|
512
|
+
logger.warning(f"Error fetching Snapshot proposals for space '{space}': {exc}")
|
|
513
|
+
|
|
514
|
+
# 2. Filter out already processed proposals
|
|
515
|
+
new_proposals: List[GovernanceProposal] = []
|
|
516
|
+
for prop in discovered_proposals:
|
|
517
|
+
rule_id = f"gov-{prop.space_id}-{prop.proposal_id[:12]}"
|
|
518
|
+
if prop.proposal_id in seen_proposal_ids or rule_id in seen_proposal_ids:
|
|
519
|
+
logger.debug(f"Skipping already audited proposal: {prop.proposal_id}")
|
|
520
|
+
continue
|
|
521
|
+
new_proposals.append(prop)
|
|
522
|
+
|
|
523
|
+
# 3. Audit newly discovered proposals
|
|
524
|
+
if new_proposals:
|
|
525
|
+
print(f"[+] Discovered {len(new_proposals)} new un-audited proposal(s). Running audits...")
|
|
526
|
+
cycle_reports = await audit_governance_proposals(
|
|
527
|
+
connector=active_connector,
|
|
528
|
+
engine=active_engine,
|
|
529
|
+
proposals=new_proposals,
|
|
530
|
+
source="governance_daemon",
|
|
531
|
+
)
|
|
532
|
+
|
|
533
|
+
# Record into seen tracking set
|
|
534
|
+
for r in cycle_reports:
|
|
535
|
+
seen_proposal_ids.add(r.proposal.proposal_id)
|
|
536
|
+
seen_proposal_ids.add(r.rule_id)
|
|
537
|
+
all_audited_reports.extend(cycle_reports)
|
|
538
|
+
|
|
539
|
+
# 4. Display ASCII table
|
|
540
|
+
print_audit_table(cycle_reports)
|
|
541
|
+
|
|
542
|
+
# 5. Webhook dispatch
|
|
543
|
+
if active_webhook:
|
|
544
|
+
dispatcher = WebhookAlertDispatcher(
|
|
545
|
+
webhook_url=active_webhook,
|
|
546
|
+
public_api_url=public_api_url,
|
|
547
|
+
)
|
|
548
|
+
sent_count = await dispatcher.dispatch_batch(
|
|
549
|
+
cycle_reports,
|
|
550
|
+
min_alert_level=min_alert_level,
|
|
551
|
+
)
|
|
552
|
+
print(f"[+] Dispatched {sent_count} webhook alert(s) (min_level={min_alert_level}).")
|
|
553
|
+
|
|
554
|
+
# Metrics summary
|
|
555
|
+
rejections = [r for r in cycle_reports if r.alert_level == "CRITICAL"]
|
|
556
|
+
warnings = [r for r in cycle_reports if r.alert_level == "WARNING"]
|
|
557
|
+
info = [r for r in cycle_reports if r.alert_level == "INFO"]
|
|
558
|
+
print(
|
|
559
|
+
f"[*] Iteration #{iteration} Summary: {len(cycle_reports)} audited | "
|
|
560
|
+
f"Critical: {len(rejections)} | Warning: {len(warnings)} | Info: {len(info)}\n"
|
|
561
|
+
)
|
|
562
|
+
else:
|
|
563
|
+
print(f"[*] Iteration #{iteration}: All {len(discovered_proposals)} proposal(s) previously audited. No new actions.")
|
|
564
|
+
|
|
565
|
+
if once:
|
|
566
|
+
print("[*] Single scan cycle (--once) completed.")
|
|
567
|
+
break
|
|
568
|
+
|
|
569
|
+
if max_iterations is not None and iteration >= max_iterations:
|
|
570
|
+
print(f"[*] Reached max iterations ({max_iterations}). Exiting daemon loop.")
|
|
571
|
+
break
|
|
572
|
+
|
|
573
|
+
print(f"[*] Sleeping for {poll_interval}s until next poll cycle (Press Ctrl+C to stop)...")
|
|
574
|
+
await asyncio.sleep(poll_interval)
|
|
575
|
+
|
|
576
|
+
except (KeyboardInterrupt, asyncio.CancelledError):
|
|
577
|
+
print("\n[*] Governance daemon stopped by user or cancellation signal.")
|
|
578
|
+
|
|
579
|
+
return all_audited_reports
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def parse_args(args: Optional[List[str]] = None) -> argparse.Namespace:
|
|
583
|
+
"""Parses command-line arguments for the governance daemon."""
|
|
584
|
+
parser = argparse.ArgumentParser(
|
|
585
|
+
description="Autonomous DAO Governance Proposal Monitor & Security Daemon (Engine 2)"
|
|
586
|
+
)
|
|
587
|
+
parser.add_argument(
|
|
588
|
+
"--poll-interval",
|
|
589
|
+
type=float,
|
|
590
|
+
default=120.0,
|
|
591
|
+
help="Polling interval in seconds between governance proposal scans (default: 120.0)",
|
|
592
|
+
)
|
|
593
|
+
parser.add_argument(
|
|
594
|
+
"--once",
|
|
595
|
+
action="store_true",
|
|
596
|
+
default=False,
|
|
597
|
+
help="Execute a single discovery and audit cycle then exit",
|
|
598
|
+
)
|
|
599
|
+
parser.add_argument(
|
|
600
|
+
"--dry-run",
|
|
601
|
+
action="store_true",
|
|
602
|
+
default=False,
|
|
603
|
+
help="Run in offline dry-run mode using curated mock proposals and MockSemanticEvaluator",
|
|
604
|
+
)
|
|
605
|
+
parser.add_argument(
|
|
606
|
+
"--limit",
|
|
607
|
+
type=int,
|
|
608
|
+
default=3,
|
|
609
|
+
help="Maximum number of proposals to inspect per DAO space (default: 3)",
|
|
610
|
+
)
|
|
611
|
+
parser.add_argument(
|
|
612
|
+
"--spaces",
|
|
613
|
+
type=str,
|
|
614
|
+
default=None,
|
|
615
|
+
help="Comma-separated list of Snapshot space identifiers (e.g. 'uniswap.eth,arbitrumfoundation.eth')",
|
|
616
|
+
)
|
|
617
|
+
parser.add_argument(
|
|
618
|
+
"--space",
|
|
619
|
+
action="append",
|
|
620
|
+
dest="space_list",
|
|
621
|
+
default=None,
|
|
622
|
+
help="Single Snapshot space identifier (can be repeated, e.g. --space ens.eth --space aave.eth)",
|
|
623
|
+
)
|
|
624
|
+
parser.add_argument(
|
|
625
|
+
"--webhook-url",
|
|
626
|
+
type=str,
|
|
627
|
+
default=None,
|
|
628
|
+
help="Optional Discord/Slack/HTTP webhook URL for threat notifications (overrides ALERT_WEBHOOK_URL env)",
|
|
629
|
+
)
|
|
630
|
+
parser.add_argument(
|
|
631
|
+
"--public-url",
|
|
632
|
+
type=str,
|
|
633
|
+
default=None,
|
|
634
|
+
help="Public API base URL included in x402 alert links",
|
|
635
|
+
)
|
|
636
|
+
parser.add_argument(
|
|
637
|
+
"--min-alert-level",
|
|
638
|
+
type=str,
|
|
639
|
+
default="WARNING",
|
|
640
|
+
choices=["INFO", "WARNING", "CRITICAL"],
|
|
641
|
+
help="Minimum alert severity to trigger webhook dispatch (default: WARNING)",
|
|
642
|
+
)
|
|
643
|
+
parser.add_argument(
|
|
644
|
+
"--db-path",
|
|
645
|
+
type=str,
|
|
646
|
+
default=None,
|
|
647
|
+
help="Optional SQLite database path (defaults to data/agent.db)",
|
|
648
|
+
)
|
|
649
|
+
return parser.parse_args(args)
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def main() -> None:
|
|
653
|
+
"""CLI entrypoint for running the governance daemon."""
|
|
654
|
+
args = parse_args()
|
|
655
|
+
logging.basicConfig(
|
|
656
|
+
level=logging.INFO,
|
|
657
|
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
|
658
|
+
)
|
|
659
|
+
|
|
660
|
+
combined_spaces = []
|
|
661
|
+
if args.spaces:
|
|
662
|
+
combined_spaces.append(args.spaces)
|
|
663
|
+
if args.space_list:
|
|
664
|
+
combined_spaces.extend(args.space_list)
|
|
665
|
+
spaces_input = combined_spaces if combined_spaces else None
|
|
666
|
+
|
|
667
|
+
asyncio.run(
|
|
668
|
+
run_governance_daemon(
|
|
669
|
+
poll_interval=args.poll_interval,
|
|
670
|
+
once=args.once,
|
|
671
|
+
dry_run=args.dry_run,
|
|
672
|
+
limit=args.limit,
|
|
673
|
+
spaces=spaces_input,
|
|
674
|
+
webhook_url=args.webhook_url,
|
|
675
|
+
public_api_url=args.public_url,
|
|
676
|
+
min_alert_level=args.min_alert_level,
|
|
677
|
+
db_path=args.db_path,
|
|
678
|
+
)
|
|
679
|
+
)
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
if __name__ == "__main__":
|
|
683
|
+
main()
|