polypad-agent 2.0.0__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.
- polypad_agent/__init__.py +85 -0
- polypad_agent/binding.py +55 -0
- polypad_agent/client.py +380 -0
- polypad_agent/constants.py +144 -0
- polypad_agent/errors.py +80 -0
- polypad_agent/prepare.py +180 -0
- polypad_agent/spend_vault.py +217 -0
- polypad_agent/tools.py +74 -0
- polypad_agent/x402.py +308 -0
- polypad_agent-2.0.0.dist-info/METADATA +105 -0
- polypad_agent-2.0.0.dist-info/RECORD +13 -0
- polypad_agent-2.0.0.dist-info/WHEEL +5 -0
- polypad_agent-2.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""polypad-agent — thin typed client for the Polypad agent API (MCP) on Robinhood Chain."""
|
|
2
|
+
|
|
3
|
+
from .binding import connect_url, decode_wallet_token
|
|
4
|
+
from .client import CHAIN_ID, DEFAULT_RPC_URL, MCP_URL, SITE_ORIGIN, PolypadClient
|
|
5
|
+
from .constants import (
|
|
6
|
+
ACTION_LIMITS,
|
|
7
|
+
CHAIN_NAME,
|
|
8
|
+
ERROR_MEANINGS,
|
|
9
|
+
EXPLORER,
|
|
10
|
+
MCP_ENDPOINT,
|
|
11
|
+
MCP_PROTOCOL_VERSION,
|
|
12
|
+
RATE_LIMITS,
|
|
13
|
+
SERVER_VERSION,
|
|
14
|
+
SPEND_VAULT_ADDRESS,
|
|
15
|
+
VAULT_TOKENS,
|
|
16
|
+
X402,
|
|
17
|
+
X402_PRODUCTS,
|
|
18
|
+
x402_product,
|
|
19
|
+
)
|
|
20
|
+
from .errors import PolypadConfirmTimeoutError, PolypadError, PolypadTxFailedError
|
|
21
|
+
from .prepare import confirm, sign_and_send, sign_send_and_confirm
|
|
22
|
+
from .spend_vault import (
|
|
23
|
+
build_create_key_tx,
|
|
24
|
+
build_deposit_tx,
|
|
25
|
+
build_revoke_key_tx,
|
|
26
|
+
build_withdraw_tx,
|
|
27
|
+
get_key_status,
|
|
28
|
+
get_vault_balance,
|
|
29
|
+
spend_vault_key_flow,
|
|
30
|
+
)
|
|
31
|
+
from .tools import PREPARE_TOOLS, TOOL_NAMES, is_prepare_tool
|
|
32
|
+
from .x402 import (
|
|
33
|
+
encode_payment_header,
|
|
34
|
+
fetch_with_x402,
|
|
35
|
+
next_permit2_nonce,
|
|
36
|
+
pay_for_report,
|
|
37
|
+
product_url,
|
|
38
|
+
sign_x402_payment,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"PolypadClient",
|
|
43
|
+
"PolypadError",
|
|
44
|
+
"PolypadTxFailedError",
|
|
45
|
+
"PolypadConfirmTimeoutError",
|
|
46
|
+
"MCP_URL",
|
|
47
|
+
"MCP_ENDPOINT",
|
|
48
|
+
"SITE_ORIGIN",
|
|
49
|
+
"CHAIN_ID",
|
|
50
|
+
"DEFAULT_RPC_URL",
|
|
51
|
+
"connect_url",
|
|
52
|
+
"decode_wallet_token",
|
|
53
|
+
"pay_for_report",
|
|
54
|
+
"confirm",
|
|
55
|
+
"sign_and_send",
|
|
56
|
+
"sign_send_and_confirm",
|
|
57
|
+
"TOOL_NAMES",
|
|
58
|
+
"PREPARE_TOOLS",
|
|
59
|
+
"is_prepare_tool",
|
|
60
|
+
"build_create_key_tx",
|
|
61
|
+
"build_deposit_tx",
|
|
62
|
+
"build_revoke_key_tx",
|
|
63
|
+
"build_withdraw_tx",
|
|
64
|
+
"get_key_status",
|
|
65
|
+
"get_vault_balance",
|
|
66
|
+
"spend_vault_key_flow",
|
|
67
|
+
"encode_payment_header",
|
|
68
|
+
"fetch_with_x402",
|
|
69
|
+
"next_permit2_nonce",
|
|
70
|
+
"product_url",
|
|
71
|
+
"sign_x402_payment",
|
|
72
|
+
"ACTION_LIMITS",
|
|
73
|
+
"CHAIN_NAME",
|
|
74
|
+
"ERROR_MEANINGS",
|
|
75
|
+
"EXPLORER",
|
|
76
|
+
"MCP_PROTOCOL_VERSION",
|
|
77
|
+
"RATE_LIMITS",
|
|
78
|
+
"SERVER_VERSION",
|
|
79
|
+
"SPEND_VAULT_ADDRESS",
|
|
80
|
+
"VAULT_TOKENS",
|
|
81
|
+
"X402",
|
|
82
|
+
"X402_PRODUCTS",
|
|
83
|
+
"x402_product",
|
|
84
|
+
]
|
|
85
|
+
__version__ = "2.0.0"
|
polypad_agent/binding.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Persistent wallet binding — the token from /sign?connect=1.
|
|
2
|
+
|
|
3
|
+
Connect once: the user opens the connect URL, signs one message (not a transaction), and gets
|
|
4
|
+
a token. The SDK stores it (POLYPAD_WALLET_TOKEN) and passes it instead of a wallet address on
|
|
5
|
+
every prepare call. The server recovers the wallet from the signature — no server storage, no
|
|
6
|
+
per-call `from`. The token lasts 90 days; after that, connect again.
|
|
7
|
+
|
|
8
|
+
The token is base64url JSON {v: 1, address, exp, sig}. This module only decodes it (to show
|
|
9
|
+
which wallet is bound and when it expires). Verification happens server-side on every call.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import base64
|
|
13
|
+
import json
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
SITE_ORIGIN = "https://polypad.family"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def decode_wallet_token(token: str):
|
|
20
|
+
"""Decode a wallet token. Returns None when it is not a token at all."""
|
|
21
|
+
try:
|
|
22
|
+
padded = token.strip() + "=" * (-len(token.strip()) % 4)
|
|
23
|
+
text = base64.urlsafe_b64decode(padded).decode("utf-8")
|
|
24
|
+
parsed = json.loads(text)
|
|
25
|
+
except Exception:
|
|
26
|
+
return None
|
|
27
|
+
if not isinstance(parsed, dict):
|
|
28
|
+
return None
|
|
29
|
+
if parsed.get("v") != 1 or not isinstance(parsed.get("address"), str):
|
|
30
|
+
return None
|
|
31
|
+
if not isinstance(parsed.get("exp"), (int, float)) or not isinstance(parsed.get("sig"), str):
|
|
32
|
+
return None
|
|
33
|
+
address = parsed["address"]
|
|
34
|
+
if len(address) != 42 or not address.startswith("0x"):
|
|
35
|
+
return None
|
|
36
|
+
try:
|
|
37
|
+
int(address[2:], 16)
|
|
38
|
+
except ValueError:
|
|
39
|
+
return None
|
|
40
|
+
exp = int(parsed["exp"])
|
|
41
|
+
return {"address": address, "exp": exp, "expired": exp <= int(time.time())}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def connect_url(return_url=None, origin=SITE_ORIGIN):
|
|
45
|
+
"""The connect URL to show the user so they can bind a wallet and get a token.
|
|
46
|
+
|
|
47
|
+
When return_url is given, the page sends them back to it with
|
|
48
|
+
?walletToken=...&wallet=... after connecting.
|
|
49
|
+
"""
|
|
50
|
+
from urllib.parse import urlencode
|
|
51
|
+
|
|
52
|
+
params = {"connect": "1"}
|
|
53
|
+
if return_url:
|
|
54
|
+
params["r"] = return_url
|
|
55
|
+
return f"{origin}/sign?{urlencode(params)}"
|
polypad_agent/client.py
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
"""polypad-agent — thin typed client for the Polypad agent API (MCP) on Robinhood Chain.
|
|
2
|
+
|
|
3
|
+
The client talks JSON-RPC to https://polypad.family/api/mcp. Reads only fetch data. Prepare
|
|
4
|
+
calls return an unsigned transaction, a plain summary, and a signing link — nothing moves until
|
|
5
|
+
somebody signs.
|
|
6
|
+
|
|
7
|
+
Wallet binding (persistent): connect once on /sign?connect=1, store the token, and pass it here.
|
|
8
|
+
The client attaches it to every prepare call instead of a wallet address; the server resolves the
|
|
9
|
+
wallet from the token. Per-call `from` still works as the fallback — pass it explicitly and the
|
|
10
|
+
client leaves the token out for that call.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import itertools
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import time
|
|
18
|
+
|
|
19
|
+
import requests
|
|
20
|
+
|
|
21
|
+
from .binding import connect_url, decode_wallet_token
|
|
22
|
+
from .constants import MCP_ENDPOINT, SERVER_VERSION
|
|
23
|
+
from .errors import PolypadError, error_from_body, is_api_error_body
|
|
24
|
+
from .tools import is_prepare_tool
|
|
25
|
+
|
|
26
|
+
MCP_URL = MCP_ENDPOINT
|
|
27
|
+
SITE_ORIGIN = "https://polypad.family"
|
|
28
|
+
CHAIN_ID = 4663
|
|
29
|
+
DEFAULT_RPC_URL = "https://robinhood.drpc.org"
|
|
30
|
+
|
|
31
|
+
PREPARE_TOOLS = {
|
|
32
|
+
"polypad_prepare_buy",
|
|
33
|
+
"polypad_prepare_sell",
|
|
34
|
+
"polypad_prepare_nft_buy",
|
|
35
|
+
"polypad_prepare_fund_create",
|
|
36
|
+
"polypad_prepare_fund_mint",
|
|
37
|
+
"polypad_prepare_fund_redeem",
|
|
38
|
+
"polypad_prepare_token_launch",
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
# Prepare tools plus intent: the calls that take a wallet (from the token or an explicit `from`).
|
|
42
|
+
_TOKEN_TOOLS = PREPARE_TOOLS | {"polypad_intent"}
|
|
43
|
+
|
|
44
|
+
_KEY_LOOKALIKE = re.compile(r"^(0x)?[0-9a-fA-F]{64}$")
|
|
45
|
+
_ADDRESS_RE = re.compile(r"^0x[0-9a-fA-F]{40}$")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _reject_key_material(args):
|
|
49
|
+
"""The server refuses anything that looks like key material. Check first, so nothing sensitive is ever sent."""
|
|
50
|
+
|
|
51
|
+
def walk(value):
|
|
52
|
+
if isinstance(value, str) and _KEY_LOOKALIKE.match(value.strip()):
|
|
53
|
+
raise PolypadError(
|
|
54
|
+
"Do not send private keys or seed phrases. Polypad never needs them. Nothing was sent.",
|
|
55
|
+
"key_material_rejected",
|
|
56
|
+
)
|
|
57
|
+
if isinstance(value, list):
|
|
58
|
+
for item in value:
|
|
59
|
+
walk(item)
|
|
60
|
+
elif isinstance(value, dict):
|
|
61
|
+
for item in value.values():
|
|
62
|
+
walk(item)
|
|
63
|
+
|
|
64
|
+
walk(args)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class PolypadClient:
|
|
68
|
+
def __init__(self, mcp_url=None, wallet_token=None, client_name=None, session=None, ref=None, timeout=30):
|
|
69
|
+
self.mcp_url = mcp_url or MCP_URL
|
|
70
|
+
self.wallet_token = wallet_token or os.environ.get("POLYPAD_WALLET_TOKEN") or None
|
|
71
|
+
self.client_name = client_name or "polypad-agent"
|
|
72
|
+
self.session = session or requests.Session()
|
|
73
|
+
self.default_ref = ref
|
|
74
|
+
self.timeout = timeout
|
|
75
|
+
self._ids = itertools.count(1)
|
|
76
|
+
|
|
77
|
+
# ---- binding ------------------------------------------------------------
|
|
78
|
+
|
|
79
|
+
def set_wallet_token(self, token):
|
|
80
|
+
"""Store a wallet token (from /sign?connect=1). Later prepare calls resolve the wallet from it."""
|
|
81
|
+
self.wallet_token = token or None
|
|
82
|
+
|
|
83
|
+
def wallet_address(self):
|
|
84
|
+
"""The wallet bound by the stored token, or None when no token is set."""
|
|
85
|
+
if not self.wallet_token:
|
|
86
|
+
return None
|
|
87
|
+
info = decode_wallet_token(self.wallet_token)
|
|
88
|
+
return info["address"] if info else None
|
|
89
|
+
|
|
90
|
+
def connect_url(self, return_url=None):
|
|
91
|
+
"""The connect URL to show the user so they can bind a wallet and get a token."""
|
|
92
|
+
return connect_url(return_url=return_url, origin=SITE_ORIGIN)
|
|
93
|
+
|
|
94
|
+
# ---- raw call -----------------------------------------------------------
|
|
95
|
+
|
|
96
|
+
def rpc(self, method, params=None):
|
|
97
|
+
"""Low-level JSON-RPC call. Returns the ``result`` object, or raises PolypadError."""
|
|
98
|
+
request_id = next(self._ids)
|
|
99
|
+
headers = {"content-type": "application/json", "x-polypad-client": self.client_name}
|
|
100
|
+
try:
|
|
101
|
+
response = self.session.post(
|
|
102
|
+
self.mcp_url,
|
|
103
|
+
json={"jsonrpc": "2.0", "id": request_id, "method": method, "params": params or {}},
|
|
104
|
+
headers=headers,
|
|
105
|
+
timeout=self.timeout,
|
|
106
|
+
)
|
|
107
|
+
except requests.RequestException as exc:
|
|
108
|
+
raise PolypadError(
|
|
109
|
+
f"Could not reach {self.mcp_url}: {exc}. Check your connection and try again.",
|
|
110
|
+
"network_error",
|
|
111
|
+
) from exc
|
|
112
|
+
if not response.ok:
|
|
113
|
+
text = response.text or ""
|
|
114
|
+
raise PolypadError(
|
|
115
|
+
"The Polypad API answered HTTP " + str(response.status_code) + (f": {text[:200]}" if text else "."),
|
|
116
|
+
"http_error",
|
|
117
|
+
status=response.status_code,
|
|
118
|
+
)
|
|
119
|
+
try:
|
|
120
|
+
reply = response.json()
|
|
121
|
+
except ValueError as exc:
|
|
122
|
+
raise PolypadError("The Polypad API answered with something that was not JSON.", "invalid_response") from exc
|
|
123
|
+
if reply.get("error"):
|
|
124
|
+
error = reply["error"]
|
|
125
|
+
raise PolypadError(
|
|
126
|
+
error.get("message", "JSON-RPC error."),
|
|
127
|
+
f"rpc_{error.get('code')}",
|
|
128
|
+
extra={"json_rpc_code": error.get("code"), **(error.get("data") or {})},
|
|
129
|
+
)
|
|
130
|
+
return reply.get("result") or {}
|
|
131
|
+
|
|
132
|
+
def initialize(self):
|
|
133
|
+
"""The MCP handshake. Optional — the server is stateless and answers tools/call without it."""
|
|
134
|
+
return self.rpc(
|
|
135
|
+
"initialize",
|
|
136
|
+
{
|
|
137
|
+
"protocolVersion": "2025-06-18",
|
|
138
|
+
"capabilities": {},
|
|
139
|
+
"clientInfo": {"name": self.client_name, "version": SERVER_VERSION},
|
|
140
|
+
},
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
def ping(self):
|
|
144
|
+
"""Returns True when the server answers."""
|
|
145
|
+
self.rpc("ping")
|
|
146
|
+
return True
|
|
147
|
+
|
|
148
|
+
def list_tools(self):
|
|
149
|
+
"""The 21 tools, with names, descriptions, and input schemas, straight from the server."""
|
|
150
|
+
result = self.rpc("tools/list")
|
|
151
|
+
return result.get("tools") or []
|
|
152
|
+
|
|
153
|
+
def call_tool(self, name, arguments=None):
|
|
154
|
+
"""One MCP tools/call. Raises PolypadError when the tool answers with an error."""
|
|
155
|
+
args = dict(arguments or {})
|
|
156
|
+
if self.default_ref and args.get("ref") is None and (is_prepare_tool(name) or name == "polypad_intent"):
|
|
157
|
+
args["ref"] = self.default_ref
|
|
158
|
+
if name in _TOKEN_TOOLS:
|
|
159
|
+
if self.wallet_token and "walletToken" not in args and "from" not in args:
|
|
160
|
+
args["walletToken"] = self.wallet_token
|
|
161
|
+
_reject_key_material(args)
|
|
162
|
+
from_value = args.get("from")
|
|
163
|
+
if isinstance(from_value, str) and not _ADDRESS_RE.match(from_value.strip()):
|
|
164
|
+
raise PolypadError("`from` must be a 0x wallet address.", "invalid_params", extra={"field": "from"})
|
|
165
|
+
result = self.rpc("tools/call", {"name": name, "arguments": args})
|
|
166
|
+
if result.get("isError"):
|
|
167
|
+
structured = result.get("structuredContent")
|
|
168
|
+
if is_api_error_body(structured):
|
|
169
|
+
raise error_from_body(structured)
|
|
170
|
+
content = result.get("content") or []
|
|
171
|
+
text = content[0].get("text", "") if content else ""
|
|
172
|
+
try:
|
|
173
|
+
parsed = json.loads(text)
|
|
174
|
+
except ValueError:
|
|
175
|
+
parsed = None
|
|
176
|
+
if is_api_error_body(parsed):
|
|
177
|
+
raise error_from_body(parsed)
|
|
178
|
+
raise PolypadError(text[:400] or f"The {name} tool reported an error.", "tool_error")
|
|
179
|
+
out = result.get("structuredContent")
|
|
180
|
+
if out is None and result.get("content"):
|
|
181
|
+
try:
|
|
182
|
+
out = json.loads(result["content"][0]["text"])
|
|
183
|
+
except (ValueError, KeyError, IndexError):
|
|
184
|
+
out = None
|
|
185
|
+
if not isinstance(out, dict):
|
|
186
|
+
raise PolypadError("MCP endpoint answered with no result.", "bad_response")
|
|
187
|
+
if out.get("ok") is False:
|
|
188
|
+
err = out.get("error") or {}
|
|
189
|
+
raise PolypadError(err.get("message", "The tool call failed."), err.get("code", "tool_error"))
|
|
190
|
+
return out
|
|
191
|
+
|
|
192
|
+
# ---- reads (no wallet, no signature) ------------------------------------
|
|
193
|
+
|
|
194
|
+
def what_can_i_do(self):
|
|
195
|
+
return self.call_tool("polypad_what_can_i_do", {})
|
|
196
|
+
|
|
197
|
+
def intent(self, args):
|
|
198
|
+
return self.call_tool("polypad_intent", args)
|
|
199
|
+
|
|
200
|
+
def list_tokens(self, **kwargs):
|
|
201
|
+
return self.call_tool("polypad_list_tokens", kwargs)
|
|
202
|
+
|
|
203
|
+
def get_token(self, token):
|
|
204
|
+
return self.call_tool("polypad_get_token", {"token": token})
|
|
205
|
+
|
|
206
|
+
def token_protections(self, token):
|
|
207
|
+
return self.call_tool("polypad_token_protections", {"token": token})
|
|
208
|
+
|
|
209
|
+
def quote_trade(self, **kwargs):
|
|
210
|
+
return self.call_tool("polypad_quote_trade", kwargs)
|
|
211
|
+
|
|
212
|
+
def list_nfts(self, **kwargs):
|
|
213
|
+
return self.call_tool("polypad_list_nfts", kwargs)
|
|
214
|
+
|
|
215
|
+
def list_nft_listings(self, **kwargs):
|
|
216
|
+
return self.call_tool("polypad_list_nft_listings", kwargs)
|
|
217
|
+
|
|
218
|
+
def list_funds(self, **kwargs):
|
|
219
|
+
return self.call_tool("polypad_list_funds", kwargs)
|
|
220
|
+
|
|
221
|
+
def get_fund(self, fund):
|
|
222
|
+
return self.call_tool("polypad_get_fund", {"fund": fund})
|
|
223
|
+
|
|
224
|
+
def list_fund_templates(self):
|
|
225
|
+
return self.call_tool("polypad_list_fund_templates", {})
|
|
226
|
+
|
|
227
|
+
def portfolio(self, address):
|
|
228
|
+
return self.call_tool("polypad_portfolio", {"address": address})
|
|
229
|
+
|
|
230
|
+
def stats(self):
|
|
231
|
+
return self.call_tool("polypad_stats", {})
|
|
232
|
+
|
|
233
|
+
def get_tx_status(self, tx_hash):
|
|
234
|
+
"""One status check. Pending means the transaction is still travelling."""
|
|
235
|
+
return self.call_tool("polypad_get_tx_status", {"hash": tx_hash})
|
|
236
|
+
|
|
237
|
+
# ---- prepares (wallet from the token, or an explicit `from`) ------------
|
|
238
|
+
|
|
239
|
+
def prepare_buy(self, **kwargs):
|
|
240
|
+
return self.call_tool("polypad_prepare_buy", kwargs)
|
|
241
|
+
|
|
242
|
+
def prepare_sell(self, **kwargs):
|
|
243
|
+
return self.call_tool("polypad_prepare_sell", kwargs)
|
|
244
|
+
|
|
245
|
+
def prepare_nft_buy(self, **kwargs):
|
|
246
|
+
return self.call_tool("polypad_prepare_nft_buy", kwargs)
|
|
247
|
+
|
|
248
|
+
def prepare_fund_create(self, **kwargs):
|
|
249
|
+
return self.call_tool("polypad_prepare_fund_create", kwargs)
|
|
250
|
+
|
|
251
|
+
def prepare_fund_mint(self, **kwargs):
|
|
252
|
+
return self.call_tool("polypad_prepare_fund_mint", kwargs)
|
|
253
|
+
|
|
254
|
+
def prepare_fund_redeem(self, **kwargs):
|
|
255
|
+
return self.call_tool("polypad_prepare_fund_redeem", kwargs)
|
|
256
|
+
|
|
257
|
+
def prepare_token_launch(self, **kwargs):
|
|
258
|
+
return self.call_tool("polypad_prepare_token_launch", kwargs)
|
|
259
|
+
|
|
260
|
+
# ---- the loop: prepare → sign → confirm --------------------------------
|
|
261
|
+
|
|
262
|
+
def wait_for_confirmation(self, tx_hash, interval_s=3, timeout_s=120):
|
|
263
|
+
"""Poll get_tx_status until the transaction confirms or fails. Raises on timeout.
|
|
264
|
+
|
|
265
|
+
A hash the chain has not seen yet (``tx_not_found``) keeps polling until the
|
|
266
|
+
timeout, because a just-sent transaction can take a few seconds to appear.
|
|
267
|
+
"""
|
|
268
|
+
started = time.time()
|
|
269
|
+
while True:
|
|
270
|
+
try:
|
|
271
|
+
status = self.get_tx_status(tx_hash)
|
|
272
|
+
except PolypadError as exc:
|
|
273
|
+
if exc.code == "tx_not_found":
|
|
274
|
+
if time.time() - started > timeout_s:
|
|
275
|
+
raise PolypadError(
|
|
276
|
+
f"No confirmation after {int(timeout_s)}s for {tx_hash}. Check the explorer.",
|
|
277
|
+
"confirm_timeout",
|
|
278
|
+
) from exc
|
|
279
|
+
time.sleep(interval_s)
|
|
280
|
+
continue
|
|
281
|
+
raise
|
|
282
|
+
if status.get("status") in ("confirmed", "failed"):
|
|
283
|
+
return status
|
|
284
|
+
if time.time() - started > timeout_s:
|
|
285
|
+
raise PolypadError(
|
|
286
|
+
f"No confirmation after {int(timeout_s)}s for {tx_hash}. Check the explorer.",
|
|
287
|
+
"confirm_timeout",
|
|
288
|
+
)
|
|
289
|
+
time.sleep(interval_s)
|
|
290
|
+
|
|
291
|
+
def prepare_sign_confirm(self, tool, arguments, on_signing_link, get_tx_hash,
|
|
292
|
+
return_url=None, interval_s=3, timeout_s=120):
|
|
293
|
+
"""Prepare → sign → confirm, for a chat agent.
|
|
294
|
+
|
|
295
|
+
Prepares the action (wallet from the stored token), hands the signing link to
|
|
296
|
+
`on_signing_link` for the user to open, then waits for the transaction hash — supplied by
|
|
297
|
+
`get_tx_hash`, which resolves once the user has signed (for example from the returnUrl
|
|
298
|
+
callback, or the user pasting the hash back) — and polls until the chain confirms it.
|
|
299
|
+
"""
|
|
300
|
+
args = dict(arguments)
|
|
301
|
+
if return_url:
|
|
302
|
+
args["returnUrl"] = return_url
|
|
303
|
+
prepared = self.call_tool(tool, args)
|
|
304
|
+
on_signing_link(prepared["signing"]["url"], prepared["summary"])
|
|
305
|
+
tx_hash = get_tx_hash()
|
|
306
|
+
done = self.wait_for_confirmation(tx_hash, interval_s=interval_s, timeout_s=timeout_s)
|
|
307
|
+
return {"status": done["status"], "tx_hash": tx_hash, "result": done.get("result"),
|
|
308
|
+
"tx_status": done, "prepared": prepared}
|
|
309
|
+
|
|
310
|
+
def prepare_sign_broadcast(self, tool, arguments, private_key, rpc_url=None,
|
|
311
|
+
interval_s=3, timeout_s=120):
|
|
312
|
+
"""Prepare → sign → confirm, for a script with its own wallet (the Forge path).
|
|
313
|
+
|
|
314
|
+
Prepares the action, signs and sends each step with the script's own key, waits for each
|
|
315
|
+
step's receipt before the next, then polls get_tx_status for the final result. The signing
|
|
316
|
+
key must be the bound wallet — never the Polypad deployer wallet.
|
|
317
|
+
"""
|
|
318
|
+
from eth_account import Account
|
|
319
|
+
|
|
320
|
+
prepared = self.call_tool(tool, dict(arguments))
|
|
321
|
+
account = Account.from_key(private_key)
|
|
322
|
+
rpc = rpc_url or DEFAULT_RPC_URL
|
|
323
|
+
bound = self.wallet_address()
|
|
324
|
+
if bound and bound.lower() != account.address.lower():
|
|
325
|
+
raise PolypadError(
|
|
326
|
+
f"The signing key ({account.address}) is not the bound wallet ({bound}).",
|
|
327
|
+
"wallet_mismatch",
|
|
328
|
+
)
|
|
329
|
+
for step in prepared["transactions"]:
|
|
330
|
+
if step["from"].lower() != account.address.lower():
|
|
331
|
+
raise PolypadError(
|
|
332
|
+
f"Step {step['step']} was prepared for {step['from']}, not the signing wallet {account.address}.",
|
|
333
|
+
"wallet_mismatch",
|
|
334
|
+
)
|
|
335
|
+
hashes = []
|
|
336
|
+
nonce = self._rpc(rpc, "eth_getTransactionCount", [account.address, "pending"])
|
|
337
|
+
gas_price = self._rpc(rpc, "eth_gasPrice", [])
|
|
338
|
+
for i, step in enumerate(prepared["transactions"]):
|
|
339
|
+
tx = {
|
|
340
|
+
"chainId": CHAIN_ID,
|
|
341
|
+
"to": step["to"],
|
|
342
|
+
"data": step["data"],
|
|
343
|
+
"value": int(step["value"]),
|
|
344
|
+
"gas": int(step["gas"]) if step.get("gas") else 300000,
|
|
345
|
+
"gasPrice": gas_price,
|
|
346
|
+
"nonce": nonce,
|
|
347
|
+
}
|
|
348
|
+
signed = account.sign_transaction(tx)
|
|
349
|
+
tx_hash = self._rpc(rpc, "eth_sendRawTransaction", [signed.raw_transaction.hex()])
|
|
350
|
+
hashes.append(tx_hash)
|
|
351
|
+
nonce += 1
|
|
352
|
+
if i < len(prepared["transactions"]) - 1:
|
|
353
|
+
receipt = self._wait_receipt(rpc, tx_hash)
|
|
354
|
+
if int(receipt.get("status", "0x0"), 16) != 1:
|
|
355
|
+
raise PolypadError(f"Step {i + 1} failed on-chain. Nothing after it was sent.", "step_failed")
|
|
356
|
+
tx_hash = hashes[-1]
|
|
357
|
+
done = self.wait_for_confirmation(tx_hash, interval_s=interval_s, timeout_s=timeout_s)
|
|
358
|
+
return {"status": done["status"], "tx_hash": tx_hash, "result": done.get("result"),
|
|
359
|
+
"tx_status": done, "hashes": hashes, "prepared": prepared}
|
|
360
|
+
|
|
361
|
+
# ---- minimal JSON-RPC helpers (script signing path only) -----------------
|
|
362
|
+
|
|
363
|
+
def _rpc(self, rpc_url, method, params):
|
|
364
|
+
resp = self.session.post(
|
|
365
|
+
rpc_url, json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params}, timeout=30)
|
|
366
|
+
body = resp.json()
|
|
367
|
+
if body.get("error"):
|
|
368
|
+
raise PolypadError(f"RPC {method} failed: {body['error'].get('message')}", "rpc_error")
|
|
369
|
+
result = body["result"]
|
|
370
|
+
return int(result, 16) if isinstance(result, str) and result.startswith("0x") and method != "eth_sendRawTransaction" else result
|
|
371
|
+
|
|
372
|
+
def _wait_receipt(self, rpc_url, tx_hash, timeout_s=120):
|
|
373
|
+
started = time.time()
|
|
374
|
+
while True:
|
|
375
|
+
receipt = self._rpc(rpc_url, "eth_getTransactionReceipt", [tx_hash])
|
|
376
|
+
if receipt:
|
|
377
|
+
return receipt
|
|
378
|
+
if time.time() - started > timeout_s:
|
|
379
|
+
raise PolypadError(f"No receipt after {int(timeout_s)}s for {tx_hash}.", "confirm_timeout")
|
|
380
|
+
time.sleep(2)
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Shared constants for the Polypad agent API.
|
|
2
|
+
|
|
3
|
+
Every value here is copied from the live server code
|
|
4
|
+
(lib/agents-api/v2/config.ts, lib/x402/constants.ts) or the published
|
|
5
|
+
plan appendix — nothing is invented. If the server changes a number,
|
|
6
|
+
this file is the one place to update.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
MCP_ENDPOINT = "https://polypad.family/api/mcp"
|
|
10
|
+
SITE_ORIGIN = "https://polypad.family"
|
|
11
|
+
EXPLORER = "https://robinhoodchain.blockscout.com"
|
|
12
|
+
CHAIN_ID = 4663
|
|
13
|
+
CHAIN_NAME = "Robinhood Chain"
|
|
14
|
+
SERVER_VERSION = "2.0.0"
|
|
15
|
+
MCP_PROTOCOL_VERSION = "2025-06-18"
|
|
16
|
+
|
|
17
|
+
# Published rate limits (per client IP, per minute).
|
|
18
|
+
RATE_LIMITS = {
|
|
19
|
+
"read_per_minute": 120,
|
|
20
|
+
"prepare_per_minute": 30,
|
|
21
|
+
"per_wallet_prepare_per_minute": 12,
|
|
22
|
+
"intent_per_minute": 40,
|
|
23
|
+
"max_body_bytes": 16384,
|
|
24
|
+
"max_batch": 10,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
# Guardrails on prepared actions.
|
|
28
|
+
ACTION_LIMITS = {
|
|
29
|
+
"max_action_eth": 25, # One prepared action can move at most 25 ETH.
|
|
30
|
+
"confirm_large_above_eth": 1, # Above 1 ETH, the call needs confirmLarge=True.
|
|
31
|
+
"default_slippage_bps": 100,
|
|
32
|
+
"max_slippage_bps": 1000,
|
|
33
|
+
"signing_expires_in_seconds": 1200, # A prepared action stays valid to sign for 20 minutes.
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
# x402 pay-per-call: the three priced reads, in US dollars.
|
|
37
|
+
X402_PRODUCTS = [
|
|
38
|
+
{
|
|
39
|
+
"id": "token-report",
|
|
40
|
+
"name": "Token report",
|
|
41
|
+
"price_usd": 0.01,
|
|
42
|
+
"endpoint": "/api/x402/products/token-report",
|
|
43
|
+
"query_param": "address",
|
|
44
|
+
"delivers": "Price, market cap, volume, supply, bonding-curve progress, graduation state, creator, and launch details — read straight from Robinhood Chain.",
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
"id": "fund-nav",
|
|
48
|
+
"name": "Tokenized Fund NAV snapshot",
|
|
49
|
+
"price_usd": 0.01,
|
|
50
|
+
"endpoint": "/api/x402/products/fund-nav",
|
|
51
|
+
"query_param": "fund",
|
|
52
|
+
"delivers": "Net asset value per share and total NAV, shares sold, amount raised, strategy, and the manager — read straight from the chain.",
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
"id": "cto-report",
|
|
56
|
+
"name": "CTO report",
|
|
57
|
+
"price_usd": 0.05,
|
|
58
|
+
"endpoint": "/api/x402/products/cto-report",
|
|
59
|
+
"query_param": "launch",
|
|
60
|
+
"delivers": "Summary, risk, utility, momentum, holder distribution, narrative, sentiment, and conclusion — the same report the token page shows.",
|
|
61
|
+
},
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def x402_product(product_id):
|
|
66
|
+
for product in X402_PRODUCTS:
|
|
67
|
+
if product["id"] == product_id:
|
|
68
|
+
return product
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# x402 payment facts (chain 4663).
|
|
73
|
+
X402 = {
|
|
74
|
+
"version": 2,
|
|
75
|
+
"network": "eip155:4663",
|
|
76
|
+
"chain_id": 4663,
|
|
77
|
+
"max_timeout_seconds": 120, # How long a payment approval stays valid.
|
|
78
|
+
"pay_to": "0x9a21c75aC263cC43125E70200636f6397f8776d0", # Where paid-call revenue settles.
|
|
79
|
+
"usdg": {
|
|
80
|
+
"address": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",
|
|
81
|
+
"decimals": 6,
|
|
82
|
+
"symbol": "USDG",
|
|
83
|
+
"method": "eip3009",
|
|
84
|
+
"eip712": {"name": "Global Dollar", "version": "1"},
|
|
85
|
+
},
|
|
86
|
+
"polydash": {
|
|
87
|
+
"address": "0x319525528f42167eF7fC18b77b889958080568e4",
|
|
88
|
+
"decimals": 18,
|
|
89
|
+
"symbol": "POLYDASH",
|
|
90
|
+
"method": "permit2",
|
|
91
|
+
"eip712": {"name": "Polydash", "version": "1"},
|
|
92
|
+
},
|
|
93
|
+
"permit2": "0x000000000022D473030F116dDEE9F6B43aC78BA3",
|
|
94
|
+
"permit2_proxy": "0x402085c248EeA27D92E8b30b2C58ed07f9E20001",
|
|
95
|
+
"rpc_url": "https://rpc.mainnet.chain.robinhood.com",
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
# The SpendVault: where an agent's spending money lives.
|
|
99
|
+
SPEND_VAULT_ADDRESS = "0xDb5544a977b0dF881268746F2C47F049da579486"
|
|
100
|
+
|
|
101
|
+
VAULT_TOKENS = [
|
|
102
|
+
{"key": "USDG", "address": X402["usdg"]["address"], "decimals": 6},
|
|
103
|
+
{"key": "POLYDASH", "address": X402["polydash"]["address"], "decimals": 18},
|
|
104
|
+
]
|
|
105
|
+
|
|
106
|
+
# Plain-language error meanings, copied from the server's tool reference.
|
|
107
|
+
ERROR_MEANINGS = {
|
|
108
|
+
"amount_too_large": "One action is above the 25 ETH cap. Split it into smaller actions.",
|
|
109
|
+
"confirm_large_required": 'The amount is above 1 ETH. Confirm it with the user first, then resend with "confirmLarge": true.',
|
|
110
|
+
"invalid_json": "The request body was not valid JSON, or was not a JSON object.",
|
|
111
|
+
"invalid_params": "A field was missing, the wrong type, or out of range (bad address, bad number, bad hash). The error names the field.",
|
|
112
|
+
"key_material_rejected": "The request contained a private key or seed phrase. Never send one — Polypad never needs it. Nothing was processed.",
|
|
113
|
+
"not_found": "No token, tokenized fund, collection, listing, or endpoint matched.",
|
|
114
|
+
"tx_not_found": "No transaction with that hash on Robinhood Chain yet — it may not have been sent.",
|
|
115
|
+
"unknown_template": "No Strategy with that id. List the strategies first.",
|
|
116
|
+
"method_not_allowed": "Wrong HTTP method for the endpoint (GET vs POST).",
|
|
117
|
+
"ambiguous_collection": "More than one collection matches. Use the collection address.",
|
|
118
|
+
"ambiguous_fund": "More than one tokenized fund matches. Use the fund address.",
|
|
119
|
+
"ambiguous_token": "More than one token matches. Use the token address.",
|
|
120
|
+
"amount_exceeds_curve": "More tokens than the bonding curve can buy back right now. Try a smaller amount.",
|
|
121
|
+
"choose_template": "More than one Strategy fits the assets. Ask the user which one.",
|
|
122
|
+
"commit_window_open": "The collection is still in its commitment window. Commit from the collection page.",
|
|
123
|
+
"insufficient_balance": "The wallet holds less than the amount requested.",
|
|
124
|
+
"listing_not_valid": "The listing is sold, cancelled, expired, or no longer backed by the seller.",
|
|
125
|
+
"no_shares": "The wallet holds no shares of that tokenized fund.",
|
|
126
|
+
"not_holder": "The wallet does not hold the share(s) being redeemed.",
|
|
127
|
+
"not_tradable": "The token is in a phase that cannot be traded right now.",
|
|
128
|
+
"own_listing": "This wallet is the seller of that listing.",
|
|
129
|
+
"raise_closed": "The tokenized fund is not open for minting.",
|
|
130
|
+
"raise_open": "The tokenized fund is still raising. Exit opens after the raise closes; a refund opens only if the raise fails.",
|
|
131
|
+
"skin_required": "Only the fund manager can mint until the required manager shares are minted.",
|
|
132
|
+
"sold_out": "Sold out (NFT collection, or no shares left).",
|
|
133
|
+
"unsupported_fund": "Exits from this fund type are not prepared by the API yet. Open the fund page.",
|
|
134
|
+
"wallet_cap": "The collection’s per-wallet mint limit is reached.",
|
|
135
|
+
"payload_too_large": "Request body over 16 KB.",
|
|
136
|
+
"no_matching_template": "No Strategy can hold the requested assets.",
|
|
137
|
+
"quote_failed": "The pool could not quote that amount. Try a smaller amount.",
|
|
138
|
+
"simulation_reverted": "The on-chain simulation reverted — the transaction as built would fail. Nothing was sent.",
|
|
139
|
+
"rate_limited": "Too many requests from this IP. Wait a minute; the reply says how long (retry-after).",
|
|
140
|
+
"rate_limited_wallet": "Too many prepared actions for this wallet. Wait a minute.",
|
|
141
|
+
"internal_error": "Unexpected error. Nothing was signed or sent.",
|
|
142
|
+
"unsupported_collection_type": "Buys from bonding-curve collections are not prepared by the API yet. Open the collection page.",
|
|
143
|
+
"rpc_unavailable": "The chain data source could not be reached. Retry shortly.",
|
|
144
|
+
}
|