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/x402.py ADDED
@@ -0,0 +1,308 @@
1
+ """x402 pay-per-call: pay a few cents for a priced report (token report $0.01, Tokenized Fund NAV $0.01,
2
+ CTO report $0.05) with USDG (EIP-3009). The flow is the x402 v2 one: ask, get a 402 with the
3
+ price, sign the authorization, send it back in the X-PAYMENT header. The server only settles
4
+ after the report is built — if the report cannot be built, nothing is charged.
5
+
6
+ Everything the signature needs comes from the 402 answer itself (asset, pay-to, domain name and
7
+ version), so nothing about the payment is hardcoded here except the chain (4663) and the EIP-3009
8
+ type shape.
9
+ """
10
+
11
+ import base64
12
+ import json
13
+ import os
14
+ import secrets
15
+ import time
16
+
17
+ import requests
18
+ from eth_account import Account
19
+ from eth_account.messages import encode_typed_data
20
+
21
+ SITE_ORIGIN = "https://polypad.family"
22
+ CHAIN_ID = 4663
23
+
24
+ _EIP3009_TYPES = {
25
+ "TransferWithAuthorization": [
26
+ {"name": "from", "type": "address"},
27
+ {"name": "to", "type": "address"},
28
+ {"name": "value", "type": "uint256"},
29
+ {"name": "validAfter", "type": "uint256"},
30
+ {"name": "validBefore", "type": "uint256"},
31
+ {"name": "nonce", "type": "bytes32"},
32
+ ]
33
+ }
34
+
35
+
36
+ def pay_for_report(product, query, private_key, origin=SITE_ORIGIN, session=None):
37
+ """Fetch a priced report, paying with USDG from the given key.
38
+
39
+ `query` is the report's query string, for example "address=0x..." for a token report.
40
+ Returns the report JSON.
41
+ """
42
+ sess = session or requests.Session()
43
+ account = Account.from_key(private_key)
44
+ url = f"{origin}/api/x402/products/{product}?{query}"
45
+
46
+ ask = sess.get(url, timeout=30)
47
+ if ask.status_code == 200:
48
+ return ask.json()
49
+ if ask.status_code != 402:
50
+ raise RuntimeError(f"Report endpoint answered HTTP {ask.status_code}.")
51
+ accepts = ask.json().get("accepts") or []
52
+ requirement = next((r for r in accepts if (r.get("extra") or {}).get("assetTransferMethod") == "eip3009"), None)
53
+ if requirement is None:
54
+ raise RuntimeError("The report does not offer a USDG (EIP-3009) payment option.")
55
+
56
+ now = int(time.time())
57
+ nonce = "0x" + secrets.token_hex(32)
58
+ authorization = {
59
+ "from": account.address,
60
+ "to": requirement["payTo"],
61
+ "value": requirement["amount"],
62
+ "validAfter": "0",
63
+ "validBefore": str(now + requirement["maxTimeoutSeconds"]),
64
+ "nonce": nonce,
65
+ }
66
+ extra = requirement.get("extra") or {}
67
+ domain = {
68
+ "name": extra.get("name", "Global Dollar"),
69
+ "version": extra.get("version", "1"),
70
+ "chainId": CHAIN_ID,
71
+ "verifyingContract": requirement["asset"],
72
+ }
73
+ message = encode_typed_data(domain, _EIP3009_TYPES, authorization)
74
+ signature = account.sign_message(message).signature.hex()
75
+ if not signature.startswith("0x"):
76
+ signature = "0x" + signature
77
+ payment = base64.b64encode(json.dumps(
78
+ {"x402Version": 2, "accepted": requirement,
79
+ "payload": {"signature": signature, "authorization": authorization}}
80
+ ).encode()).decode()
81
+ paid = sess.get(url, headers={"X-PAYMENT": payment}, timeout=30)
82
+ if paid.status_code != 200:
83
+ raise RuntimeError(f"Paid report request answered HTTP {paid.status_code}.")
84
+ return paid.json()
85
+
86
+
87
+ # ---- Building blocks: sign a payment yourself (USDG or POLYDASH) -----------
88
+
89
+ from .constants import X402, x402_product
90
+ from .errors import PolypadError
91
+
92
+ # Function selector for Permit2 nonceBitmap(address,uint256), verified against eth-utils keccak.
93
+ _NONCE_BITMAP_SELECTOR = "0x4fe02b44"
94
+
95
+
96
+ def _encode_address_word(address):
97
+ return bytes.fromhex(address[2:].lower()).rjust(32, b"\x00")
98
+
99
+
100
+ def _rpc_call(rpc_url, method, params, session=None):
101
+ session = session or requests.Session()
102
+ response = session.post(rpc_url, json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params}, timeout=30)
103
+ response.raise_for_status()
104
+ body = response.json()
105
+ if body.get("error"):
106
+ raise PolypadError(f"Robinhood Chain RPC error: {body['error'].get('message', body['error'])}", "rpc_unavailable")
107
+ return body.get("result")
108
+
109
+
110
+ def next_permit2_nonce(owner, rpc_url=None, session=None):
111
+ """The next unused Permit2 nonce for a wallet.
112
+
113
+ Permit2 tracks used nonces in 256-bit words; the first unset bit in
114
+ the lowest word is the next free nonce. A payment signed with an
115
+ already-used nonce is rejected, so never reuse a nonce.
116
+ """
117
+ rpc_url = rpc_url or X402["rpc_url"]
118
+ for word in range(4):
119
+ data = _NONCE_BITMAP_SELECTOR + _encode_address_word(owner).hex() + word.to_bytes(32, "big").hex()
120
+ result = _rpc_call(rpc_url, "eth_call", [{"to": X402["permit2"], "data": "0x" + data}, "latest"], session=session)
121
+ bitmap = int(result, 16) if result else 0
122
+ for bit in range(256):
123
+ if not (bitmap >> bit) & 1:
124
+ return word * 256 + bit
125
+ raise PolypadError("No free Permit2 nonce found in the first 1,024 nonces for this wallet.", "invalid_params")
126
+
127
+
128
+ def _sign_typed_data(account, full_message):
129
+ try:
130
+ from eth_account.messages import encode_typed_data
131
+ except ImportError as exc:
132
+ raise PolypadError(
133
+ 'Signing needs eth-account: pip install "polypad-agent[signing]".',
134
+ "invalid_params",
135
+ ) from exc
136
+ encoded = encode_typed_data(full_message=full_message)
137
+ return account.sign_message(encoded).signature
138
+
139
+
140
+ def sign_x402_payment(accepted, account, nonce=None, rpc_url=None, timeout_seconds=None):
141
+ """Sign a payment for one ``accepts`` entry from a 402 reply.
142
+
143
+ Returns the full x402 v2 payload — pass it to ``encode_payment_header``
144
+ and send it as the ``X-PAYMENT`` header. The payment is checked before
145
+ signing: a wrong recipient, wrong network, wrong token, or zero amount
146
+ is refused.
147
+ """
148
+ if accepted.get("scheme") != "exact" or accepted.get("network") != X402["network"]:
149
+ raise PolypadError(
150
+ f"Unsupported payment requirement: {accepted.get('scheme')} on {accepted.get('network')}. "
151
+ "This SDK pays x402 v2 exact payments on eip155:4663 only.",
152
+ "invalid_params",
153
+ )
154
+ if accepted.get("payTo", "").lower() != X402["pay_to"].lower():
155
+ raise PolypadError(f"Refused: this payment goes to {accepted.get('payTo')}, not the Polypad fee wallet.", "invalid_params")
156
+ amount = int(accepted["amount"])
157
+ if amount <= 0:
158
+ raise PolypadError("Refused: the payment amount is zero.", "invalid_params")
159
+ now = int(time.time())
160
+ timeout = timeout_seconds if timeout_seconds is not None else accepted.get("maxTimeoutSeconds") or X402["max_timeout_seconds"]
161
+ valid_after = now
162
+ valid_before = now + timeout
163
+
164
+ method = (accepted.get("extra") or {}).get("assetTransferMethod")
165
+ if method == "eip3009":
166
+ if accepted["asset"].lower() != X402["usdg"]["address"].lower():
167
+ raise PolypadError(f"Refused: EIP-3009 payment for an unexpected token {accepted['asset']}.", "invalid_params")
168
+ # EIP-3009 nonces are random 32-byte values, one use each.
169
+ nonce_bytes = secrets.token_bytes(32)
170
+ signature = _sign_typed_data(
171
+ account,
172
+ {
173
+ "domain": {
174
+ "name": X402["usdg"]["eip712"]["name"],
175
+ "version": X402["usdg"]["eip712"]["version"],
176
+ "chainId": X402["chain_id"],
177
+ "verifyingContract": X402["usdg"]["address"],
178
+ },
179
+ "types": {
180
+ "TransferWithAuthorization": [
181
+ {"name": "from", "type": "address"},
182
+ {"name": "to", "type": "address"},
183
+ {"name": "value", "type": "uint256"},
184
+ {"name": "validAfter", "type": "uint256"},
185
+ {"name": "validBefore", "type": "uint256"},
186
+ {"name": "nonce", "type": "bytes32"},
187
+ ]
188
+ },
189
+ "primaryType": "TransferWithAuthorization",
190
+ "message": {
191
+ "from": account.address,
192
+ "to": accepted["payTo"],
193
+ "value": amount,
194
+ "validAfter": valid_after,
195
+ "validBefore": valid_before,
196
+ "nonce": nonce_bytes,
197
+ },
198
+ },
199
+ )
200
+ return {
201
+ "x402Version": 2,
202
+ "accepted": accepted,
203
+ "payload": {
204
+ "signature": "0x" + signature.hex(),
205
+ "authorization": {
206
+ "from": account.address,
207
+ "to": accepted["payTo"],
208
+ "value": str(amount),
209
+ "validAfter": str(valid_after),
210
+ "validBefore": str(valid_before),
211
+ "nonce": "0x" + nonce_bytes.hex(),
212
+ },
213
+ },
214
+ }
215
+
216
+ if method == "permit2":
217
+ if accepted["asset"].lower() != X402["polydash"]["address"].lower():
218
+ raise PolypadError(f"Refused: Permit2 payment for an unexpected token {accepted['asset']}.", "invalid_params")
219
+ if nonce is None:
220
+ nonce = next_permit2_nonce(account.address, rpc_url)
221
+ signature = _sign_typed_data(
222
+ account,
223
+ {
224
+ "domain": {"name": "Permit2", "chainId": X402["chain_id"], "verifyingContract": X402["permit2"]},
225
+ "types": {
226
+ "PermitWitnessTransferFrom": [
227
+ {"name": "permitted", "type": "TokenPermissions"},
228
+ {"name": "spender", "type": "address"},
229
+ {"name": "nonce", "type": "uint256"},
230
+ {"name": "deadline", "type": "uint256"},
231
+ {"name": "witness", "type": "Witness"},
232
+ ],
233
+ "TokenPermissions": [
234
+ {"name": "token", "type": "address"},
235
+ {"name": "amount", "type": "uint256"},
236
+ ],
237
+ "Witness": [
238
+ {"name": "to", "type": "address"},
239
+ {"name": "validAfter", "type": "uint256"},
240
+ ],
241
+ },
242
+ "primaryType": "PermitWitnessTransferFrom",
243
+ "message": {
244
+ "permitted": {"token": accepted["asset"], "amount": amount},
245
+ "spender": X402["permit2_proxy"],
246
+ "nonce": nonce,
247
+ "deadline": valid_before,
248
+ "witness": {"to": accepted["payTo"], "validAfter": valid_after},
249
+ },
250
+ },
251
+ )
252
+ return {
253
+ "x402Version": 2,
254
+ "accepted": accepted,
255
+ "payload": {
256
+ "signature": "0x" + signature.hex(),
257
+ "permit2Authorization": {
258
+ "permitted": {"token": accepted["asset"], "amount": str(amount)},
259
+ "from": account.address,
260
+ "spender": X402["permit2_proxy"],
261
+ "nonce": str(nonce),
262
+ "deadline": str(valid_before),
263
+ "witness": {"to": accepted["payTo"], "validAfter": str(valid_after)},
264
+ },
265
+ },
266
+ }
267
+
268
+ raise PolypadError(f"Unsupported payment method: {method}.", "invalid_params")
269
+
270
+
271
+ def encode_payment_header(payment):
272
+ """The ``X-PAYMENT`` header value for a signed payment: base64 JSON."""
273
+ return base64.b64encode(json.dumps(payment).encode("utf-8")).decode("ascii")
274
+
275
+
276
+ def fetch_with_x402(url, account, asset="USDG", session=None, timeout=30, nonce=None, rpc_url=None):
277
+ """GET a priced Polypad read with x402 payment handled for you.
278
+
279
+ Requests, gets a 402 with the price, signs the payment, retries with
280
+ the ``X-PAYMENT`` header. Returns ``{"response", "payment", "accepted"}``.
281
+ ``url`` is the full product URL — use ``product_url()`` to build it.
282
+ """
283
+ session = session or requests.Session()
284
+ first = session.get(url, timeout=timeout)
285
+ if first.status_code != 402:
286
+ return {"response": first, "payment": None, "accepted": None}
287
+ try:
288
+ body = first.json()
289
+ except ValueError as exc:
290
+ raise PolypadError("The priced read answered 402 with something that was not JSON.", "invalid_response") from exc
291
+ accepts = body.get("accepts") or []
292
+ if not accepts:
293
+ raise PolypadError("The priced read answered 402 but named no payment option.", "invalid_response")
294
+ wanted_address = X402["usdg"]["address"] if asset == "USDG" else X402["polydash"]["address"]
295
+ accepted = next((a for a in accepts if a.get("asset", "").lower() == wanted_address.lower()), accepts[0])
296
+ payment = sign_x402_payment(accepted, account, nonce=nonce, rpc_url=rpc_url)
297
+ second = session.get(url, headers={"x-payment": encode_payment_header(payment)}, timeout=timeout)
298
+ return {"response": second, "payment": payment, "accepted": accepted}
299
+
300
+
301
+ def product_url(product_id, address):
302
+ """Build the URL for a priced read: product id plus the one address it needs."""
303
+ product = x402_product(product_id)
304
+ if product is None:
305
+ raise PolypadError(f"Unknown x402 product: {product_id}.", "invalid_params")
306
+ from urllib.parse import quote
307
+
308
+ return f"https://polypad.family{product['endpoint']}?{product['query_param']}={quote(address, safe='')}"
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: polypad-agent
3
+ Version: 2.0.0
4
+ Summary: Thin typed client for the Polypad agent API (MCP) on Robinhood Chain: prepare → sign → confirm, persistent wallet binding, and x402 pay-per-call.
5
+ License: MIT
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: requests>=2.0
9
+ Requires-Dist: eth-account>=0.13
10
+ Provides-Extra: dev
11
+ Requires-Dist: pytest>=7.0; extra == "dev"
12
+
13
+ # polypad-agent (Python)
14
+
15
+ Thin typed client for the Polypad agent API (MCP) on Robinhood Chain. Version 2.0.0, matching the
16
+ server. Not yet published to PyPI — install from the repo for now: `pip install -e py/`.
17
+
18
+ ## Install (once published)
19
+
20
+ ```bash
21
+ pip install polypad-agent
22
+ ```
23
+
24
+ ## Connect once
25
+
26
+ ```python
27
+ from polypad_agent import PolypadClient
28
+
29
+ client = PolypadClient()
30
+ # Show the user this URL: they connect their wallet, sign one message, and get a token.
31
+ print(client.connect_url(return_url="https://example.com/agent/done"))
32
+ # Store the token as POLYPAD_WALLET_TOKEN. The client reads it automatically.
33
+ ```
34
+
35
+ ## Quickstart
36
+
37
+ ```python
38
+ from polypad_agent import PolypadClient
39
+
40
+ client = PolypadClient() # reads POLYPAD_WALLET_TOKEN
41
+ print(client.list_tokens(sort="new", limit=5))
42
+ print(client.quote_trade(token="POLYDASH", side="buy", amountEth="0.01"))
43
+ mint = client.prepare_fund_mint(fund="0x7c1d31629ac68aebe83f230edbc7eacfc26285ef", quantity=1)
44
+ print(mint["signing"]["url"]) # the user opens this and signs
45
+ ```
46
+
47
+ ## The loop
48
+
49
+ ```python
50
+ # Chat agent: prepare, show the link, wait for the hash, poll until confirmed.
51
+ done = client.prepare_sign_confirm(
52
+ "polypad_prepare_fund_mint",
53
+ {"fund": "0x7c1d31629ac68aebe83f230edbc7eacfc26285ef", "quantity": 1},
54
+ on_signing_link=lambda url, summary: print(summary["headline"], url),
55
+ get_tx_hash=read_hash_from_return_callback,
56
+ return_url="https://example.com/agent/done",
57
+ )
58
+ print(done["status"], done["tx_hash"], done["result"])
59
+
60
+ # Script with its own wallet (the Forge path): prepare, sign, broadcast, confirm.
61
+ launched = client.prepare_sign_broadcast(
62
+ "polypad_prepare_token_launch",
63
+ {"name": "Agent Swarm", "symbol": "SWARM", "creatorFeeBps": 100, "devBuyEth": "0"},
64
+ private_key=os.environ["LAUNCHER_PRIVATE_KEY"],
65
+ )
66
+ print(launched["status"], launched["tx_hash"])
67
+ ```
68
+
69
+ ## Pay-per-call
70
+
71
+ ```python
72
+ from polypad_agent import pay_for_report
73
+
74
+ report = pay_for_report(
75
+ "token-report",
76
+ "address=0x3Da9244DDE38284017fD15e45d1Fdf66D3617B4B",
77
+ private_key=os.environ["PAYER_PRIVATE_KEY"],
78
+ )
79
+ ```
80
+
81
+ ## Recipes
82
+
83
+ - `examples/launch_token.py` — launch a token from a script, then create its staking pool.
84
+ - `examples/run_fund.py` — create a tokenized fund, then mint the manager's skin shares.
85
+ - `examples/smoke.py` — read-only live smoke test (initialize, tools/list, stats).
86
+
87
+ ## More in the package
88
+
89
+ - `confirm` / `sign_and_send` / `sign_send_and_confirm` — the standalone sign-loop helpers
90
+ (`confirm` polls `polypad_get_tx_status` until the transaction confirms or fails).
91
+ - `sign_x402_payment` / `fetch_with_x402` / `product_url` / `next_permit2_nonce` — x402
92
+ building blocks for USDG (EIP-3009) and POLYDASH (Permit2) payments.
93
+ - `build_create_key_tx` / `build_deposit_tx` / `build_withdraw_tx` / `build_revoke_key_tx` /
94
+ `get_key_status` / `get_vault_balance` — SpendVault spending keys.
95
+ - `TOOL_NAMES` / `PREPARE_TOOLS` / `is_prepare_tool`, `RATE_LIMITS`, `ACTION_LIMITS`,
96
+ `ERROR_MEANINGS` — the 21 tools, the published limits, and the server's error meanings.
97
+
98
+ ## Tests
99
+
100
+ ```bash
101
+ PYTHONPATH=src python -m unittest discover -s tests -v # 44 tests (mocked transport, no network)
102
+ ```
103
+
104
+ Per-call `from` still works: pass it explicitly and the client leaves the token out for that call.
105
+ Contracts are unaudited.
@@ -0,0 +1,13 @@
1
+ polypad_agent/__init__.py,sha256=aSUk7JiRQ3sgp5dm2O20uJkJibCXNoVCqofQ__q7rc4,2032
2
+ polypad_agent/binding.py,sha256=ymTdw88AGMpabEuzRumaw10p6WO3U5kmXn04v-64WGs,2023
3
+ polypad_agent/client.py,sha256=so2guohwMldfzYBXYDvzUg1AoLTg_uVb5SmYJeme4rM,16475
4
+ polypad_agent/constants.py,sha256=PsLpDTbhsvVqc8jxTIWcsKQoZHuT6-yiBPDtwdPWoeU,7121
5
+ polypad_agent/errors.py,sha256=Q1wsGAciES1YkFtq5Xt5HQEPCh6q4Clb5akK8UagKzI,3086
6
+ polypad_agent/prepare.py,sha256=_bLZyN2pyasQGgEPczNwOWt59wcBxcW2kaj_0RlHR2A,8286
7
+ polypad_agent/spend_vault.py,sha256=Br6BKFTRa-jz7UnYFPmotfIzM5L0okV0DXFCD2XqJyI,9359
8
+ polypad_agent/tools.py,sha256=3ONl8g6Nvf4Cxq46WoKgbrBiuvq1CY4mvZaTUk9_YSk,2923
9
+ polypad_agent/x402.py,sha256=aRwkA--_QJ6XbNKD1N1Qxkoqfz6WTDX16U6mR6tIWZY,13391
10
+ polypad_agent-2.0.0.dist-info/METADATA,sha256=0elWrR3eG6KlWEjdTL2Ha5kL1XXR4MEsRk81D6BwvAE,3734
11
+ polypad_agent-2.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ polypad_agent-2.0.0.dist-info/top_level.txt,sha256=0WqmSTSHexaircWWcJRqw4tAmyLJ5pcU7lY6DcF_K1I,14
13
+ polypad_agent-2.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ polypad_agent