-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathx402_client.py
More file actions
218 lines (169 loc) · 6.32 KB
/
x402_client.py
File metadata and controls
218 lines (169 loc) · 6.32 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
"""
x402 Client for Rug Munch Intelligence API.
Handles x402 payment flow: send request → get 402 → sign payment → retry with proof.
"""
import os
import json
import logging
from typing import Optional
from dataclasses import dataclass
import httpx
from eth_account import Account
logger = logging.getLogger(__name__)
RUG_MUNCH_URL = os.getenv("RUG_MUNCH_URL", "https://cryptorugmunch.app")
AGENT_API = f"{RUG_MUNCH_URL}/api/agent/v1"
# x402 payment networks
BASE_MAINNET = "eip155:8453"
SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"
@dataclass
class RiskResult:
"""Token risk assessment result."""
token_address: str
risk_score: int
risk_level: str
recommendation: str
honeypot_risk: bool
risk_factors: list
raw: dict
@property
def is_safe(self) -> bool:
return self.recommendation == "SAFE"
@property
def is_dangerous(self) -> bool:
return self.recommendation == "AVOID"
def _get_x402_session() -> httpx.Client:
"""Create an httpx client with x402 payment handling."""
try:
from x402.client import x402ClientSync
from x402.client.config import x402ClientConfig
from x402.mechanisms.evm.exact import ExactEvmClientScheme
from x402.client.types import SchemeRegistration
from eth_account import Account
private_key = os.environ.get("WALLET_PRIVATE_KEY", "")
if not private_key:
raise ValueError("WALLET_PRIVATE_KEY not set")
account = Account.from_key(private_key)
signer = account # x402 ExactEvmClientScheme accepts eth_account.Account
scheme = ExactEvmClientScheme(signer)
reg = SchemeRegistration(
network=BASE_MAINNET,
client=scheme,
x402_version=2,
)
config = x402ClientConfig(schemes=[reg])
core = x402ClientSync.from_config(config)
# Return a session that auto-handles 402 responses
from x402.integrations.httpx import x402_httpx_client
return x402_httpx_client(core)
except ImportError:
logger.warning("x402 SDK not installed — falling back to manual payment flow")
return httpx.Client(timeout=60.0)
def _make_request(method: str, path: str, **kwargs) -> dict:
"""Make an x402-authenticated request to Rug Munch API."""
url = f"{AGENT_API}/{path}"
max_spend = float(os.getenv("MAX_SPEND_PER_CHECK", "0.50"))
client = _get_x402_session()
try:
if method == "GET":
resp = client.get(url, **kwargs)
else:
resp = client.post(url, **kwargs)
if resp.status_code == 402:
logger.error(f"Payment required but x402 client didn't handle it. "
f"Check wallet balance and WALLET_PRIVATE_KEY.")
raise PaymentError(f"402 Payment Required for {path}")
resp.raise_for_status()
return resp.json()
finally:
client.close()
class PaymentError(Exception):
"""Raised when x402 payment fails."""
pass
# ─── Public API ───────────────────────────────────────────────
def check_risk(token_address: str, chain: str = "solana") -> RiskResult:
"""
Check a token's risk score. Costs $0.04 USDC via x402.
Args:
token_address: Token mint (Solana) or contract address (EVM)
chain: Blockchain (solana, ethereum, base, etc.)
Returns:
RiskResult with score, recommendation, and risk factors
"""
data = _make_request("POST", "check-risk", json={
"token_address": token_address,
"chain": chain,
})
return RiskResult(
token_address=data.get("token_address", token_address),
risk_score=data.get("risk_score", -1),
risk_level=data.get("risk_level", "unknown"),
recommendation=data.get("recommendation", "UNKNOWN"),
honeypot_risk=data.get("honeypot_risk", False),
risk_factors=data.get("risk_factors", []),
raw=data,
)
def check_batch(token_addresses: list, chain: str = "solana") -> list:
"""
Batch risk check for up to 20 tokens. Costs $0.30 USDC via x402.
"""
data = _make_request("POST", "check-batch", json={
"tokens": token_addresses[:20],
"chain": chain,
})
return data.get("results", [])
def marcus_quick(token_address: str, chain: str = "solana",
question: str = None) -> dict:
"""
AI forensic verdict by Marcus Aurelius. Costs $0.15 USDC via x402.
"""
payload = {"token_address": token_address, "chain": chain}
if question:
payload["question"] = question
return _make_request("POST", "marcus-quick", json=payload)
def marcus_forensics(token_address: str, chain: str = "solana") -> dict:
"""
Full AI forensic investigation. Costs $0.50 USDC via x402.
"""
return _make_request("POST", "marcus-forensics", json={
"token_address": token_address,
"chain": chain,
})
def deployer_history(deployer_address: str) -> dict:
"""
Check deployer's history. Costs $0.06 USDC via x402.
"""
return _make_request("GET", f"deployer/{deployer_address}")
def holder_deepdive(token_address: str) -> dict:
"""
Deep holder analysis. Costs $0.10 USDC via x402.
"""
return _make_request("GET", f"holder-deepdive/{token_address}")
def token_intel(token_address: str) -> dict:
"""
Full token intelligence. Costs $0.06 USDC via x402.
"""
return _make_request("GET", f"token-intel/{token_address}")
def watch_token(token_address: str, webhook_url: str,
watch_type: str = "rug_detected") -> dict:
"""
Set up webhook monitoring. Costs $0.20 USDC for 7 days via x402.
"""
return _make_request("POST", "watch", json={
"token_address": token_address,
"webhook_url": webhook_url,
"watch_type": watch_type,
})
def get_status() -> dict:
"""
Get API status, pricing, and performance metrics. FREE (no x402).
"""
resp = httpx.get(f"{AGENT_API}/status", timeout=10.0)
resp.raise_for_status()
return resp.json()
def discover_services() -> dict:
"""
Discover all Rug Munch endpoints via /.well-known/x402. FREE.
"""
resp = httpx.get(f"{RUG_MUNCH_URL}/.well-known/x402", timeout=10.0)
resp.raise_for_status()
return resp.json()