-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
315 lines (253 loc) · 10.9 KB
/
agent.py
File metadata and controls
315 lines (253 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#!/usr/bin/env python3
"""
x402 Safe Trading Agent — Check risk before every trade.
Usage:
python agent.py check <token_address> [--chain solana]
python agent.py batch <addr1> <addr2> ... [--chain solana]
python agent.py discover
python agent.py status
python agent.py watch <token_address> --webhook <url>
python agent.py demo
"""
import os
import sys
import argparse
import logging
from dotenv import load_dotenv
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich import print as rprint
load_dotenv()
from x402_client import (
check_risk, check_batch, marcus_quick, marcus_forensics,
deployer_history, holder_deepdive, token_intel, watch_token,
get_status, discover_services, PaymentError,
)
console = Console()
logger = logging.getLogger(__name__)
# Thresholds from env
RISK_THRESHOLD = int(os.getenv("RISK_THRESHOLD", "70"))
DEEP_THRESHOLD = int(os.getenv("DEEP_ANALYSIS_THRESHOLD", "40"))
def cmd_check(args):
"""Check a single token's risk."""
console.print(f"\n🔍 Checking risk for [bold]{args.token}[/bold] on {args.chain}...\n")
try:
result = check_risk(args.token, chain=args.chain)
except PaymentError as e:
console.print(f"[red]💳 Payment failed:[/red] {e}")
console.print(" Check your WALLET_PRIVATE_KEY and USDC balance on Base.")
return
# Display result
color = "green" if result.is_safe else "red" if result.is_dangerous else "yellow"
score_bar = "█" * (result.risk_score // 5) + "░" * (20 - result.risk_score // 5)
console.print(Panel(
f"[bold]Risk Score:[/bold] [{color}]{result.risk_score}/100[/{color}] "
f"[{score_bar}]\n"
f"[bold]Level:[/bold] {result.risk_level}\n"
f"[bold]Recommendation:[/bold] [{color}]{result.recommendation}[/{color}]\n"
f"[bold]Honeypot:[/bold] {'🚨 YES' if result.honeypot_risk else '✅ No'}\n"
f"\n[bold]Risk Factors:[/bold]\n" +
"\n".join(f" • {f}" for f in result.risk_factors) if result.risk_factors
else "[dim]No risk factors identified[/dim]",
title=f"🛡️ {result.token_address[:16]}...",
border_style=color,
))
# Trading decision
if result.risk_score >= RISK_THRESHOLD:
console.print(f"\n🚨 [red bold]SKIP[/red bold] — Risk score {result.risk_score} exceeds threshold {RISK_THRESHOLD}")
elif result.risk_score >= DEEP_THRESHOLD:
console.print(f"\n⚠️ [yellow]BORDERLINE[/yellow] — Score {result.risk_score} is between {DEEP_THRESHOLD}-{RISK_THRESHOLD}")
console.print(" Consider running: [bold]python agent.py deep {token}[/bold] for AI analysis ($0.50)")
else:
console.print(f"\n✅ [green bold]PROCEED[/green bold] — Risk score {result.risk_score} is below threshold {DEEP_THRESHOLD}")
def cmd_batch(args):
"""Batch check multiple tokens."""
tokens = args.tokens
console.print(f"\n🔍 Batch checking {len(tokens)} tokens on {args.chain}...\n")
try:
results = check_batch(tokens, chain=args.chain)
except PaymentError as e:
console.print(f"[red]💳 Payment failed:[/red] {e}")
return
table = Table(title="Batch Risk Results")
table.add_column("Token", style="dim", max_width=20)
table.add_column("Score", justify="right")
table.add_column("Level")
table.add_column("Recommendation")
table.add_column("Decision")
for r in results:
score = r.get("risk_score", -1)
rec = r.get("recommendation", "?")
color = "green" if rec == "SAFE" else "red" if rec == "AVOID" else "yellow"
decision = "✅ TRADE" if score < DEEP_THRESHOLD else "🚨 SKIP" if score >= RISK_THRESHOLD else "⚠️ REVIEW"
addr = r.get("token_address", "?")
table.add_row(
f"{addr[:12]}...",
f"[{color}]{score}[/{color}]",
r.get("risk_level", "?"),
f"[{color}]{rec}[/{color}]",
decision,
)
console.print(table)
def cmd_deep(args):
"""Deep AI forensic analysis."""
console.print(f"\n🧠 Running Marcus AI forensics on [bold]{args.token}[/bold]...\n")
console.print("[dim]This uses Claude Sonnet 4 — costs $0.50, takes 15-30s[/dim]\n")
try:
result = marcus_forensics(args.token, chain=args.chain)
except PaymentError as e:
console.print(f"[red]💳 Payment failed:[/red] {e}")
return
console.print(Panel(
f"[bold]Verdict:[/bold] {result.get('verdict', '?')}\n"
f"[bold]Risk Score:[/bold] {result.get('risk_score', '?')}\n"
f"[bold]Confidence:[/bold] {result.get('confidence', '?')}%\n\n"
f"{result.get('analysis', 'No analysis available')}",
title="🗿 Marcus Aurelius — Forensic Analysis",
border_style="blue",
))
findings = result.get("key_findings", [])
if findings:
console.print("\n[bold]Key Findings:[/bold]")
for f in findings:
console.print(f" • {f}")
console.print(f"\n[bold]Recommendation:[/bold] {result.get('recommendation', '?')}")
def cmd_discover(args):
"""Discover available endpoints."""
console.print("\n🔎 Discovering Rug Munch Intelligence endpoints...\n")
try:
data = discover_services()
except Exception as e:
console.print(f"[red]Discovery failed:[/red] {e}")
return
table = Table(title="Available Endpoints (x402)")
table.add_column("Endpoint", style="bold")
table.add_column("Method")
table.add_column("Price")
table.add_column("Description", max_width=50)
for ep in data.get("paid_endpoints", []):
table.add_row(
ep.get("path", "?"),
ep.get("method", "?"),
ep.get("price", "?"),
ep.get("description", "")[:50],
)
console.print(table)
free = data.get("free_endpoints", [])
if free:
console.print(f"\n[dim]+ {len(free)} free endpoints (status, health, feedback, etc.)[/dim]")
def cmd_status(args):
"""Get API status and performance metrics."""
console.print("\n📊 Rug Munch Intelligence — Service Status\n")
try:
data = get_status()
except Exception as e:
console.print(f"[red]Status check failed:[/red] {e}")
return
console.print(f" Service: [bold]{data.get('service', '?')}[/bold]")
console.print(f" Version: {data.get('version', '?')}")
trust = data.get("trust_score", {})
if trust:
console.print(f" Trust Score: [bold green]{trust.get('composite', '?')}/100[/bold green]")
perf = data.get("performance", {})
if perf:
console.print(f" Latency (p50): {perf.get('latency_p50_ms', '?')}ms")
console.print(f" Uptime: {perf.get('uptime_pct', '?')}%")
def cmd_watch(args):
"""Set up token monitoring with webhook alerts."""
console.print(f"\n👁️ Setting up watch for [bold]{args.token}[/bold]...")
console.print(f" Webhook: {args.webhook}")
console.print(f" Type: {args.type}\n")
try:
result = watch_token(args.token, args.webhook, watch_type=args.type)
except PaymentError as e:
console.print(f"[red]💳 Payment failed:[/red] {e}")
return
console.print(f" ✅ Watch ID: {result.get('watch_id')}")
console.print(f" 📅 Expires: {result.get('expires_at')}")
console.print(f" 🔔 Status: {result.get('status')}")
def cmd_demo(args):
"""Run a demo flow showing the full agent pipeline."""
console.print(Panel(
"[bold]x402 Safe Trading Agent — Demo Flow[/bold]\n\n"
"This demo shows the full pipeline:\n"
"1. Discover endpoints via /.well-known/x402\n"
"2. Check API status (free)\n"
"3. Risk-check a known safe token\n"
"4. Risk-check a known risky token\n\n"
"[dim]No actual trades are executed. Risk checks cost $0.04 each.[/dim]",
title="🎬 Demo Mode",
))
if input("\nProceed? [y/N] ").lower() != "y":
return
# Step 1: Discovery
console.print("\n[bold]Step 1: Discover endpoints[/bold]")
try:
services = discover_services()
paid = len(services.get("paid_endpoints", []))
console.print(f" ✅ Found {paid} paid endpoints via /.well-known/x402")
except Exception as e:
console.print(f" ⚠️ Discovery failed: {e} (continuing with hardcoded URL)")
# Step 2: Status
console.print("\n[bold]Step 2: Check service status[/bold]")
try:
status = get_status()
console.print(f" ✅ Service: {status.get('service', '?')}")
trust = status.get("trust_score", {})
console.print(f" ✅ Trust: {trust.get('composite', '?')}/100")
except Exception as e:
console.print(f" ⚠️ Status check failed: {e}")
# Step 3: Check SOL (should be safe)
console.print("\n[bold]Step 3: Risk-check SOL (wrapped)[/bold]")
console.print(" 💳 Paying $0.04 USDC via x402...")
try:
sol = check_risk("So11111111111111111111111111111111111111112")
console.print(f" ✅ Risk: {sol.risk_score}/100 → {sol.recommendation}")
except Exception as e:
console.print(f" ❌ Failed: {e}")
console.print("\n[bold]Demo complete![/bold] 🎉")
def main():
parser = argparse.ArgumentParser(
description="x402 Safe Trading Agent — Check risk before every trade"
)
sub = parser.add_subparsers(dest="command")
# check
p_check = sub.add_parser("check", help="Check a single token's risk")
p_check.add_argument("token", help="Token address")
p_check.add_argument("--chain", default="solana")
p_check.set_defaults(func=cmd_check)
# batch
p_batch = sub.add_parser("batch", help="Batch check multiple tokens")
p_batch.add_argument("tokens", nargs="+", help="Token addresses")
p_batch.add_argument("--chain", default="solana")
p_batch.set_defaults(func=cmd_batch)
# deep
p_deep = sub.add_parser("deep", help="Deep AI forensic analysis")
p_deep.add_argument("token", help="Token address")
p_deep.add_argument("--chain", default="solana")
p_deep.set_defaults(func=cmd_deep)
# discover
p_discover = sub.add_parser("discover", help="Discover available endpoints")
p_discover.set_defaults(func=cmd_discover)
# status
p_status = sub.add_parser("status", help="Get API status")
p_status.set_defaults(func=cmd_status)
# watch
p_watch = sub.add_parser("watch", help="Set up token monitoring")
p_watch.add_argument("token", help="Token address")
p_watch.add_argument("--webhook", required=True, help="Webhook URL")
p_watch.add_argument("--type", default="rug_detected",
choices=["risk_change", "rug_detected", "price_drop", "all"])
p_watch.set_defaults(func=cmd_watch)
# demo
p_demo = sub.add_parser("demo", help="Run demo flow")
p_demo.set_defaults(func=cmd_demo)
args = parser.parse_args()
if not args.command:
parser.print_help()
return
args.func(args)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
main()