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
polypad_agent/errors.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Errors. The server answers with ``{"ok": false, "error": {"code", "message", ...}}``
|
|
2
|
+
(and the same shape inside a tools/call reply marked ``isError: true``).
|
|
3
|
+
This module turns those replies — plus plain JSON-RPC and HTTP failures —
|
|
4
|
+
into one typed error with the server's own plain-language meaning attached.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .constants import ERROR_MEANINGS
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PolypadError(Exception):
|
|
11
|
+
"""One error for every Polypad failure, with the server's own code.
|
|
12
|
+
|
|
13
|
+
Args:
|
|
14
|
+
message: Plain-language message, usually the server's own.
|
|
15
|
+
code: Machine-readable code from the server (for example ``rate_limited``).
|
|
16
|
+
status: HTTP status when the server sent one.
|
|
17
|
+
extra: Extra fields the server sent (for example ``retryAfter``, ``field``).
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(self, message, code="error", status=None, extra=None):
|
|
21
|
+
super().__init__(message)
|
|
22
|
+
self.message = message
|
|
23
|
+
self.code = code
|
|
24
|
+
#: HTTP status when the server sent one.
|
|
25
|
+
self.status = status
|
|
26
|
+
#: Extra fields the server sent (for example ``retryAfter``, ``field``).
|
|
27
|
+
self.extra = extra or {}
|
|
28
|
+
#: The server's plain-language meaning for this code, when one is published.
|
|
29
|
+
self.meaning = ERROR_MEANINGS.get(code)
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def retry_after_seconds(self):
|
|
33
|
+
"""Seconds to wait before retrying, when the server said so (429s)."""
|
|
34
|
+
value = self.extra.get("retryAfter")
|
|
35
|
+
return value if isinstance(value, (int, float)) else None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class PolypadTxFailedError(PolypadError):
|
|
39
|
+
"""Raised by ``confirm()`` when a transaction is mined but fails on-chain."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, tx_hash, result):
|
|
42
|
+
super().__init__(
|
|
43
|
+
f"Transaction {tx_hash} was mined but failed on-chain. {result}",
|
|
44
|
+
"tx_failed",
|
|
45
|
+
extra={"tx_hash": tx_hash},
|
|
46
|
+
)
|
|
47
|
+
self.tx_hash = tx_hash
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class PolypadConfirmTimeoutError(PolypadError):
|
|
51
|
+
"""Raised by ``confirm()`` when no final answer arrives before the timeout."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, tx_hash, timeout_ms, explorer_url):
|
|
54
|
+
super().__init__(
|
|
55
|
+
f"No confirmed or failed result for {tx_hash} within {round(timeout_ms / 1000)} seconds. "
|
|
56
|
+
f"The transaction may still confirm — check {explorer_url} before sending it again, "
|
|
57
|
+
"or you may pay twice.",
|
|
58
|
+
"confirm_timeout",
|
|
59
|
+
extra={"tx_hash": tx_hash, "timeout_ms": timeout_ms},
|
|
60
|
+
)
|
|
61
|
+
self.tx_hash = tx_hash
|
|
62
|
+
self.explorer_url = explorer_url
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def is_api_error_body(value):
|
|
66
|
+
"""True when ``value`` is the server's ``{ok: False, error: {...}}`` shape."""
|
|
67
|
+
return (
|
|
68
|
+
isinstance(value, dict)
|
|
69
|
+
and value.get("ok") is False
|
|
70
|
+
and isinstance(value.get("error"), dict)
|
|
71
|
+
and isinstance(value["error"].get("code"), str)
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def error_from_body(body, status=None):
|
|
76
|
+
"""Build a PolypadError from a server error body."""
|
|
77
|
+
error = dict(body["error"])
|
|
78
|
+
code = error.pop("code")
|
|
79
|
+
message = error.pop("message")
|
|
80
|
+
return PolypadError(message, code, status=status, extra=error)
|
polypad_agent/prepare.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""The sign loop: prepare → sign → confirm.
|
|
2
|
+
|
|
3
|
+
Polypad is non-custodial, so signing always happens outside the API:
|
|
4
|
+
|
|
5
|
+
1. **Prepare** — a ``prepare_*`` tool returns unsigned transactions plus a
|
|
6
|
+
one-tap ``/sign`` link. Show the summary first, then the link.
|
|
7
|
+
2. **Sign** — either a person opens the link and signs in their own
|
|
8
|
+
wallet on polypad.family/sign, or a script signs the steps itself
|
|
9
|
+
with its own wallet (the Forge path — see ``sign_and_send``).
|
|
10
|
+
3. **Confirm** — ``confirm()`` polls ``polypad_get_tx_status`` until the
|
|
11
|
+
transaction confirms or fails.
|
|
12
|
+
|
|
13
|
+
Wallet model: the agent connects once on /sign?connect=1 and gets a
|
|
14
|
+
token; prepare calls pass ``walletToken`` instead of a per-call ``from``
|
|
15
|
+
(see binding.py). The per-call ``from`` address is the underlying
|
|
16
|
+
transport and fallback: every prepare call still names the wallet that
|
|
17
|
+
will sign, and the /sign page rebuilds the action for whichever wallet
|
|
18
|
+
connects there.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import re
|
|
22
|
+
import time
|
|
23
|
+
|
|
24
|
+
from .constants import EXPLORER, X402
|
|
25
|
+
from .errors import PolypadConfirmTimeoutError, PolypadError, PolypadTxFailedError
|
|
26
|
+
|
|
27
|
+
_ADDRESS_RE = re.compile(r"^0x[0-9a-fA-F]{40}$")
|
|
28
|
+
_HEX_RE = re.compile(r"^0x[0-9a-fA-F]*$")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def confirm(client, tx_hash, timeout_ms=120_000, interval_ms=3_000):
|
|
32
|
+
"""Poll ``polypad_get_tx_status`` until the transaction confirms or fails.
|
|
33
|
+
|
|
34
|
+
- ``pending`` → keep polling.
|
|
35
|
+
- ``tx_not_found`` (404) → the chain has not seen the hash yet; keep
|
|
36
|
+
polling until the timeout, because a just-sent transaction can take a
|
|
37
|
+
few seconds to appear.
|
|
38
|
+
- ``confirmed`` → returns the status, with its plain-language ``result``.
|
|
39
|
+
- ``failed`` → raises PolypadTxFailedError.
|
|
40
|
+
- Nothing final before ``timeout_ms`` → raises PolypadConfirmTimeoutError.
|
|
41
|
+
A timeout does NOT mean the transaction failed — check the explorer
|
|
42
|
+
link in the error before sending anything again.
|
|
43
|
+
"""
|
|
44
|
+
timeout_s = timeout_ms / 1000.0
|
|
45
|
+
interval_s = interval_ms / 1000.0
|
|
46
|
+
started = time.monotonic()
|
|
47
|
+
explorer_url = f"{EXPLORER}/tx/{tx_hash}"
|
|
48
|
+
while True:
|
|
49
|
+
try:
|
|
50
|
+
status = client.get_tx_status(tx_hash)
|
|
51
|
+
except PolypadError as exc:
|
|
52
|
+
if exc.code == "tx_not_found":
|
|
53
|
+
if time.monotonic() - started > timeout_s:
|
|
54
|
+
raise PolypadConfirmTimeoutError(tx_hash, timeout_ms, explorer_url) from exc
|
|
55
|
+
time.sleep(interval_s)
|
|
56
|
+
continue
|
|
57
|
+
raise
|
|
58
|
+
if status.get("status") == "confirmed":
|
|
59
|
+
return status
|
|
60
|
+
if status.get("status") == "failed":
|
|
61
|
+
raise PolypadTxFailedError(
|
|
62
|
+
tx_hash, status.get("result") or "The transaction was mined but failed. No state changed except gas spent."
|
|
63
|
+
)
|
|
64
|
+
if time.monotonic() - started > timeout_s:
|
|
65
|
+
raise PolypadConfirmTimeoutError(tx_hash, timeout_ms, explorer_url)
|
|
66
|
+
time.sleep(interval_s)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _rpc(session, rpc_url, method, params):
|
|
70
|
+
import requests
|
|
71
|
+
|
|
72
|
+
response = session.post(rpc_url, json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params}, timeout=30)
|
|
73
|
+
response.raise_for_status()
|
|
74
|
+
body = response.json()
|
|
75
|
+
if body.get("error"):
|
|
76
|
+
raise PolypadError(f"Robinhood Chain RPC error: {body['error'].get('message', body['error'])}", "rpc_unavailable")
|
|
77
|
+
return body.get("result")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _wait_receipt(session, rpc_url, tx_hash, timeout_ms=120_000):
|
|
81
|
+
started = time.monotonic()
|
|
82
|
+
while time.monotonic() - started < timeout_ms / 1000.0:
|
|
83
|
+
receipt = _rpc(session, rpc_url, "eth_getTransactionReceipt", [tx_hash])
|
|
84
|
+
if receipt is not None:
|
|
85
|
+
return receipt
|
|
86
|
+
time.sleep(2)
|
|
87
|
+
raise PolypadConfirmTimeoutError(tx_hash, timeout_ms, f"{EXPLORER}/tx/{tx_hash}")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def sign_and_send(prepared, account, rpc_url=None, wait_between_steps=True, step_timeout_ms=120_000, session=None):
|
|
91
|
+
"""Sign every step of a prepared action with your own wallet and send them, in order — the path Forge uses to launch a token from a script.
|
|
92
|
+
|
|
93
|
+
``account`` is an eth-account account (for example from
|
|
94
|
+
``eth_account.Account.from_key(...)`` — needs the ``signing`` extra:
|
|
95
|
+
``pip install "polypad-agent[signing]"``). The key stays in your
|
|
96
|
+
process; it is never sent to Polypad. Each step is checked before it
|
|
97
|
+
is sent: it must be for Robinhood Chain (4663), its ``from`` must
|
|
98
|
+
match your wallet, and its ``to`` must be an address the API returned
|
|
99
|
+
for this action. Steps are sent one at a time, and each step's receipt
|
|
100
|
+
is awaited before the next step is sent (unless ``wait_between_steps``
|
|
101
|
+
is False) — the same order the /sign page uses.
|
|
102
|
+
|
|
103
|
+
Returns the transaction hash of every step sent. If a step fails, the
|
|
104
|
+
error is raised and no later step is sent.
|
|
105
|
+
"""
|
|
106
|
+
import requests
|
|
107
|
+
|
|
108
|
+
rpc_url = rpc_url or X402["rpc_url"]
|
|
109
|
+
session = session or requests.Session()
|
|
110
|
+
steps = prepared.get("transactions") or []
|
|
111
|
+
|
|
112
|
+
allowed_targets = {step["to"].lower() for step in steps}
|
|
113
|
+
|
|
114
|
+
def collect(value):
|
|
115
|
+
if isinstance(value, str) and _ADDRESS_RE.match(value):
|
|
116
|
+
allowed_targets.add(value.lower())
|
|
117
|
+
elif isinstance(value, list):
|
|
118
|
+
for item in value:
|
|
119
|
+
collect(item)
|
|
120
|
+
elif isinstance(value, dict):
|
|
121
|
+
for item in value.values():
|
|
122
|
+
collect(item)
|
|
123
|
+
|
|
124
|
+
rest = {k: v for k, v in prepared.items() if k not in ("transactions", "signing")}
|
|
125
|
+
collect(rest)
|
|
126
|
+
|
|
127
|
+
sent = []
|
|
128
|
+
for step in steps:
|
|
129
|
+
if step.get("chainId") != 4663:
|
|
130
|
+
raise PolypadError(f"Refused: step {step['step']} is not for Robinhood Chain (chain id 4663).", "invalid_params")
|
|
131
|
+
if step.get("from", "").lower() != account.address.lower():
|
|
132
|
+
raise PolypadError(f"Refused: step {step['step']} was built for a different wallet ({step.get('from')}).", "invalid_params")
|
|
133
|
+
if step.get("to", "").lower() not in allowed_targets:
|
|
134
|
+
raise PolypadError(f"Refused: step {step['step']} sends to an address the API did not return for this action.", "invalid_params")
|
|
135
|
+
if not _HEX_RE.match(step.get("data", "")) or not re.match(r"^\d{1,40}$", str(step.get("value", ""))):
|
|
136
|
+
raise PolypadError(f"Refused: step {step['step']} is malformed.", "invalid_params")
|
|
137
|
+
|
|
138
|
+
nonce = int(_rpc(session, rpc_url, "eth_getTransactionCount", [account.address, "pending"]), 16)
|
|
139
|
+
gas_price = int(_rpc(session, rpc_url, "eth_gasPrice", []), 16)
|
|
140
|
+
gas = int(step["gas"]) if step.get("gas") else int(
|
|
141
|
+
_rpc(
|
|
142
|
+
session,
|
|
143
|
+
rpc_url,
|
|
144
|
+
"eth_estimateGas",
|
|
145
|
+
[{"from": account.address, "to": step["to"], "data": step["data"], "value": hex(int(step["value"]))}],
|
|
146
|
+
),
|
|
147
|
+
16,
|
|
148
|
+
)
|
|
149
|
+
tx = {
|
|
150
|
+
"chainId": 4663,
|
|
151
|
+
"to": step["to"],
|
|
152
|
+
"data": step["data"],
|
|
153
|
+
"value": int(step["value"]),
|
|
154
|
+
"gas": gas,
|
|
155
|
+
"gasPrice": gas_price,
|
|
156
|
+
"nonce": nonce,
|
|
157
|
+
}
|
|
158
|
+
signed = account.sign_transaction(tx)
|
|
159
|
+
tx_hash = _rpc(session, rpc_url, "eth_sendRawTransaction", [signed.raw_transaction.hex()])
|
|
160
|
+
sent.append({"step": step["step"], "hash": tx_hash})
|
|
161
|
+
is_last = step["step"] == len(steps)
|
|
162
|
+
if wait_between_steps and not is_last:
|
|
163
|
+
receipt = _wait_receipt(session, rpc_url, tx_hash, timeout_ms=step_timeout_ms)
|
|
164
|
+
if receipt.get("status") != "0x1":
|
|
165
|
+
raise PolypadTxFailedError(tx_hash, f"Step {step['step']} failed on-chain. Nothing after it was sent.")
|
|
166
|
+
return sent
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def sign_send_and_confirm(client, prepared, account, rpc_url=None, timeout_ms=120_000, interval_ms=3_000, **kwargs):
|
|
170
|
+
"""The whole scripted loop in one call: sign and send every step, then wait for the last step to confirm.
|
|
171
|
+
|
|
172
|
+
Returns ``{"sent": [...], "status": {...}}``. For the human flow (a
|
|
173
|
+
person signs on the /sign page), use ``confirm()`` with the hash they
|
|
174
|
+
paste back instead.
|
|
175
|
+
"""
|
|
176
|
+
sent = sign_and_send(prepared, account, rpc_url=rpc_url, **kwargs)
|
|
177
|
+
if not sent:
|
|
178
|
+
raise PolypadError("The prepared action has no transactions.", "invalid_params")
|
|
179
|
+
status = confirm(client, sent[-1]["hash"], timeout_ms=timeout_ms, interval_ms=interval_ms)
|
|
180
|
+
return {"sent": sent, "status": status}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""SpendVault spending keys.
|
|
2
|
+
|
|
3
|
+
How it works (this is how /agents/accounts issues keys — nothing here
|
|
4
|
+
invents a format):
|
|
5
|
+
|
|
6
|
+
- A "spending key" is a wallet *address*, not a secret string. The owner
|
|
7
|
+
deposits USDG or POLYDASH into the SpendVault, then calls ``createKey``
|
|
8
|
+
with the agent's wallet address, the token, a per-payment cap, a daily
|
|
9
|
+
cap, an allowlist of addresses the agent may pay, and an expiry.
|
|
10
|
+
- The agent then spends from the vault with that wallet, inside the caps.
|
|
11
|
+
The owner can take the money back any time (``withdraw``) and can revoke
|
|
12
|
+
the key any time (``revokeKey``).
|
|
13
|
+
- The key is created by the *owner* in their own wallet (on
|
|
14
|
+
polypad.family/agents/accounts, or with ``build_create_key_tx`` below).
|
|
15
|
+
The agent never holds a secret for the vault — its wallet address is
|
|
16
|
+
the key, and the vault enforces the caps on-chain.
|
|
17
|
+
|
|
18
|
+
The SDK does not send these transactions for you: each builder returns
|
|
19
|
+
the unsigned call (to / data / value) for the owner's wallet to sign.
|
|
20
|
+
``get_key_status`` reads a key's live state without a wallet.
|
|
21
|
+
|
|
22
|
+
Calldata is encoded by hand (stdlib only) — the selectors below were
|
|
23
|
+
verified against the on-chain ABI, and the unit tests check the encoding
|
|
24
|
+
against viem's output byte for byte.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
import re
|
|
28
|
+
import time
|
|
29
|
+
|
|
30
|
+
import requests
|
|
31
|
+
|
|
32
|
+
from .constants import SPEND_VAULT_ADDRESS, X402
|
|
33
|
+
from .errors import PolypadError
|
|
34
|
+
|
|
35
|
+
# Function selectors (first 4 bytes of keccak of the signature), verified.
|
|
36
|
+
_SELECTORS = {
|
|
37
|
+
"deposit(address,uint256)": "47e7ef24",
|
|
38
|
+
"withdraw(address,uint256)": "f3fef3a3",
|
|
39
|
+
"createKey(address,address,uint256,uint256,address[],uint64)": "9d30cddc",
|
|
40
|
+
"revokeKey(address)": "5ae7ab32",
|
|
41
|
+
"balances(address,address)": "c23f001f",
|
|
42
|
+
"keys(address)": "670d14b2",
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
_ADDRESS_RE = re.compile(r"^0x[0-9a-fA-F]{40}$")
|
|
46
|
+
ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _require_address(value, field):
|
|
50
|
+
if not isinstance(value, str) or not _ADDRESS_RE.match(value):
|
|
51
|
+
raise PolypadError(f"{field} must be a 0x wallet address.", "invalid_params", extra={"field": field})
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _word(value):
|
|
55
|
+
return int(value).to_bytes(32, "big")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _address_word(address):
|
|
59
|
+
return bytes.fromhex(address[2:].lower()).rjust(32, b"\x00")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _token_address(token):
|
|
63
|
+
if token == "USDG":
|
|
64
|
+
return X402["usdg"]["address"]
|
|
65
|
+
if token == "POLYDASH":
|
|
66
|
+
return X402["polydash"]["address"]
|
|
67
|
+
return token
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def spend_vault_key_flow():
|
|
71
|
+
"""The key flow in plain words — for docs, prompts, and agent instructions."""
|
|
72
|
+
return [
|
|
73
|
+
"The owner opens polypad.family/agents/accounts and connects their own wallet.",
|
|
74
|
+
"The owner deposits USDG or POLYDASH into the SpendVault (the vault holds the money; the agent never holds it).",
|
|
75
|
+
"The owner creates a spending key for the agent wallet address: the token, a per-payment cap, a daily cap, the addresses the agent may pay, and an expiry date.",
|
|
76
|
+
"The agent spends from the vault with that wallet, inside the caps. The vault enforces them on-chain.",
|
|
77
|
+
"The owner can withdraw the money back or revoke the key at any time.",
|
|
78
|
+
"A spending key is a wallet address, not a password or secret. Never share a private key — Polypad never asks for one.",
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _rpc_call(rpc_url, method, params, session=None):
|
|
83
|
+
session = session or requests.Session()
|
|
84
|
+
response = session.post(rpc_url, json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params}, timeout=30)
|
|
85
|
+
response.raise_for_status()
|
|
86
|
+
body = response.json()
|
|
87
|
+
if body.get("error"):
|
|
88
|
+
raise PolypadError(f"Robinhood Chain RPC error: {body['error'].get('message', body['error'])}", "rpc_unavailable")
|
|
89
|
+
return body.get("result")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def get_key_status(key_address, rpc_url=None, session=None):
|
|
93
|
+
"""Read a spending key's live state (caps, expiry, revoked, spent today). Returns None when the address has no key."""
|
|
94
|
+
_require_address(key_address, "key_address")
|
|
95
|
+
rpc_url = rpc_url or X402["rpc_url"]
|
|
96
|
+
data = "0x" + _SELECTORS["keys(address)"] + _address_word(key_address).hex()
|
|
97
|
+
result = _rpc_call(rpc_url, "eth_call", [{"to": SPEND_VAULT_ADDRESS, "data": data}, "latest"], session=session)
|
|
98
|
+
raw = bytes.fromhex(result[2:])
|
|
99
|
+
if len(raw) < 288:
|
|
100
|
+
raise PolypadError("The SpendVault answered with a short key record.", "invalid_response")
|
|
101
|
+
words = [int.from_bytes(raw[i * 32 : (i + 1) * 32], "big") for i in range(9)]
|
|
102
|
+
owner = "0x" + raw[0 * 32 + 12 : 0 * 32 + 32].hex()
|
|
103
|
+
token = "0x" + raw[1 * 32 + 12 : 1 * 32 + 32].hex()
|
|
104
|
+
if owner.lower() == ZERO_ADDRESS:
|
|
105
|
+
return None
|
|
106
|
+
return {
|
|
107
|
+
"key": key_address,
|
|
108
|
+
"owner": owner,
|
|
109
|
+
"token": token,
|
|
110
|
+
"per_payment_cap": words[2],
|
|
111
|
+
"daily_cap": words[3],
|
|
112
|
+
"expiry": words[4],
|
|
113
|
+
"revoked": words[5] != 0,
|
|
114
|
+
"spent_today": words[7],
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def get_vault_balance(owner, token, rpc_url=None, session=None):
|
|
119
|
+
"""Read how much of a token an owner has in the vault."""
|
|
120
|
+
_require_address(owner, "owner")
|
|
121
|
+
token_address = _token_address(token)
|
|
122
|
+
_require_address(token_address, "token")
|
|
123
|
+
rpc_url = rpc_url or X402["rpc_url"]
|
|
124
|
+
data = "0x" + _SELECTORS["balances(address,address)"] + _address_word(owner).hex() + _address_word(token_address).hex()
|
|
125
|
+
result = _rpc_call(rpc_url, "eth_call", [{"to": SPEND_VAULT_ADDRESS, "data": data}, "latest"], session=session)
|
|
126
|
+
return int(result, 16)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def build_create_key_tx(key, token, per_payment_cap, daily_cap, allowlist=None, expiry=None):
|
|
130
|
+
"""Unsigned ``createKey`` call for the owner's wallet to sign. The owner signs this — never the agent.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
key: The agent's wallet address — this IS the key.
|
|
134
|
+
token: "USDG", "POLYDASH", or a token address.
|
|
135
|
+
per_payment_cap: Largest single payment, in the token's smallest units.
|
|
136
|
+
daily_cap: Largest total per day, in the token's smallest units. Must be at least the per-payment cap.
|
|
137
|
+
allowlist: Addresses the agent may pay. Defaults to [].
|
|
138
|
+
expiry: Expiry as a Unix timestamp (seconds). Must be in the future.
|
|
139
|
+
"""
|
|
140
|
+
_require_address(key, "key")
|
|
141
|
+
token_address = _token_address(token)
|
|
142
|
+
_require_address(token_address, "token")
|
|
143
|
+
if per_payment_cap <= 0 or daily_cap <= 0:
|
|
144
|
+
raise PolypadError("Caps must be above zero.", "invalid_params")
|
|
145
|
+
if per_payment_cap > daily_cap:
|
|
146
|
+
raise PolypadError("The per-payment cap cannot be larger than the daily cap.", "invalid_params")
|
|
147
|
+
if expiry is None or expiry * 1000 <= int(time.time() * 1000):
|
|
148
|
+
raise PolypadError("The expiry must be in the future.", "invalid_params")
|
|
149
|
+
allowlist = allowlist or []
|
|
150
|
+
for i, address in enumerate(allowlist):
|
|
151
|
+
_require_address(address, f"allowlist[{i}]")
|
|
152
|
+
# Head: 6 words (key, token, perPaymentCap, dailyCap, allowlist offset, expiry).
|
|
153
|
+
# The allowlist is dynamic, so its offset points past the head (6 * 32 = 192).
|
|
154
|
+
head = b"".join(
|
|
155
|
+
[
|
|
156
|
+
_address_word(key),
|
|
157
|
+
_address_word(token_address),
|
|
158
|
+
_word(per_payment_cap),
|
|
159
|
+
_word(daily_cap),
|
|
160
|
+
_word(192),
|
|
161
|
+
_word(expiry),
|
|
162
|
+
]
|
|
163
|
+
)
|
|
164
|
+
tail = _word(len(allowlist)) + b"".join(_address_word(a) for a in allowlist)
|
|
165
|
+
data = "0x" + _SELECTORS["createKey(address,address,uint256,uint256,address[],uint64)"] + (head + tail).hex()
|
|
166
|
+
return {
|
|
167
|
+
"to": SPEND_VAULT_ADDRESS,
|
|
168
|
+
"data": data,
|
|
169
|
+
"value": "0",
|
|
170
|
+
"chainId": 4663,
|
|
171
|
+
"description": f"Create a spending key for {key} (token {token_address}, per-payment cap {per_payment_cap}, daily cap {daily_cap}).",
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def build_deposit_tx(token, amount):
|
|
176
|
+
"""Unsigned ``deposit`` call for the owner's wallet to sign. Approve the vault to take the tokens first."""
|
|
177
|
+
token_address = _token_address(token)
|
|
178
|
+
_require_address(token_address, "token")
|
|
179
|
+
if amount <= 0:
|
|
180
|
+
raise PolypadError("Deposit amount must be above zero.", "invalid_params")
|
|
181
|
+
data = "0x" + _SELECTORS["deposit(address,uint256)"] + _address_word(token_address).hex() + _word(amount).hex()
|
|
182
|
+
return {
|
|
183
|
+
"to": SPEND_VAULT_ADDRESS,
|
|
184
|
+
"data": data,
|
|
185
|
+
"value": "0",
|
|
186
|
+
"chainId": 4663,
|
|
187
|
+
"description": f"Deposit {amount} of {token_address} into the SpendVault.",
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def build_withdraw_tx(token, amount):
|
|
192
|
+
"""Unsigned ``withdraw`` call for the owner's wallet to sign — takes money back out of the vault."""
|
|
193
|
+
token_address = _token_address(token)
|
|
194
|
+
_require_address(token_address, "token")
|
|
195
|
+
if amount <= 0:
|
|
196
|
+
raise PolypadError("Withdraw amount must be above zero.", "invalid_params")
|
|
197
|
+
data = "0x" + _SELECTORS["withdraw(address,uint256)"] + _address_word(token_address).hex() + _word(amount).hex()
|
|
198
|
+
return {
|
|
199
|
+
"to": SPEND_VAULT_ADDRESS,
|
|
200
|
+
"data": data,
|
|
201
|
+
"value": "0",
|
|
202
|
+
"chainId": 4663,
|
|
203
|
+
"description": f"Withdraw {amount} of {token_address} from the SpendVault.",
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def build_revoke_key_tx(key):
|
|
208
|
+
"""Unsigned ``revokeKey`` call for the owner's wallet to sign — the agent can no longer spend."""
|
|
209
|
+
_require_address(key, "key")
|
|
210
|
+
data = "0x" + _SELECTORS["revokeKey(address)"] + _address_word(key).hex()
|
|
211
|
+
return {
|
|
212
|
+
"to": SPEND_VAULT_ADDRESS,
|
|
213
|
+
"data": data,
|
|
214
|
+
"value": "0",
|
|
215
|
+
"chainId": 4663,
|
|
216
|
+
"description": f"Revoke the spending key for {key}.",
|
|
217
|
+
}
|
polypad_agent/tools.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""The 21 ``polypad_*`` tools.
|
|
2
|
+
|
|
3
|
+
Arguments are plain dicts whose keys match the server exactly — including
|
|
4
|
+
``templateId`` (the site calls it a Strategy id) and ``from`` (always a
|
|
5
|
+
wallet *address*, never a private key). Amounts in wei are decimal strings;
|
|
6
|
+
amounts in ETH are plain decimals like "0.01". On prepare calls ``from`` is
|
|
7
|
+
optional when a wallet token is bound — the client passes ``walletToken``
|
|
8
|
+
instead and the server resolves the wallet.
|
|
9
|
+
|
|
10
|
+
Per-tool arguments (required fields marked *):
|
|
11
|
+
|
|
12
|
+
- what_can_i_do: {}
|
|
13
|
+
- intent: {"text"*, "from", "ref"}
|
|
14
|
+
- list_tokens: {"sort" (trending/new/graduating/volume/graduated), "q", "phase", "agentLaunched", "limit"}
|
|
15
|
+
- get_token: {"token"*}
|
|
16
|
+
- token_protections: {"token"*}
|
|
17
|
+
- quote_trade: {"token"*, "side"* (buy/sell), "amount", "amountEth", "slippageBps"}
|
|
18
|
+
- prepare_buy: {"token"*, "from"*, "amountEth", "amountWei", "slippageBps", "confirmLarge", "ref"}
|
|
19
|
+
- prepare_sell: {"token"*, "from"*, "amount", "percentOfBalance", "slippageBps", "ref"}
|
|
20
|
+
- list_nfts: {"q", "status", "sort", "limit"}
|
|
21
|
+
- list_nft_listings: {"collection", "maxPriceEth", "maxPriceWei", "limit"}
|
|
22
|
+
- prepare_nft_buy: {"from"*, "listingId", "collection", "collectionName", "quantity", "confirmLarge", "ref"}
|
|
23
|
+
- list_fund_templates: {}
|
|
24
|
+
- list_funds: {"open", "status", "templateId", "asset", "manager", "factory", "q", "sort", "limit"}
|
|
25
|
+
- get_fund: {"fund"*}
|
|
26
|
+
- prepare_fund_create: {"from"*, "name"*, "symbol"*, "templateId", "assets", "mintPriceEth",
|
|
27
|
+
"mintPriceWei", "raiseCapEth", "raiseCapWei", "entryFeeBps", "raiseDurationDays",
|
|
28
|
+
"minSkinBps", "imageUri", "factory", "ref"}
|
|
29
|
+
- prepare_fund_mint: {"from"*, "fund"*, "quantity", "confirmLarge", "ref"}
|
|
30
|
+
- prepare_fund_redeem: {"from"*, "fund"*, "quantity", "ids", "ref"}
|
|
31
|
+
- prepare_token_launch: {"from"*, "name"*, "symbol"*, "creatorFeeBps"* (0–500),
|
|
32
|
+
"imageUri", "description", "socialLinks", "devBuyEth", "launchDelay", "agentMark", "repository", "ref"}
|
|
33
|
+
- portfolio: {"address"*}
|
|
34
|
+
- get_tx_status: {"hash"*}
|
|
35
|
+
- stats: {}
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
TOOL_NAMES = [
|
|
39
|
+
"polypad_what_can_i_do",
|
|
40
|
+
"polypad_intent",
|
|
41
|
+
"polypad_list_tokens",
|
|
42
|
+
"polypad_get_token",
|
|
43
|
+
"polypad_token_protections",
|
|
44
|
+
"polypad_quote_trade",
|
|
45
|
+
"polypad_prepare_buy",
|
|
46
|
+
"polypad_prepare_sell",
|
|
47
|
+
"polypad_list_nfts",
|
|
48
|
+
"polypad_list_nft_listings",
|
|
49
|
+
"polypad_prepare_nft_buy",
|
|
50
|
+
"polypad_list_fund_templates",
|
|
51
|
+
"polypad_list_funds",
|
|
52
|
+
"polypad_get_fund",
|
|
53
|
+
"polypad_prepare_fund_create",
|
|
54
|
+
"polypad_prepare_fund_mint",
|
|
55
|
+
"polypad_prepare_fund_redeem",
|
|
56
|
+
"polypad_prepare_token_launch",
|
|
57
|
+
"polypad_portfolio",
|
|
58
|
+
"polypad_get_tx_status",
|
|
59
|
+
"polypad_stats",
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
PREPARE_TOOLS = [
|
|
63
|
+
"polypad_prepare_buy",
|
|
64
|
+
"polypad_prepare_sell",
|
|
65
|
+
"polypad_prepare_nft_buy",
|
|
66
|
+
"polypad_prepare_fund_create",
|
|
67
|
+
"polypad_prepare_fund_mint",
|
|
68
|
+
"polypad_prepare_fund_redeem",
|
|
69
|
+
"polypad_prepare_token_launch",
|
|
70
|
+
]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def is_prepare_tool(name):
|
|
74
|
+
return name in PREPARE_TOOLS
|