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,548 @@
|
|
|
1
|
+
"""
|
|
2
|
+
DAO Governance Connector & Security Scanner.
|
|
3
|
+
|
|
4
|
+
Provides Snapshot GraphQL API polling, heuristic on-chain calldata/target extraction,
|
|
5
|
+
and automated conversion into ConditionRulePayload for semantic governance audit.
|
|
6
|
+
|
|
7
|
+
Usage:
|
|
8
|
+
from src.governance_connector import (
|
|
9
|
+
SnapshotGovernanceConnector,
|
|
10
|
+
GovernanceProposal,
|
|
11
|
+
GovernanceAuditReport,
|
|
12
|
+
GovernanceScanRequest,
|
|
13
|
+
WebhookAlertDispatcher,
|
|
14
|
+
ALERT_SEVERITY_ORDER,
|
|
15
|
+
get_curated_dao_proposals,
|
|
16
|
+
extract_onchain_hints,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
connector = SnapshotGovernanceConnector()
|
|
20
|
+
proposals = await connector.fetch_proposals(spaces=["arbitrumfoundation.eth"], limit=3)
|
|
21
|
+
reports = await connector.audit_proposals(engine, proposals=proposals)
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import asyncio
|
|
25
|
+
import logging
|
|
26
|
+
import os
|
|
27
|
+
import re
|
|
28
|
+
import sys
|
|
29
|
+
from typing import Dict, Any, Optional, List, Literal
|
|
30
|
+
|
|
31
|
+
import httpx
|
|
32
|
+
from pydantic import BaseModel, Field, field_validator
|
|
33
|
+
from web3 import Web3
|
|
34
|
+
|
|
35
|
+
# Ensure module search paths support running directly or as a package
|
|
36
|
+
_CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
37
|
+
_ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, "..")) if os.path.basename(_CURRENT_DIR) == "src" else _CURRENT_DIR
|
|
38
|
+
_SRC_DIR = os.path.join(_ROOT_DIR, "src")
|
|
39
|
+
for _p in (_ROOT_DIR, _SRC_DIR):
|
|
40
|
+
if _p not in sys.path:
|
|
41
|
+
sys.path.insert(0, _p)
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
from src.schemas import (
|
|
45
|
+
ChainId,
|
|
46
|
+
ConditionRulePayload,
|
|
47
|
+
DeterministicCondition,
|
|
48
|
+
SemanticCondition,
|
|
49
|
+
FinalAgentResponse,
|
|
50
|
+
)
|
|
51
|
+
from src.engine import ConditionAgentEngine
|
|
52
|
+
except ImportError:
|
|
53
|
+
from schemas import (
|
|
54
|
+
ChainId,
|
|
55
|
+
ConditionRulePayload,
|
|
56
|
+
DeterministicCondition,
|
|
57
|
+
SemanticCondition,
|
|
58
|
+
FinalAgentResponse,
|
|
59
|
+
)
|
|
60
|
+
from engine import ConditionAgentEngine
|
|
61
|
+
|
|
62
|
+
logger = logging.getLogger(__name__)
|
|
63
|
+
|
|
64
|
+
DEFAULT_TARGET_ADDRESS: str = "0x4200000000000000000000000000000000000006"
|
|
65
|
+
|
|
66
|
+
ALERT_SEVERITY_ORDER: Dict[str, int] = {
|
|
67
|
+
"INFO": 1,
|
|
68
|
+
"WARNING": 2,
|
|
69
|
+
"CRITICAL": 3,
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class GovernanceProposal(BaseModel):
|
|
74
|
+
"""
|
|
75
|
+
Representation of an on-chain or off-chain DAO governance proposal.
|
|
76
|
+
"""
|
|
77
|
+
proposal_id: str
|
|
78
|
+
space_id: str
|
|
79
|
+
title: str
|
|
80
|
+
body: str
|
|
81
|
+
author: str = "0x0000000000000000000000000000000000000000"
|
|
82
|
+
state: str = "active"
|
|
83
|
+
created: int = 0
|
|
84
|
+
target_address: str = DEFAULT_TARGET_ADDRESS
|
|
85
|
+
calldata: str = "0x"
|
|
86
|
+
tx_value_wei: int = Field(default=0, ge=0)
|
|
87
|
+
chain_id: ChainId = ChainId.BASE_SEPOLIA
|
|
88
|
+
|
|
89
|
+
@field_validator("target_address")
|
|
90
|
+
@classmethod
|
|
91
|
+
def validate_target_address(cls, v: str) -> str:
|
|
92
|
+
if isinstance(v, str) and Web3.is_address(v):
|
|
93
|
+
return Web3.to_checksum_address(v)
|
|
94
|
+
raise ValueError(f"Invalid target EVM address: {v}")
|
|
95
|
+
|
|
96
|
+
@field_validator("author")
|
|
97
|
+
@classmethod
|
|
98
|
+
def validate_author(cls, v: str) -> str:
|
|
99
|
+
if isinstance(v, str) and Web3.is_address(v):
|
|
100
|
+
return Web3.to_checksum_address(v)
|
|
101
|
+
return v
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class GovernanceAuditReport(BaseModel):
|
|
105
|
+
"""
|
|
106
|
+
Structured audit evaluation report generated by auditing a DAO governance proposal.
|
|
107
|
+
"""
|
|
108
|
+
proposal: GovernanceProposal
|
|
109
|
+
rule_id: str
|
|
110
|
+
agent_response: FinalAgentResponse
|
|
111
|
+
alert_level: Literal["CRITICAL", "WARNING", "INFO"]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class GovernanceScanRequest(BaseModel):
|
|
115
|
+
"""
|
|
116
|
+
Request parameters for triggering an on-demand governance scan.
|
|
117
|
+
"""
|
|
118
|
+
spaces: Optional[List[str]] = None
|
|
119
|
+
limit: int = Field(default=3, ge=1, le=20)
|
|
120
|
+
chain_id: ChainId = ChainId.BASE_SEPOLIA
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def extract_onchain_hints(text: str) -> Dict[str, Any]:
|
|
124
|
+
"""
|
|
125
|
+
Extracts heuristic on-chain target address and calldata hints from proposal text.
|
|
126
|
+
|
|
127
|
+
Scans for:
|
|
128
|
+
- First valid 42-char EVM address (defaulting to 0x4200000000000000000000000000000000000006).
|
|
129
|
+
- Explicit calldata hex or known function keywords:
|
|
130
|
+
transferOwnership -> 0xf2fde38b...
|
|
131
|
+
upgradeTo -> 0x3659cfe6...
|
|
132
|
+
transfer( / treasury -> 0xa9059cbb...
|
|
133
|
+
else 0x
|
|
134
|
+
"""
|
|
135
|
+
text_str = text or ""
|
|
136
|
+
|
|
137
|
+
# 1. Target address: First valid 42-char EVM address
|
|
138
|
+
target_address = DEFAULT_TARGET_ADDRESS
|
|
139
|
+
addr_match = re.search(r"\b0x[a-fA-F0-9]{40}\b", text_str)
|
|
140
|
+
if addr_match:
|
|
141
|
+
raw_addr = addr_match.group(0)
|
|
142
|
+
try:
|
|
143
|
+
target_address = Web3.to_checksum_address(raw_addr)
|
|
144
|
+
except Exception:
|
|
145
|
+
pass
|
|
146
|
+
|
|
147
|
+
# 2. Calldata hex:
|
|
148
|
+
# Match any hex string with at least 8 hex digits (len >= 10) not equal to a 42-char address
|
|
149
|
+
hex_candidates = [
|
|
150
|
+
m.group(0) for m in re.finditer(r"\b0x[a-fA-F0-9]{8,}\b", text_str)
|
|
151
|
+
if len(m.group(0)) != 42
|
|
152
|
+
]
|
|
153
|
+
|
|
154
|
+
calldata = "0x"
|
|
155
|
+
if hex_candidates:
|
|
156
|
+
calldata = hex_candidates[0]
|
|
157
|
+
elif "transferownership" in text_str.lower():
|
|
158
|
+
calldata = "0xf2fde38b000000000000000000000000deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
|
|
159
|
+
elif "upgradeto" in text_str.lower():
|
|
160
|
+
calldata = "0x3659cfe6000000000000000000000000deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
|
|
161
|
+
elif "transfer(" in text_str.lower() or "treasury" in text_str.lower():
|
|
162
|
+
calldata = "0xa9059cbb00000000000000000000000011111111111111111111111111111111111111110000000000000000000000000000000000000000000000000de0b6b3a7640000"
|
|
163
|
+
|
|
164
|
+
return {
|
|
165
|
+
"target_address": target_address,
|
|
166
|
+
"calldata": calldata,
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def get_curated_dao_proposals(
|
|
171
|
+
default_chain_id: ChainId = ChainId.BASE_SEPOLIA,
|
|
172
|
+
limit: int = 3,
|
|
173
|
+
) -> List[GovernanceProposal]:
|
|
174
|
+
"""
|
|
175
|
+
Returns up to limit curated realistic DAO proposals covering:
|
|
176
|
+
1. Benign liquidity/parameter proposal (APPROVE candidate, selector 0xa9059cbb)
|
|
177
|
+
2. Discrepant malicious governance takeover (REJECT candidate, claims routine update while executing 0xf2fde38b transferOwnership without audit)
|
|
178
|
+
3. Audited UUPS proxy upgrade (MANUAL_REVIEW candidate, 0x3659cfe6 upgradeTo with OpenZeppelin audit reference)
|
|
179
|
+
"""
|
|
180
|
+
proposals = [
|
|
181
|
+
GovernanceProposal(
|
|
182
|
+
proposal_id="curated-aave-001",
|
|
183
|
+
space_id="aavedao.eth",
|
|
184
|
+
title="Aave v3 Liquidity Pool Incentive Reallocation",
|
|
185
|
+
body=(
|
|
186
|
+
"Allocate 100,000 USDC from community treasury for secondary market liquidity rewards. "
|
|
187
|
+
"Target liquidity vault at 0x4200000000000000000000000000000000000006 via transfer(0x1111111111111111111111111111111111111111, 100000000000). "
|
|
188
|
+
"Calldata: 0xa9059cbb00000000000000000000000011111111111111111111111111111111111111110000000000000000000000000000000000000000000000000de0b6b3a7640000"
|
|
189
|
+
),
|
|
190
|
+
author="0x5555555555555555555555555555555555555555",
|
|
191
|
+
state="active",
|
|
192
|
+
created=1710000000,
|
|
193
|
+
target_address="0x4200000000000000000000000000000000000006",
|
|
194
|
+
calldata="0xa9059cbb00000000000000000000000011111111111111111111111111111111111111110000000000000000000000000000000000000000000000000de0b6b3a7640000",
|
|
195
|
+
tx_value_wei=0,
|
|
196
|
+
chain_id=default_chain_id,
|
|
197
|
+
),
|
|
198
|
+
GovernanceProposal(
|
|
199
|
+
proposal_id="curated-ens-002",
|
|
200
|
+
space_id="ens.eth",
|
|
201
|
+
title="Routine DNS Gateway Maintenance & Parameter Update",
|
|
202
|
+
body=(
|
|
203
|
+
"Routine parameter adjustment for ENS DNS gateway and resolver config at 0x4200000000000000000000000000000000000006. "
|
|
204
|
+
"Executing configuration sync without audit. "
|
|
205
|
+
"Calldata: 0xf2fde38b000000000000000000000000deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
|
|
206
|
+
),
|
|
207
|
+
author="0x6666666666666666666666666666666666666666",
|
|
208
|
+
state="active",
|
|
209
|
+
created=1710001000,
|
|
210
|
+
target_address="0x4200000000000000000000000000000000000006",
|
|
211
|
+
calldata="0xf2fde38b000000000000000000000000deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
|
|
212
|
+
tx_value_wei=0,
|
|
213
|
+
chain_id=default_chain_id,
|
|
214
|
+
),
|
|
215
|
+
GovernanceProposal(
|
|
216
|
+
proposal_id="curated-arb-003",
|
|
217
|
+
space_id="arbitrumfoundation.eth",
|
|
218
|
+
title="Arbitrum Bridge L2 Adapter UUPS Implementation Upgrade",
|
|
219
|
+
body=(
|
|
220
|
+
"Upgrade implementation contract for L2 bridge adapter at 0x4200000000000000000000000000000000000006 using upgradeTo. "
|
|
221
|
+
"Comprehensive security audit completed by OpenZeppelin with zero critical findings. "
|
|
222
|
+
"Calldata: 0x3659cfe6000000000000000000000000deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
|
|
223
|
+
),
|
|
224
|
+
author="0x7777777777777777777777777777777777777777",
|
|
225
|
+
state="active",
|
|
226
|
+
created=1710002000,
|
|
227
|
+
target_address="0x4200000000000000000000000000000000000006",
|
|
228
|
+
calldata="0x3659cfe6000000000000000000000000deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
|
|
229
|
+
tx_value_wei=0,
|
|
230
|
+
chain_id=default_chain_id,
|
|
231
|
+
),
|
|
232
|
+
]
|
|
233
|
+
return proposals[: max(1, limit)]
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
class SnapshotGovernanceConnector:
|
|
237
|
+
"""
|
|
238
|
+
Asynchronous connector for Snapshot GraphQL governance data with automatic fallback
|
|
239
|
+
to realistic curated proposals.
|
|
240
|
+
"""
|
|
241
|
+
|
|
242
|
+
SNAPSHOT_GRAPHQL_URL: str = "https://hub.snapshot.org/graphql"
|
|
243
|
+
DEFAULT_SPACES: List[str] = ["arbitrumfoundation.eth", "aavedao.eth", "ens.eth"]
|
|
244
|
+
|
|
245
|
+
def __init__(
|
|
246
|
+
self,
|
|
247
|
+
graphql_url: Optional[str] = None,
|
|
248
|
+
default_chain_id: ChainId = ChainId.BASE_SEPOLIA,
|
|
249
|
+
timeout: float = 8.0,
|
|
250
|
+
):
|
|
251
|
+
self.graphql_url = graphql_url or self.SNAPSHOT_GRAPHQL_URL
|
|
252
|
+
self.default_chain_id = default_chain_id
|
|
253
|
+
self.timeout = timeout
|
|
254
|
+
|
|
255
|
+
async def fetch_proposals(
|
|
256
|
+
self,
|
|
257
|
+
spaces: Optional[List[str]] = None,
|
|
258
|
+
limit: int = 3,
|
|
259
|
+
state: str = "all",
|
|
260
|
+
use_curated_fallback: bool = True,
|
|
261
|
+
) -> List[GovernanceProposal]:
|
|
262
|
+
"""
|
|
263
|
+
Fetches recent DAO proposals from Snapshot GraphQL API.
|
|
264
|
+
Falls back to curated DAO proposals if unreachable or on error.
|
|
265
|
+
"""
|
|
266
|
+
target_spaces = spaces if spaces is not None else self.DEFAULT_SPACES
|
|
267
|
+
query = """
|
|
268
|
+
query GetProposals($limit: Int!, $spaces: [String!]) {
|
|
269
|
+
proposals(first: $limit, where: {space_in: $spaces}) {
|
|
270
|
+
id
|
|
271
|
+
title
|
|
272
|
+
body
|
|
273
|
+
author
|
|
274
|
+
state
|
|
275
|
+
created
|
|
276
|
+
space {
|
|
277
|
+
id
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
"""
|
|
282
|
+
variables = {"limit": limit, "spaces": target_spaces}
|
|
283
|
+
try:
|
|
284
|
+
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
285
|
+
resp = await client.post(
|
|
286
|
+
self.graphql_url,
|
|
287
|
+
json={"query": query, "variables": variables},
|
|
288
|
+
)
|
|
289
|
+
if resp.status_code != 200:
|
|
290
|
+
if use_curated_fallback:
|
|
291
|
+
logger.warning(
|
|
292
|
+
f"Snapshot API returned status {resp.status_code}; using curated fallback"
|
|
293
|
+
)
|
|
294
|
+
return get_curated_dao_proposals(self.default_chain_id, limit=limit)
|
|
295
|
+
resp.raise_for_status()
|
|
296
|
+
|
|
297
|
+
data = resp.json().get("data", {})
|
|
298
|
+
proposals_raw = data.get("proposals") if isinstance(data, dict) else None
|
|
299
|
+
if not proposals_raw:
|
|
300
|
+
if use_curated_fallback:
|
|
301
|
+
return get_curated_dao_proposals(self.default_chain_id, limit=limit)
|
|
302
|
+
return []
|
|
303
|
+
|
|
304
|
+
results: List[GovernanceProposal] = []
|
|
305
|
+
for item in proposals_raw[:limit]:
|
|
306
|
+
space_id = (
|
|
307
|
+
item.get("space", {}).get("id", "")
|
|
308
|
+
if isinstance(item.get("space"), dict)
|
|
309
|
+
else str(item.get("space") or "")
|
|
310
|
+
)
|
|
311
|
+
body = item.get("body") or ""
|
|
312
|
+
hints = extract_onchain_hints(body)
|
|
313
|
+
results.append(
|
|
314
|
+
GovernanceProposal(
|
|
315
|
+
proposal_id=str(item.get("id", "")),
|
|
316
|
+
space_id=space_id,
|
|
317
|
+
title=str(item.get("title", "")),
|
|
318
|
+
body=body,
|
|
319
|
+
author=str(item.get("author", "0x0000000000000000000000000000000000000000")),
|
|
320
|
+
state=str(item.get("state", "active")),
|
|
321
|
+
created=int(item.get("created", 0)),
|
|
322
|
+
target_address=hints["target_address"],
|
|
323
|
+
calldata=hints["calldata"],
|
|
324
|
+
tx_value_wei=0,
|
|
325
|
+
chain_id=self.default_chain_id,
|
|
326
|
+
)
|
|
327
|
+
)
|
|
328
|
+
return results
|
|
329
|
+
except Exception as exc:
|
|
330
|
+
if use_curated_fallback:
|
|
331
|
+
logger.warning(
|
|
332
|
+
f"Snapshot GraphQL request failed ({exc}); using curated fallback"
|
|
333
|
+
)
|
|
334
|
+
return get_curated_dao_proposals(self.default_chain_id, limit=limit)
|
|
335
|
+
raise
|
|
336
|
+
|
|
337
|
+
def proposal_to_rule_payload(
|
|
338
|
+
self,
|
|
339
|
+
proposal: GovernanceProposal,
|
|
340
|
+
policy_prompt: Optional[str] = None,
|
|
341
|
+
risk_threshold: float = 7.0,
|
|
342
|
+
) -> ConditionRulePayload:
|
|
343
|
+
"""
|
|
344
|
+
Converts a GovernanceProposal into an actionable ConditionRulePayload for the agent engine.
|
|
345
|
+
"""
|
|
346
|
+
return ConditionRulePayload(
|
|
347
|
+
rule_id=f"gov-{proposal.space_id}-{proposal.proposal_id[:12]}",
|
|
348
|
+
chain_id=proposal.chain_id,
|
|
349
|
+
deterministic=DeterministicCondition(
|
|
350
|
+
target_address=proposal.target_address,
|
|
351
|
+
min_value_wei=0,
|
|
352
|
+
required_function_selectors=None,
|
|
353
|
+
check_native_balance=False,
|
|
354
|
+
),
|
|
355
|
+
semantic=SemanticCondition(
|
|
356
|
+
enabled=True,
|
|
357
|
+
policy_prompt=policy_prompt
|
|
358
|
+
or (
|
|
359
|
+
"Audit DAO governance proposal for hidden privilege escalation, "
|
|
360
|
+
"unverified contract upgrades, or discrepancies between proposal text and on-chain calldata."
|
|
361
|
+
),
|
|
362
|
+
risk_threshold=risk_threshold,
|
|
363
|
+
),
|
|
364
|
+
context_metadata={
|
|
365
|
+
"proposal_id": proposal.proposal_id,
|
|
366
|
+
"space_id": proposal.space_id,
|
|
367
|
+
"proposal_title": proposal.title,
|
|
368
|
+
"proposal_description": f"{proposal.title}\n\n{proposal.body}",
|
|
369
|
+
"calldata": proposal.calldata,
|
|
370
|
+
"tx_value_wei": proposal.tx_value_wei,
|
|
371
|
+
},
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
async def audit_proposals(
|
|
375
|
+
self,
|
|
376
|
+
engine: ConditionAgentEngine,
|
|
377
|
+
proposals: Optional[List[GovernanceProposal]] = None,
|
|
378
|
+
spaces: Optional[List[str]] = None,
|
|
379
|
+
limit: int = 3,
|
|
380
|
+
) -> List[GovernanceAuditReport]:
|
|
381
|
+
"""
|
|
382
|
+
Executes end-to-end security audits across governance proposals.
|
|
383
|
+
"""
|
|
384
|
+
target_proposals = proposals
|
|
385
|
+
if target_proposals is None:
|
|
386
|
+
target_proposals = await self.fetch_proposals(spaces=spaces, limit=limit)
|
|
387
|
+
|
|
388
|
+
reports: List[GovernanceAuditReport] = []
|
|
389
|
+
for prop in target_proposals:
|
|
390
|
+
payload = self.proposal_to_rule_payload(prop)
|
|
391
|
+
resp = await engine.process_rule(payload, source="governance_listener")
|
|
392
|
+
|
|
393
|
+
if resp.semantic_Evaluation is None:
|
|
394
|
+
alert_level: Literal["CRITICAL", "WARNING", "INFO"] = "INFO"
|
|
395
|
+
elif resp.semantic_Evaluation.recommended_action == "REJECT":
|
|
396
|
+
alert_level = "CRITICAL"
|
|
397
|
+
elif resp.semantic_Evaluation.recommended_action == "MANUAL_REVIEW":
|
|
398
|
+
alert_level = "WARNING"
|
|
399
|
+
else:
|
|
400
|
+
alert_level = "INFO"
|
|
401
|
+
|
|
402
|
+
reports.append(
|
|
403
|
+
GovernanceAuditReport(
|
|
404
|
+
proposal=prop,
|
|
405
|
+
rule_id=payload.rule_id,
|
|
406
|
+
agent_response=resp,
|
|
407
|
+
alert_level=alert_level,
|
|
408
|
+
)
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
return reports
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
class WebhookAlertDispatcher:
|
|
415
|
+
"""
|
|
416
|
+
Dispatches automated governance security alerts to external webhooks
|
|
417
|
+
(Discord, Slack, or generic HTTP endpoints) with x402 monetization links.
|
|
418
|
+
"""
|
|
419
|
+
|
|
420
|
+
def __init__(
|
|
421
|
+
self,
|
|
422
|
+
webhook_url: Optional[str] = None,
|
|
423
|
+
public_api_url: Optional[str] = None,
|
|
424
|
+
price_usdc: float = 0.015,
|
|
425
|
+
timeout: float = 10.0,
|
|
426
|
+
client: Optional[httpx.AsyncClient] = None,
|
|
427
|
+
):
|
|
428
|
+
self.webhook_url = (webhook_url or os.getenv("ALERT_WEBHOOK_URL") or "").strip() or None
|
|
429
|
+
self.public_api_url = (public_api_url or os.getenv("PUBLIC_API_URL") or "http://localhost:8000").rstrip("/")
|
|
430
|
+
self.price_usdc = price_usdc
|
|
431
|
+
self.timeout = timeout
|
|
432
|
+
self.client = client
|
|
433
|
+
|
|
434
|
+
def format_alert_payload(self, report: GovernanceAuditReport) -> Dict[str, Any]:
|
|
435
|
+
"""
|
|
436
|
+
Formats a governance audit report into Discord/Slack/generic compatible JSON payload
|
|
437
|
+
with x402 monetization links.
|
|
438
|
+
"""
|
|
439
|
+
prop = report.proposal
|
|
440
|
+
sem = report.agent_response.semantic_Evaluation
|
|
441
|
+
decision = sem.recommended_action if sem else "SKIPPED"
|
|
442
|
+
risk_score = sem.risk_score if sem else 0.0
|
|
443
|
+
summary = sem.summary if sem else "Stage 1 filtered"
|
|
444
|
+
flagged = list(sem.flagged_issues) if sem else []
|
|
445
|
+
|
|
446
|
+
audit_endpoint = f"{self.public_api_url}/evaluate"
|
|
447
|
+
content_text = (
|
|
448
|
+
f"🚨 **GOVERNANCE SECURITY ALERT [{report.alert_level}]** 🚨\n"
|
|
449
|
+
f"• **Space**: `{prop.space_id}`\n"
|
|
450
|
+
f"• **Title**: {prop.title}\n"
|
|
451
|
+
f"• **Decision**: `{decision}` (Risk Score: {risk_score:.1f})\n"
|
|
452
|
+
f"• **Target Address**: `{prop.target_address}`\n"
|
|
453
|
+
f"• **Summary**: {summary}\n"
|
|
454
|
+
f"💳 **x402 Monetized Audit**: `{audit_endpoint}` (${self.price_usdc:.4f} USDC)"
|
|
455
|
+
)
|
|
456
|
+
|
|
457
|
+
color_map = {
|
|
458
|
+
"CRITICAL": 0xFF0000,
|
|
459
|
+
"WARNING": 0xFFA500,
|
|
460
|
+
"INFO": 0x3498DB,
|
|
461
|
+
}
|
|
462
|
+
embed_color = color_map.get(report.alert_level, 0x808080)
|
|
463
|
+
|
|
464
|
+
embeds = [
|
|
465
|
+
{
|
|
466
|
+
"title": f"[{report.alert_level}] {prop.space_id}: {prop.title[:100]}",
|
|
467
|
+
"description": summary[:1000] if summary else "",
|
|
468
|
+
"color": embed_color,
|
|
469
|
+
"fields": [
|
|
470
|
+
{"name": "Decision", "value": str(decision), "inline": True},
|
|
471
|
+
{"name": "Risk Score", "value": f"{risk_score:.1f}", "inline": True},
|
|
472
|
+
{"name": "Target Address", "value": str(prop.target_address), "inline": False},
|
|
473
|
+
{
|
|
474
|
+
"name": "Flagged Issues",
|
|
475
|
+
"value": "\n".join(f"- {i}" for i in flagged) if flagged else "None",
|
|
476
|
+
"inline": False,
|
|
477
|
+
},
|
|
478
|
+
{
|
|
479
|
+
"name": "x402 Paid Audit",
|
|
480
|
+
"value": f"{audit_endpoint} (${self.price_usdc:.4f} USDC)",
|
|
481
|
+
"inline": False,
|
|
482
|
+
},
|
|
483
|
+
],
|
|
484
|
+
}
|
|
485
|
+
]
|
|
486
|
+
|
|
487
|
+
return {
|
|
488
|
+
"content": content_text,
|
|
489
|
+
"text": content_text,
|
|
490
|
+
"embeds": embeds,
|
|
491
|
+
"alert_level": report.alert_level,
|
|
492
|
+
"proposal_id": prop.proposal_id,
|
|
493
|
+
"space_id": prop.space_id,
|
|
494
|
+
"decision": decision,
|
|
495
|
+
"risk_score": risk_score,
|
|
496
|
+
"flagged_issues": flagged,
|
|
497
|
+
"x402_audit_endpoint": audit_endpoint,
|
|
498
|
+
"price_usdc": self.price_usdc,
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
async def dispatch_alert(self, report: GovernanceAuditReport) -> bool:
|
|
502
|
+
"""
|
|
503
|
+
Sends formatted alert payload to webhook URL.
|
|
504
|
+
Returns True on HTTP 2xx, False otherwise without raising unhandled exceptions.
|
|
505
|
+
"""
|
|
506
|
+
if not self.webhook_url:
|
|
507
|
+
return False
|
|
508
|
+
|
|
509
|
+
payload = self.format_alert_payload(report)
|
|
510
|
+
try:
|
|
511
|
+
if self.client:
|
|
512
|
+
resp = await self.client.post(self.webhook_url, json=payload)
|
|
513
|
+
else:
|
|
514
|
+
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
515
|
+
resp = await client.post(self.webhook_url, json=payload)
|
|
516
|
+
|
|
517
|
+
if 200 <= resp.status_code < 300:
|
|
518
|
+
return True
|
|
519
|
+
else:
|
|
520
|
+
logger.warning(
|
|
521
|
+
f"Webhook dispatch failed with HTTP {resp.status_code}: {resp.text}"
|
|
522
|
+
)
|
|
523
|
+
return False
|
|
524
|
+
except Exception as exc:
|
|
525
|
+
logger.warning(f"Webhook dispatch exception: {exc}")
|
|
526
|
+
return False
|
|
527
|
+
|
|
528
|
+
async def dispatch_batch(
|
|
529
|
+
self,
|
|
530
|
+
reports: List[GovernanceAuditReport],
|
|
531
|
+
min_alert_level: str = "WARNING",
|
|
532
|
+
) -> int:
|
|
533
|
+
"""
|
|
534
|
+
Dispatches alerts for all reports meeting or exceeding min_alert_level.
|
|
535
|
+
Returns the count of successfully delivered webhook requests.
|
|
536
|
+
"""
|
|
537
|
+
min_order = ALERT_SEVERITY_ORDER.get(min_alert_level.upper(), 2)
|
|
538
|
+
matching_reports = [
|
|
539
|
+
r for r in reports
|
|
540
|
+
if ALERT_SEVERITY_ORDER.get(r.alert_level, 0) >= min_order
|
|
541
|
+
]
|
|
542
|
+
sent_count = 0
|
|
543
|
+
for r in matching_reports:
|
|
544
|
+
success = await self.dispatch_alert(r)
|
|
545
|
+
if success:
|
|
546
|
+
sent_count += 1
|
|
547
|
+
return sent_count
|
|
548
|
+
|