@onecraft/wallet 0.0.0-stage → 0.1.145

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.
Files changed (248) hide show
  1. package/.claude-plugin/marketplace.json +20 -0
  2. package/.openclaw/AGENTS.md +100 -0
  3. package/.openclaw/extensions/agent-wallet/README.md +195 -0
  4. package/.openclaw/extensions/agent-wallet/dist/index.js +2198 -0
  5. package/.openclaw/extensions/agent-wallet/index.ts +2198 -0
  6. package/.openclaw/extensions/agent-wallet/openclaw.plugin.json +251 -0
  7. package/.openclaw/extensions/agent-wallet/package.json +49 -0
  8. package/.openclaw/extensions/agent-wallet/skills/cards/SKILL.md +211 -0
  9. package/.openclaw/extensions/agent-wallet/skills/wallet-operator/SKILL.md +30 -0
  10. package/CHANGELOG.md +1232 -0
  11. package/LICENSE +104 -0
  12. package/README.md +193 -2
  13. package/VERSION +1 -0
  14. package/agent-wallet/.env.example +63 -0
  15. package/agent-wallet/AGENTS.md +130 -0
  16. package/agent-wallet/CARD_VAULT.md +640 -0
  17. package/agent-wallet/README.md +615 -0
  18. package/agent-wallet/UPGRADE_COMPATIBILITY.md +66 -0
  19. package/agent-wallet/agent_wallet/__init__.py +16 -0
  20. package/agent-wallet/agent_wallet/approval.py +165 -0
  21. package/agent-wallet/agent_wallet/autonomous_permissions.py +281 -0
  22. package/agent-wallet/agent_wallet/autonomous_policy.py +305 -0
  23. package/agent-wallet/agent_wallet/autonomous_session.py +236 -0
  24. package/agent-wallet/agent_wallet/boot_key_migration.py +155 -0
  25. package/agent-wallet/agent_wallet/boot_key_recovery.py +57 -0
  26. package/agent-wallet/agent_wallet/bootstrap.py +194 -0
  27. package/agent-wallet/agent_wallet/card_catalog.py +243 -0
  28. package/agent-wallet/agent_wallet/card_runtime_secrets.py +108 -0
  29. package/agent-wallet/agent_wallet/card_vault.py +331 -0
  30. package/agent-wallet/agent_wallet/card_vault_cli.py +174 -0
  31. package/agent-wallet/agent_wallet/card_vault_import.py +65 -0
  32. package/agent-wallet/agent_wallet/card_vault_keychain.py +239 -0
  33. package/agent-wallet/agent_wallet/config.py +719 -0
  34. package/agent-wallet/agent_wallet/connector_cli.py +198 -0
  35. package/agent-wallet/agent_wallet/connectors/__init__.py +28 -0
  36. package/agent-wallet/agent_wallet/connectors/catalog.py +68 -0
  37. package/agent-wallet/agent_wallet/connectors/client.py +308 -0
  38. package/agent-wallet/agent_wallet/connectors/intent_policy.py +243 -0
  39. package/agent-wallet/agent_wallet/connectors/manifest.py +192 -0
  40. package/agent-wallet/agent_wallet/connectors/registry.py +341 -0
  41. package/agent-wallet/agent_wallet/encrypted_storage.py +314 -0
  42. package/agent-wallet/agent_wallet/evm_user_wallets.py +910 -0
  43. package/agent-wallet/agent_wallet/exceptions.py +10 -0
  44. package/agent-wallet/agent_wallet/file_ops.py +34 -0
  45. package/agent-wallet/agent_wallet/http_client.py +25 -0
  46. package/agent-wallet/agent_wallet/kernel_browser.py +479 -0
  47. package/agent-wallet/agent_wallet/kernel_cli.py +57 -0
  48. package/agent-wallet/agent_wallet/kernel_gateway.py +95 -0
  49. package/agent-wallet/agent_wallet/keystore.py +503 -0
  50. package/agent-wallet/agent_wallet/laso_card_vault.py +246 -0
  51. package/agent-wallet/agent_wallet/models.py +66 -0
  52. package/agent-wallet/agent_wallet/morpho_monitor.py +298 -0
  53. package/agent-wallet/agent_wallet/nonce_registry.py +59 -0
  54. package/agent-wallet/agent_wallet/openclaw_adapter.py +9129 -0
  55. package/agent-wallet/agent_wallet/openclaw_cli.py +658 -0
  56. package/agent-wallet/agent_wallet/openclaw_runtime.py +194 -0
  57. package/agent-wallet/agent_wallet/plugin_bundle.py +44 -0
  58. package/agent-wallet/agent_wallet/providers/__init__.py +1 -0
  59. package/agent-wallet/agent_wallet/providers/bags.py +202 -0
  60. package/agent-wallet/agent_wallet/providers/dexscreener.py +147 -0
  61. package/agent-wallet/agent_wallet/providers/evm_activity.py +257 -0
  62. package/agent-wallet/agent_wallet/providers/evm_portfolio.py +459 -0
  63. package/agent-wallet/agent_wallet/providers/imd.py +720 -0
  64. package/agent-wallet/agent_wallet/providers/jupiter.py +519 -0
  65. package/agent-wallet/agent_wallet/providers/kamino.py +404 -0
  66. package/agent-wallet/agent_wallet/providers/lifi.py +302 -0
  67. package/agent-wallet/agent_wallet/providers/solana_rpc.py +447 -0
  68. package/agent-wallet/agent_wallet/providers/tokenized_stocks.py +189 -0
  69. package/agent-wallet/agent_wallet/providers/wdk_evm_local.py +346 -0
  70. package/agent-wallet/agent_wallet/providers/x402.py +1972 -0
  71. package/agent-wallet/agent_wallet/sealed_keys.py +118 -0
  72. package/agent-wallet/agent_wallet/solana_stake.py +103 -0
  73. package/agent-wallet/agent_wallet/solana_tx.py +93 -0
  74. package/agent-wallet/agent_wallet/spending_limits.py +119 -0
  75. package/agent-wallet/agent_wallet/telemetry.py +481 -0
  76. package/agent-wallet/agent_wallet/transaction_policy.py +573 -0
  77. package/agent-wallet/agent_wallet/update_check.py +190 -0
  78. package/agent-wallet/agent_wallet/user_wallets.py +573 -0
  79. package/agent-wallet/agent_wallet/validation.py +31 -0
  80. package/agent-wallet/agent_wallet/vault_executor.py +456 -0
  81. package/agent-wallet/agent_wallet/wallet_layer/__init__.py +1 -0
  82. package/agent-wallet/agent_wallet/wallet_layer/base.py +1204 -0
  83. package/agent-wallet/agent_wallet/wallet_layer/base58.py +44 -0
  84. package/agent-wallet/agent_wallet/wallet_layer/factory.py +117 -0
  85. package/agent-wallet/agent_wallet/wallet_layer/solana.py +5246 -0
  86. package/agent-wallet/agent_wallet/wallet_layer/wdk_evm.py +2705 -0
  87. package/agent-wallet/examples/bootstrap_wallet.py +21 -0
  88. package/agent-wallet/examples/openclaw_runtime_onboarding.py +28 -0
  89. package/agent-wallet/examples/openclaw_user_wallet_example.py +31 -0
  90. package/agent-wallet/examples/openclaw_wallet_adapter_example.py +33 -0
  91. package/agent-wallet/openclaw.plugin.json +118 -0
  92. package/agent-wallet/pyproject.toml +36 -0
  93. package/agent-wallet/scripts/bootstrap_openclaw_evm.py +312 -0
  94. package/agent-wallet/scripts/build_release_bundle.py +210 -0
  95. package/agent-wallet/scripts/finalize_openclaw_local_wallet_config.py +121 -0
  96. package/agent-wallet/scripts/install_agent_wallet.py +1357 -0
  97. package/agent-wallet/scripts/install_openclaw_local_config.py +421 -0
  98. package/agent-wallet/scripts/install_openclaw_sealed_keys.py +117 -0
  99. package/agent-wallet/scripts/manage_openclaw_evm_wallet.py +333 -0
  100. package/agent-wallet/scripts/security_utils.py +37 -0
  101. package/agent-wallet/scripts/setup_evm_wallet.sh +140 -0
  102. package/agent-wallet/scripts/switch_openclaw_wallet_network.py +109 -0
  103. package/agent-wallet/skills/wallet-operator/SKILL.md +157 -0
  104. package/bin/lib/boot-key.mjs +184 -0
  105. package/bin/lib/evm-daemon.mjs +389 -0
  106. package/bin/lib/host-detection.mjs +259 -0
  107. package/bin/lib/integrations.mjs +578 -0
  108. package/bin/lib/release-python.mjs +9 -0
  109. package/bin/lib/update-transaction.mjs +235 -0
  110. package/bin/openclaw-agent-wallet.mjs +3354 -0
  111. package/claude-code/plugins/agent-wallet/.claude-plugin/plugin.json +19 -0
  112. package/claude-code/plugins/agent-wallet/.mcp.json +14 -0
  113. package/claude-code/plugins/agent-wallet/AGENTLAYER_AGENT_GUIDE.md +282 -0
  114. package/claude-code/plugins/agent-wallet/README.md +134 -0
  115. package/claude-code/plugins/agent-wallet/commands/agentlayer-autonomous-approve.md +39 -0
  116. package/claude-code/plugins/agent-wallet/commands/agentlayer-autonomous-revoke.md +17 -0
  117. package/claude-code/plugins/agent-wallet/commands/cards.md +129 -0
  118. package/claude-code/plugins/agent-wallet/commands/guide.md +40 -0
  119. package/claude-code/plugins/agent-wallet/commands/imd.md +125 -0
  120. package/claude-code/plugins/agent-wallet/commands/wallet-base.md +60 -0
  121. package/claude-code/plugins/agent-wallet/commands/wallet-ethereum.md +37 -0
  122. package/claude-code/plugins/agent-wallet/commands/wallet-evm.md +39 -0
  123. package/claude-code/plugins/agent-wallet/commands/wallet-setup.md +25 -0
  124. package/claude-code/plugins/agent-wallet/commands/wallet-sol.md +51 -0
  125. package/claude-code/plugins/agent-wallet/commands/wallet-statusline.md +34 -0
  126. package/claude-code/plugins/agent-wallet/commands/x402.md +121 -0
  127. package/claude-code/plugins/agent-wallet/commands/yield.md +62 -0
  128. package/claude-code/plugins/agent-wallet/hooks/hooks.json +16 -0
  129. package/claude-code/plugins/agent-wallet/scripts/bootstrap_backend.sh +136 -0
  130. package/claude-code/plugins/agent-wallet/scripts/enable_statusline.py +52 -0
  131. package/claude-code/plugins/agent-wallet/scripts/resolve_wallet_addresses.py +69 -0
  132. package/claude-code/plugins/agent-wallet/scripts/run_mcp.sh +66 -0
  133. package/claude-code/plugins/agent-wallet/scripts/wallet_statusline.py +130 -0
  134. package/claude-code/plugins/agent-wallet/scripts/wallet_statusline_setup.sh +40 -0
  135. package/claude-code/plugins/agent-wallet/skills/wallet-operator/SKILL.md +21 -0
  136. package/codex/plugins/agent-wallet/.codex-plugin/plugin.json +37 -0
  137. package/codex/plugins/agent-wallet/.mcp.json +15 -0
  138. package/codex/plugins/agent-wallet/README.md +158 -0
  139. package/codex/plugins/agent-wallet/scripts/run_mcp.sh +47 -0
  140. package/codex/plugins/agent-wallet/server.py +1797 -0
  141. package/codex/plugins/agent-wallet/skills/cards/SKILL.md +225 -0
  142. package/codex/plugins/agent-wallet/skills/imd/SKILL.md +145 -0
  143. package/codex/plugins/agent-wallet/skills/wallet-base/SKILL.md +56 -0
  144. package/codex/plugins/agent-wallet/skills/wallet-operator/SKILL.md +85 -0
  145. package/codex/plugins/agent-wallet/skills/wallet-sol/SKILL.md +29 -0
  146. package/codex/plugins/agent-wallet/skills/x402/SKILL.md +159 -0
  147. package/codex/plugins/agent-wallet/skills/yield/SKILL.md +65 -0
  148. package/connectors/AGENTS.md +37 -0
  149. package/connectors/DEVELOPER_GUIDE.md +131 -0
  150. package/connectors/README.md +139 -0
  151. package/connectors/READ_ONLY_BETA.md +54 -0
  152. package/connectors/RELEASING.md +48 -0
  153. package/connectors/conformance/README.md +31 -0
  154. package/connectors/conformance/package.json +54 -0
  155. package/connectors/conformance/scripts/sync-license.mjs +3 -0
  156. package/connectors/conformance/scripts/sync-spec.mjs +16 -0
  157. package/connectors/conformance/src/cli.ts +43 -0
  158. package/connectors/conformance/src/index.ts +7 -0
  159. package/connectors/conformance/src/runner.ts +314 -0
  160. package/connectors/conformance/src/types.ts +27 -0
  161. package/connectors/conformance/test/fixtures/invalid-response-identity.json +14 -0
  162. package/connectors/conformance/test/fixtures/missing-tool-fixture.json +4 -0
  163. package/connectors/conformance/test/runner.test.mjs +151 -0
  164. package/connectors/conformance/tsconfig.json +17 -0
  165. package/connectors/examples/reference-crypto-data/Dockerfile +21 -0
  166. package/connectors/examples/reference-crypto-data/README.md +51 -0
  167. package/connectors/examples/reference-crypto-data/conformance.json +11 -0
  168. package/connectors/examples/reference-crypto-data/connector.json +95 -0
  169. package/connectors/examples/reference-crypto-data/package.json +21 -0
  170. package/connectors/examples/reference-crypto-data/railway.toml +9 -0
  171. package/connectors/examples/reference-crypto-data/src/connector.ts +137 -0
  172. package/connectors/examples/reference-crypto-data/src/server.ts +13 -0
  173. package/connectors/examples/reference-crypto-data/test/connector.test.mjs +97 -0
  174. package/connectors/examples/reference-crypto-data/tsconfig.json +17 -0
  175. package/connectors/package-lock.json +561 -0
  176. package/connectors/package.json +19 -0
  177. package/connectors/scripts/smoke-packed-packages.mjs +121 -0
  178. package/connectors/sdk-typescript/README.md +47 -0
  179. package/connectors/sdk-typescript/package.json +49 -0
  180. package/connectors/sdk-typescript/scripts/sync-license.mjs +3 -0
  181. package/connectors/sdk-typescript/src/connector.ts +204 -0
  182. package/connectors/sdk-typescript/src/errors.ts +11 -0
  183. package/connectors/sdk-typescript/src/http.ts +116 -0
  184. package/connectors/sdk-typescript/src/index.ts +26 -0
  185. package/connectors/sdk-typescript/src/types.ts +101 -0
  186. package/connectors/sdk-typescript/test/sdk.test.mjs +181 -0
  187. package/connectors/sdk-typescript/tsconfig.json +21 -0
  188. package/connectors/spec/connector-manifest.schema.json +340 -0
  189. package/connectors/spec/connector-protocol.md +159 -0
  190. package/connectors/spec/transaction-intent.schema.json +281 -0
  191. package/connectors/templates/read-only/.env.example +1 -0
  192. package/connectors/templates/read-only/Dockerfile +11 -0
  193. package/connectors/templates/read-only/README.md +33 -0
  194. package/connectors/templates/read-only/conformance.json +11 -0
  195. package/connectors/templates/read-only/connector.json +64 -0
  196. package/connectors/templates/read-only/package.json +21 -0
  197. package/connectors/templates/read-only/railway.toml +9 -0
  198. package/connectors/templates/read-only/src/connector.ts +61 -0
  199. package/connectors/templates/read-only/src/server.ts +14 -0
  200. package/connectors/templates/read-only/test/connector.test.mjs +62 -0
  201. package/connectors/templates/read-only/tsconfig.json +17 -0
  202. package/cursor/plugins/agent-wallet/.cursor-plugin/plugin.json +14 -0
  203. package/cursor/plugins/agent-wallet/README.md +62 -0
  204. package/cursor/plugins/agent-wallet/mcp.json +16 -0
  205. package/cursor/plugins/agent-wallet/scripts/run_mcp.sh +33 -0
  206. package/cursor/plugins/agent-wallet/server.py +33 -0
  207. package/cursor/plugins/agent-wallet/skills/cards/SKILL.md +210 -0
  208. package/cursor/plugins/agent-wallet/skills/wallet-base/SKILL.md +56 -0
  209. package/cursor/plugins/agent-wallet/skills/wallet-operator/SKILL.md +23 -0
  210. package/cursor/plugins/agent-wallet/skills/wallet-sol/SKILL.md +29 -0
  211. package/cursor/plugins/agent-wallet/skills/x402/SKILL.md +130 -0
  212. package/hermes/plugins/agent_wallet/README.md +54 -0
  213. package/hermes/plugins/agent_wallet/__init__.py +55 -0
  214. package/hermes/plugins/agent_wallet/plugin.yaml +9 -0
  215. package/hermes/plugins/agent_wallet/schemas.py +211 -0
  216. package/hermes/plugins/agent_wallet/tools.py +622 -0
  217. package/install-from-github.sh +139 -0
  218. package/integrations/hedera/treasury-guard/README.md +92 -0
  219. package/integrations/hedera/treasury-guard/examples/treasury-policy.example.json +9 -0
  220. package/integrations/hedera/treasury-guard/package-lock.json +880 -0
  221. package/integrations/hedera/treasury-guard/package.json +8 -0
  222. package/integrations/hedera/treasury-guard/skills/onecraft-hedera-treasury/SKILL.md +22 -0
  223. package/integrations/hedera/treasury-guard/src/hedera-mirror-client.mjs +106 -0
  224. package/integrations/hedera/treasury-guard/src/hedera-signer.mjs +120 -0
  225. package/integrations/hedera/treasury-guard/src/treasury-cli.mjs +177 -0
  226. package/integrations/hedera/treasury-guard/src/treasury-policy.mjs +155 -0
  227. package/mcp/README.md +39 -0
  228. package/mcp/scripts/run_mcp.sh +37 -0
  229. package/mcp/server.py +33 -0
  230. package/package.json +106 -4
  231. package/scripts/check_release_version.mjs +72 -0
  232. package/scripts/version_targets.mjs +60 -0
  233. package/setup.sh +87 -0
  234. package/wdk-evm-wallet/.env.example +38 -0
  235. package/wdk-evm-wallet/README.md +254 -0
  236. package/wdk-evm-wallet/bootstrap.sh +8 -0
  237. package/wdk-evm-wallet/package-lock.json +2359 -0
  238. package/wdk-evm-wallet/package.json +43 -0
  239. package/wdk-evm-wallet/run-local.sh +12 -0
  240. package/wdk-evm-wallet/src/config.js +461 -0
  241. package/wdk-evm-wallet/src/imd.js +231 -0
  242. package/wdk-evm-wallet/src/json.js +35 -0
  243. package/wdk-evm-wallet/src/local_vault.js +407 -0
  244. package/wdk-evm-wallet/src/network_state.js +96 -0
  245. package/wdk-evm-wallet/src/pending_transactions.js +148 -0
  246. package/wdk-evm-wallet/src/server.js +849 -0
  247. package/wdk-evm-wallet/src/shutdown.js +63 -0
  248. package/wdk-evm-wallet/src/wdk_evm_wallet.js +10036 -0
@@ -0,0 +1,246 @@
1
+ """Capture Laso card responses before the host or model can observe them."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import json
6
+ import posixpath
7
+ import time
8
+ from datetime import datetime, timezone
9
+ from typing import Any
10
+ from urllib.parse import unquote, urlsplit
11
+
12
+ import httpx
13
+
14
+ from agent_wallet.card_vault import CardVault, MAX_BYTES
15
+ from agent_wallet.card_catalog import (
16
+ CardCatalog, CARD_TYPES, MIN_REFRESH_INTERVAL, card_object, credentials, details_ready,
17
+ )
18
+ from agent_wallet.providers.x402 import LASO_PARTNER_HEADERS
19
+ from agent_wallet.wallet_layer.base import WalletBackendError
20
+
21
+ ORDER_PATHS = {"/get-card": "Non-Reloadable U.S.", "/order-intl-card": "Non-Reloadable International"}
22
+ STATUSES = {"pending", "queued", "ready", "failed", "cancelled", "expired", "depleted"}
23
+
24
+
25
+ def card_path(url: str) -> str | None:
26
+ parsed = urlsplit(url)
27
+ host = parsed.hostname or ""
28
+ if host != "laso.finance" and not host.endswith(".laso.finance"):
29
+ return None
30
+ decoded = parsed.path
31
+ for _ in range(3):
32
+ decoded = unquote(decoded)
33
+ path = posixpath.normpath(decoded).rstrip("/")
34
+ if path not in {*ORDER_PATHS, "/get-card-data"}:
35
+ return None
36
+ if parsed.scheme != "https" or parsed.netloc != "laso.finance" or parsed.fragment or parsed.path != path:
37
+ raise WalletBackendError("Card requests must use the exact HTTPS laso.finance host.")
38
+ return path
39
+
40
+
41
+ def preflight(url: str, user_id: str | None) -> CardVault | None:
42
+ path = card_path(url)
43
+ if path is None:
44
+ return None
45
+ if path == "/get-card-data":
46
+ raise WalletBackendError("Raw card retrieval is private. Use refresh_saved_card with a vault reference.")
47
+ vault = CardVault(user_id)
48
+ try:
49
+ vault.ensure_system()
50
+ vault.check_ready()
51
+ CardCatalog(vault).preflight()
52
+ except WalletBackendError:
53
+ raise
54
+ except Exception:
55
+ raise WalletBackendError("System card vault could not be provisioned. Check macOS login Keychain access before ordering.") from None
56
+ return vault
57
+
58
+
59
+ def summary(record: dict[str, Any], reference: str) -> dict[str, Any]:
60
+ card = card_object(record.get("latest") or record.get("order") or {})
61
+ details = card.get("card_details") or {}
62
+ number = str(details.get("card_number") or "") if isinstance(details, dict) else ""
63
+ status = card.get("status")
64
+ return {
65
+ "vault_reference": reference,
66
+ "status": status if isinstance(status, str) and status in STATUSES else "retrieval_required",
67
+ "last4": number[-4:] if number.isascii() and number.isdigit() and len(number) >= 12 else None,
68
+ "stored_encrypted": True,
69
+ }
70
+
71
+
72
+ async def _json_request(client: httpx.AsyncClient, method: str, url: str, **kwargs: Any) -> tuple[int, dict[str, Any]]:
73
+ # Bound responses; never include remote error bodies, URLs, or auth headers in exceptions.
74
+ async with client.stream(method, url, follow_redirects=False, **kwargs) as response:
75
+ if response.status_code != 200:
76
+ return response.status_code, {}
77
+ content = bytearray()
78
+ async for chunk in response.aiter_bytes():
79
+ content.extend(chunk)
80
+ if len(content) > MAX_BYTES // 2:
81
+ raise WalletBackendError("Laso card response exceeds size limit.")
82
+ body = json.loads(content)
83
+ if not isinstance(body, dict):
84
+ raise WalletBackendError("Laso returned an invalid card response.")
85
+ return response.status_code, body
86
+
87
+
88
+ async def refresh_record(
89
+ vault: CardVault, reference: str, record: dict[str, Any], *, attempts: int = 1,
90
+ catalog_state: dict[str, Any] | None = None,
91
+ ) -> dict[str, Any]:
92
+ """Free retrieval. Caller holds the record lock; no owner key is needed to save."""
93
+ catalog = CardCatalog(vault)
94
+ state = catalog_state
95
+ if state is None:
96
+ path = catalog._path(reference)
97
+ try:
98
+ state = catalog.load(reference) if path.exists() or path.is_symlink() else catalog.track(reference, record)
99
+ except WalletBackendError:
100
+ # Owner-only callers already supplied a decrypted record and can rebuild metadata.
101
+ state = catalog.track(reference, record)
102
+ order = record.get("order") or {}
103
+ card_id = card_object(order).get("card_id")
104
+ auth = credentials(record)
105
+ job = state.get("job")
106
+ if isinstance(job, dict) and job.get("card_id") == card_id:
107
+ # A prior process may have saved rotated tokens before writing the owner snapshot.
108
+ auth = credentials({"order": {"auth": job.get("auth")}})
109
+ record.setdefault("order", {})["auth"] = auth
110
+ token = auth.get("id_token")
111
+ if not isinstance(card_id, str) or not 0 < len(card_id) <= 128 or not token or record.get("card_type") not in CARD_TYPES:
112
+ raise WalletBackendError("Saved order has no valid retrieval credentials. Do not purchase again; review the saved order.")
113
+ try:
114
+ async with httpx.AsyncClient(timeout=20, headers={"Accept": "application/json", **LASO_PARTNER_HEADERS}, trust_env=False) as client:
115
+ for attempt in range(attempts):
116
+ if attempt:
117
+ await asyncio.sleep(MIN_REFRESH_INTERVAL)
118
+ if isinstance(state.get("job"), dict):
119
+ state["job"]["next_at"] = time.time() + (60 if record["card_type"] == "Non-Reloadable International" else MIN_REFRESH_INTERVAL)
120
+ count = state["job"].get("attempts", 0)
121
+ state["job"]["attempts"] = min(100000, max(0, count) + 1) if type(count) is int else 1
122
+ catalog.save(reference, state)
123
+ code, body = await _json_request(client, "GET", "https://laso.finance/get-card-data", params={"card_id": card_id, "card_type": record["card_type"]}, headers={"Authorization": f"Bearer {token}"})
124
+ if code == 401 and auth.get("refresh_token"):
125
+ code, fresh = await _json_request(client, "POST", "https://laso.finance/auth", json={"grant_type": "refresh_token", "refresh_token": auth["refresh_token"]})
126
+ fresh_auth = credentials({"order": {"auth": fresh}})
127
+ if code != 200 or not fresh_auth.get("id_token"):
128
+ if code in {400, 401, 403}:
129
+ state["job"] = None
130
+ state["refresh_state"] = "credentials_expired"
131
+ catalog.save(reference, state)
132
+ raise WalletBackendError("Laso credentials could not be renewed; the encrypted order is preserved.")
133
+ auth.update(fresh_auth)
134
+ record["order"]["auth"] = auth
135
+ if isinstance(state.get("job"), dict):
136
+ # Durable working credentials first, so a failed owner snapshot can be retried.
137
+ state["job"]["auth"] = dict(auth)
138
+ catalog.save(reference, state)
139
+ vault.store_update(reference, auth=auth)
140
+ token = auth["id_token"]
141
+ code, body = await _json_request(client, "GET", "https://laso.finance/get-card-data", params={"card_id": card_id, "card_type": record["card_type"]}, headers={"Authorization": f"Bearer {token}"})
142
+ if code != 200:
143
+ if code in {401, 403}:
144
+ state["job"] = None
145
+ state["refresh_state"] = "credentials_expired"
146
+ catalog.save(reference, state)
147
+ raise WalletBackendError("Laso retrieval failed; the encrypted order is preserved. Retry card status later.")
148
+ returned_id = card_object(body).get("card_id")
149
+ if returned_id is not None and returned_id != card_id:
150
+ raise WalletBackendError("Laso returned a different card ID; the saved order is preserved.")
151
+ record["latest"] = body
152
+ # Seal complete details for the owner before retiring runtime credentials.
153
+ vault.store_update(reference, latest=body, auth=auth)
154
+ catalog.update(reference, state, record)
155
+ if details_ready(record) or not state.get("job") or card_object(body).get("status") != "pending":
156
+ break
157
+ return record
158
+ except Exception as exc:
159
+ if isinstance(state.get("job"), dict):
160
+ count = state["job"].get("attempts", 1)
161
+ count = min(7, max(1, count)) if type(count) is int else 1
162
+ state["job"]["next_at"] = time.time() + min(300, MIN_REFRESH_INTERVAL * 2 ** count)
163
+ state["refresh_state"] = "retry_later"
164
+ catalog.save(reference, state)
165
+ if isinstance(exc, WalletBackendError):
166
+ raise
167
+ raise WalletBackendError("Laso retrieval failed; the encrypted order is preserved. Retry card status later.") from None
168
+
169
+
170
+ async def refresh_saved_card(vault: CardVault, reference: str) -> dict[str, Any]:
171
+ """Agent entrypoint: retrieve only an already purchased, scoped pending card."""
172
+ catalog = CardCatalog(vault)
173
+ if not catalog._path(reference).exists():
174
+ return catalog.get(reference)
175
+ async with vault.async_record_lock(reference):
176
+ state = catalog.load(reference)
177
+ job = state.get("job")
178
+ if not isinstance(job, dict):
179
+ return catalog.safe(reference, state)
180
+ now = time.time()
181
+ if type(job.get("expires_at")) not in {float, int} or not 946684800 <= job["expires_at"] <= 4133980800 or job["expires_at"] <= now:
182
+ state["job"] = None
183
+ state["refresh_state"] = "credentials_expired"
184
+ catalog.save(reference, state)
185
+ return catalog.safe(reference, state)
186
+ if type(job.get("next_at")) not in {float, int} or not 946684800 <= job["next_at"] <= 4133980800:
187
+ raise WalletBackendError("Invalid pending card schedule.")
188
+ if now < job["next_at"]:
189
+ return catalog.safe(reference, state)
190
+ card_type, card_id = job.get("card_type"), job.get("card_id")
191
+ if not isinstance(card_type, str) or card_type not in CARD_TYPES or not isinstance(card_id, str) or not 0 < len(card_id) <= 128:
192
+ raise WalletBackendError("Invalid pending card retrieval record.")
193
+ record = {"card_type": card_type, "order": {"card_id": card_id, "auth": job.get("auth")}}
194
+ try:
195
+ await refresh_record(vault, reference, record, catalog_state=state)
196
+ except WalletBackendError:
197
+ # Return a stable safe state and retry schedule, never a remote exception body.
198
+ pass
199
+ return catalog.safe(reference, state)
200
+
201
+
202
+ async def capture_request(*, call: Any, user_id: str | None, receipt_reference: str | None = None, **kwargs: Any) -> dict[str, Any]:
203
+ url = kwargs["url"]
204
+ vault = preflight(url, user_id)
205
+ if vault is None:
206
+ return await call(**kwargs)
207
+ path = card_path(url)
208
+ # A durable receipt exists even if settlement, transport, or persistence later fails.
209
+ record = {"type": "laso-card", "card_type": ORDER_PATHS[path], "created_at": datetime.now(timezone.utc).isoformat(), "state": "request_started", "request": {"url": url, "query": kwargs.get("query"), "payment": kwargs.get("approved_preview")}}
210
+ reference = vault.deposit(record, reference=receipt_reference)
211
+ async with vault.async_record_lock(reference):
212
+ try:
213
+ result = await call(**kwargs)
214
+ if result.get("status_code") != 200 or "response_preview" not in result:
215
+ # Quotes and explicit HTTP failures are not card receipts. Preserve
216
+ # the original status/error instead of replacing it with a fake card.
217
+ vault.remove_record(reference)
218
+ return result
219
+ body = result.get("response_preview")
220
+ record.update({"order": body if isinstance(body, dict) else {"unparsed_response": body}, "state": "response_saved", "http_status": result.get("status_code"), "payment_settlement": result.get("payment_settlement")})
221
+ record["payment_result"] = {
222
+ key: result[key] for key in ("paid", "broadcasted", "confirmed") if key in result
223
+ }
224
+ vault.deposit(record, reference=reference)
225
+ catalog = CardCatalog(vault)
226
+ state = catalog.track(reference, record)
227
+ notice = None
228
+ if result.get("status_code") == 200 and path == "/get-card" and not details_ready(record):
229
+ try:
230
+ record = await refresh_record(vault, reference, record, attempts=5, catalog_state=state)
231
+ except WalletBackendError:
232
+ notice = "Order saved. Use get_saved_card_status or refresh_saved_card later; do not purchase again."
233
+ safe = {**summary(record, reference), **catalog.safe(reference, state)}
234
+ if notice:
235
+ safe["notice"] = notice
236
+ # Allow no provider response fields into the model, including unexpected nested data.
237
+ result["response_preview"] = safe
238
+ return result
239
+ except Exception as exc:
240
+ record["failure"] = {"type": type(exc).__name__, "details": getattr(exc, "details", None)}
241
+ try:
242
+ vault.deposit(record, reference=reference)
243
+ CardCatalog(vault).track(reference, record)
244
+ except Exception:
245
+ pass
246
+ raise WalletBackendError(f"Laso request outcome needs review. Encrypted receipt: {reference}. Use wallet vault list; do not repeat payment automatically.") from None
@@ -0,0 +1,66 @@
1
+ """Pydantic models for wallet backend state."""
2
+
3
+ from typing import Any
4
+
5
+ from pydantic import BaseModel
6
+
7
+
8
+ class AgentWalletCapabilities(BaseModel):
9
+ backend: str
10
+ chain: str
11
+ custody_model: str
12
+ sign_only: bool
13
+ has_signer: bool
14
+ can_get_address: bool = True
15
+ can_get_balance: bool = True
16
+ can_sign_message: bool = False
17
+ can_sign_transaction: bool = False
18
+ can_send_transaction: bool = False
19
+ external_dependencies: list[str] = []
20
+
21
+
22
+ class SolanaWalletState(BaseModel):
23
+ chain: str = "solana"
24
+ backend: str
25
+ address: str | None = None
26
+ balance_native: float | None = None
27
+ sign_only: bool = True
28
+ has_signer: bool = False
29
+ source: str = "solana-rpc"
30
+
31
+
32
+ class AgentToolSpec(BaseModel):
33
+ name: str
34
+ description: str
35
+ input_schema: dict[str, Any]
36
+ read_only: bool = True
37
+ requires_explicit_user_intent: bool = False
38
+ risk_level: str = "low"
39
+
40
+
41
+ class AgentToolResult(BaseModel):
42
+ tool: str
43
+ ok: bool
44
+ data: dict[str, Any] | None = None
45
+ error: str | None = None
46
+ error_code: str | None = None
47
+ error_details: dict[str, Any] | None = None
48
+
49
+
50
+ class OpenClawWalletSessionMetadata(BaseModel):
51
+ user_id: str
52
+ chain: str = "solana"
53
+ network: str
54
+ backend: str
55
+ address: str
56
+ wallet_path: str
57
+ storage_format: str
58
+ created_now: bool
59
+ sign_only: bool
60
+ rpc_provider_mode: str | None = None
61
+ rpc_provider: str | None = None
62
+ rpc_transport: str | None = None
63
+ swap_provider: str | None = None
64
+ swap_transport: str | None = None
65
+ tool_names: list[str]
66
+ approval_token_required_for_execute: bool = True
@@ -0,0 +1,298 @@
1
+ """Local state for the Morpho rebalance monitor.
2
+
3
+ The scan itself runs in the EVM wallet daemon; this module only remembers, per
4
+ wallet address, when the last scan ran and which move recommendations it
5
+ returned. That lets every host (Claude Code, Codex, Hermes, OpenClaw) mark a
6
+ recommendation as new or already seen, and tell the agent when a scan is due.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from datetime import datetime, timedelta, timezone
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from .config import resolve_openclaw_home
17
+ from .file_ops import atomic_write_text
18
+
19
+ SCAN_INTERVAL_DAYS = 3
20
+ STATE_VERSION = 1
21
+
22
+
23
+ def state_path() -> Path:
24
+ return resolve_openclaw_home() / "defi_monitor" / "morpho_rebalance.json"
25
+
26
+
27
+ def _now() -> datetime:
28
+ return datetime.now(timezone.utc)
29
+
30
+
31
+ def _load_state(path: Path) -> dict[str, Any]:
32
+ try:
33
+ data = json.loads(path.read_text(encoding="utf-8"))
34
+ except (OSError, ValueError):
35
+ return {"version": STATE_VERSION, "wallets": {}}
36
+ if not isinstance(data, dict) or not isinstance(data.get("wallets"), dict):
37
+ return {"version": STATE_VERSION, "wallets": {}}
38
+ return data
39
+
40
+
41
+ def _wallet_key(address: str | None) -> str:
42
+ return str(address or "").strip().lower()
43
+
44
+
45
+ def _recommendation_key(position: dict[str, Any], candidate: dict[str, Any]) -> str:
46
+ chain_id = position.get("chainId")
47
+ source = str((position.get("current") or {}).get("vault", {}).get("address") or "").lower()
48
+ target = str((candidate.get("vault") or {}).get("address") or "").lower()
49
+ return f"{chain_id}:{source}->{target}"
50
+
51
+
52
+ def _parse_time(value: Any) -> datetime | None:
53
+ if not isinstance(value, str) or not value:
54
+ return None
55
+ try:
56
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
57
+ except ValueError:
58
+ return None
59
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
60
+
61
+
62
+ def scan_status(address: str | None, *, path: Path | None = None, now: datetime | None = None) -> dict[str, Any]:
63
+ """When the last scan ran for this wallet and whether the next one is due."""
64
+ current = now or _now()
65
+ wallet = _load_state(path or state_path())["wallets"].get(_wallet_key(address)) or {}
66
+ last_scan_at = wallet.get("last_scan_at")
67
+ last = _parse_time(last_scan_at)
68
+ due = last is None or current - last >= timedelta(days=SCAN_INTERVAL_DAYS)
69
+ return {
70
+ "last_scan_at": last_scan_at if last else None,
71
+ "scan_due": due,
72
+ "interval_days": SCAN_INTERVAL_DAYS,
73
+ }
74
+
75
+
76
+ def record_report(
77
+ report: dict[str, Any],
78
+ *,
79
+ path: Path | None = None,
80
+ now: datetime | None = None,
81
+ ) -> dict[str, Any]:
82
+ """Mark each candidate `isNew` against the previous scan and persist this scan.
83
+
84
+ A recommendation is new when the previous scan for the same wallet did not
85
+ return the same source -> target move. Network reports that failed are left
86
+ out of the comparison so a transient outage does not resurface old moves.
87
+ """
88
+ target = path or state_path()
89
+ current = now or _now()
90
+ state = _load_state(target)
91
+ key = _wallet_key(report.get("address"))
92
+ previous = state["wallets"].get(key) or {}
93
+ seen = set(previous.get("recommendations") or [])
94
+ keys: list[str] = []
95
+ new_count = 0
96
+ for network_report in report.get("networkReports") or []:
97
+ if network_report.get("error"):
98
+ # Keep the moves we already knew about on that network until it answers again.
99
+ chain_prefix = f"{network_report.get('chainId')}:" if network_report.get("chainId") else None
100
+ if chain_prefix:
101
+ keys.extend(item for item in seen if item.startswith(chain_prefix))
102
+ continue
103
+ for position in network_report.get("positions") or []:
104
+ for candidate in position.get("candidates") or []:
105
+ rec_key = _recommendation_key(position, candidate)
106
+ is_new = rec_key not in seen
107
+ candidate["isNew"] = is_new
108
+ new_count += int(is_new)
109
+ keys.append(rec_key)
110
+ if key:
111
+ state["wallets"][key] = {
112
+ "last_scan_at": current.isoformat().replace("+00:00", "Z"),
113
+ "recommendations": sorted(set(keys)),
114
+ }
115
+ state["version"] = STATE_VERSION
116
+ target.parent.mkdir(parents=True, exist_ok=True)
117
+ atomic_write_text(target, json.dumps(state, indent=2, sort_keys=True))
118
+ return {
119
+ "previous_scan_at": previous.get("last_scan_at"),
120
+ "new_opportunity_count": new_count,
121
+ "next_scan_due_at": (current + timedelta(days=SCAN_INTERVAL_DAYS)).isoformat().replace("+00:00", "Z"),
122
+ "interval_days": SCAN_INTERVAL_DAYS,
123
+ }
124
+
125
+
126
+ JOB_NAME = "agentlayer-morpho-monitor"
127
+ SCHEDULE_HOSTS = ("claude_code", "codex", "openclaw", "hermes")
128
+
129
+ # The one instruction every scheduled run executes, whatever the host. It only reads;
130
+ # moving funds always starts a separate, user-confirmed flow.
131
+ MONITOR_PROMPT = (
132
+ "OneCraft Morpho monitor run (read-only). Call the OneCraft wallet tool "
133
+ "get_morpho_rebalance_report with no arguments. Do not call any wallet write tool in this run. "
134
+ "If monitor.new_opportunity_count is 0, reply with one short line: no new better Morpho vaults "
135
+ "for the wallet, with the number of positions checked. Otherwise, for each position that has a "
136
+ "candidate with isNew true, show the current vault (current rate, 7-day and 30-day averages, "
137
+ "deposits, position size) and each new candidate (7-day and 30-day averages, difference versus "
138
+ "the current vault, reward share, deposits, warnings, young flag); show deposits compactly in USD, "
139
+ "for example $120.7M. "
140
+ "then the estimated migration cost, labelled as an estimate. State plainly that nothing was "
141
+ "moved. End the report with one short sentence offering the best move: the amount and asset, "
142
+ "from which vault to which vault, on which network, and that a preview with the gas estimate "
143
+ "comes first, for example 'Move 1,000 USDC from Steakhouse USDC to Gauntlet USDC Prime on Base? "
144
+ "Say yes and I will show the preview with gas first.' A move uses rebalance_evm_morpho_vault_position, "
145
+ "starting with intent_preview and executing only after the user explicitly confirms."
146
+ )
147
+
148
+
149
+ def schedule_recipe(host: str) -> dict[str, Any]:
150
+ """How to run MONITOR_PROMPT every SCAN_INTERVAL_DAYS on a given agent host."""
151
+ normalized = str(host or "").strip().lower().replace("-", "_")
152
+ if normalized not in SCHEDULE_HOSTS:
153
+ raise ValueError(f"host must be one of: {', '.join(SCHEDULE_HOSTS)}.")
154
+ hours = SCAN_INTERVAL_DAYS * 24
155
+ recipe: dict[str, Any] = {
156
+ "host": normalized,
157
+ "job_name": JOB_NAME,
158
+ "interval_days": SCAN_INTERVAL_DAYS,
159
+ "prompt": MONITOR_PROMPT,
160
+ "requires_user_consent": True,
161
+ "note": (
162
+ "Create the schedule only after the user asks for monitoring. Each run is read-only; "
163
+ "it never moves funds."
164
+ ),
165
+ }
166
+ if normalized == "hermes":
167
+ recipe["method"] = "agent_cron_tool"
168
+ recipe["agent_tool_call"] = {
169
+ "tool": "cronjob",
170
+ "arguments": {
171
+ "action": "create",
172
+ "name": JOB_NAME,
173
+ "schedule": f"every {hours}h",
174
+ "prompt": MONITOR_PROMPT
175
+ + " In Hermes the wallet tools are called through agent_wallet_invoke.",
176
+ "toolsets": ["agent_wallet"],
177
+ },
178
+ }
179
+ recipe["cli_command"] = [
180
+ "hermes", "cron", "create", f"every {hours}h", MONITOR_PROMPT, "--name", JOB_NAME,
181
+ ]
182
+ recipe["delivery"] = "Omitting deliver sends each result back to the chat where the job was created."
183
+ elif normalized == "openclaw":
184
+ recipe["method"] = "agent_cron_tool"
185
+ recipe["agent_tool"] = "cron"
186
+ recipe["job"] = {
187
+ "name": JOB_NAME,
188
+ "every": f"{hours}h",
189
+ "session": "isolated",
190
+ "message": MONITOR_PROMPT,
191
+ "announce": True,
192
+ }
193
+ recipe["cli_command"] = [
194
+ "openclaw", "cron", "add", "--name", JOB_NAME, "--every", f"{hours}h",
195
+ "--session", "isolated", "--message", MONITOR_PROMPT, "--announce",
196
+ ]
197
+ recipe["delivery"] = "--announce delivers the run's final reply to the user's last chat channel."
198
+ elif normalized == "claude_code":
199
+ recipe["method"] = "desktop_scheduled_task"
200
+ recipe["task_prompt"] = "/wallet:yield"
201
+ recipe["user_steps"] = [
202
+ "Open the Claude desktop app and go to Scheduled tasks (Claude Code).",
203
+ f"Create a task named {JOB_NAME} that runs every {SCAN_INTERVAL_DAYS} days in a folder where "
204
+ "the OneCraft wallet plugin is enabled.",
205
+ "Use /wallet:yield as the task prompt.",
206
+ ]
207
+ recipe["delivery"] = "The result appears in the task's session; desktop notifications follow app settings."
208
+ else:
209
+ recipe["method"] = "codex_automation"
210
+ recipe["task_prompt"] = "$yield"
211
+ recipe["user_steps"] = [
212
+ "Open the Codex app and go to Automations.",
213
+ f"Create an automation named {JOB_NAME} that runs every {SCAN_INTERVAL_DAYS} days in a project "
214
+ "where the OneCraft wallet plugin is enabled.",
215
+ "Use $yield as the automation prompt.",
216
+ ]
217
+ recipe["delivery"] = "Each run's result appears in the Codex automations inbox."
218
+ return recipe
219
+
220
+
221
+ # Automatic scan: piggybacks on ordinary read-only wallet calls, at most once per
222
+ # SCAN_INTERVAL_DAYS per wallet, so users with Morpho positions get the check without
223
+ # setting anything up. Disable with AGENT_WALLET_MORPHO_AUTO_SCAN=0.
224
+ AUTO_SCAN_ENV = "AGENT_WALLET_MORPHO_AUTO_SCAN"
225
+ AUTO_SCAN_RETRY_HOURS = 6
226
+ AUTO_SCAN_TIMEOUT_SECONDS = 25
227
+
228
+
229
+ def auto_scan_enabled() -> bool:
230
+ import os
231
+
232
+ return os.getenv(AUTO_SCAN_ENV, "1").strip().lower() not in {"0", "false", "off", "no"}
233
+
234
+
235
+ def auto_scan_due(address: str | None, *, path: Path | None = None, now: datetime | None = None) -> bool:
236
+ if not auto_scan_enabled() or not _wallet_key(address):
237
+ return False
238
+ current = now or _now()
239
+ status = scan_status(address, path=path, now=current)
240
+ if not status["scan_due"]:
241
+ return False
242
+ wallet = _load_state(path or state_path())["wallets"].get(_wallet_key(address)) or {}
243
+ failed = _parse_time(wallet.get("auto_scan_failed_at"))
244
+ return failed is None or current - failed >= timedelta(hours=AUTO_SCAN_RETRY_HOURS)
245
+
246
+
247
+ def record_auto_scan_failure(address: str | None, *, path: Path | None = None, now: datetime | None = None) -> None:
248
+ key = _wallet_key(address)
249
+ if not key:
250
+ return
251
+ target = path or state_path()
252
+ state = _load_state(target)
253
+ wallet = dict(state["wallets"].get(key) or {})
254
+ wallet["auto_scan_failed_at"] = (now or _now()).isoformat().replace("+00:00", "Z")
255
+ state["wallets"][key] = wallet
256
+ state["version"] = STATE_VERSION
257
+ target.parent.mkdir(parents=True, exist_ok=True)
258
+ atomic_write_text(target, json.dumps(state, indent=2, sort_keys=True))
259
+
260
+
261
+ def summarize_new_opportunities(network_reports: list[dict[str, Any]] | None) -> list[dict[str, Any]]:
262
+ """Compact rows for candidates marked isNew by record_report."""
263
+ rows: list[dict[str, Any]] = []
264
+ for network_report in network_reports or []:
265
+ for position in network_report.get("positions") or []:
266
+ current = position.get("current") or {}
267
+ current_vault = current.get("vault") or {}
268
+ for candidate in position.get("candidates") or []:
269
+ if not candidate.get("isNew"):
270
+ continue
271
+ vault = candidate.get("vault") or {}
272
+ rows.append(
273
+ {
274
+ "network": position.get("network") or network_report.get("network"),
275
+ "asset": (current.get("asset") or {}).get("symbol"),
276
+ "position_usd": current.get("assetsUsd"),
277
+ "from_vault": {
278
+ "address": current_vault.get("address"),
279
+ "name": current_vault.get("name"),
280
+ "avg_net_apy_7d": current.get("avgNetApy7d"),
281
+ "avg_net_apy_30d": current.get("avgNetApy30d"),
282
+ "deposits_usd": current.get("depositsUsd"),
283
+ },
284
+ "to_vault": {
285
+ "address": vault.get("address"),
286
+ "name": vault.get("name"),
287
+ "version": vault.get("version"),
288
+ "avg_net_apy_7d": candidate.get("avgNetApy7d"),
289
+ "avg_net_apy_30d": candidate.get("avgNetApy30d"),
290
+ "deposits_usd": candidate.get("depositsUsd"),
291
+ },
292
+ "delta_7d": candidate.get("delta7d"),
293
+ "reward_share_7d": candidate.get("rewardShare7d"),
294
+ "young": candidate.get("young"),
295
+ "warnings": candidate.get("warnings") or [],
296
+ }
297
+ )
298
+ return rows
@@ -0,0 +1,59 @@
1
+ """In-memory nonce registry to prevent approval token replay.
2
+
3
+ Each approval token can be used exactly once. After successful verification,
4
+ the token fingerprint is recorded and any subsequent attempt to reuse it is
5
+ rejected with a clear error.
6
+
7
+ For single-process deployments the in-memory registry is sufficient. For
8
+ multi-instance deployments, swap ``_registry`` for a shared store (Redis,
9
+ SQLite, etc.) behind the same interface.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import threading
16
+ import time
17
+
18
+ from agent_wallet.wallet_layer.base import WalletBackendError
19
+
20
+
21
+ class NonceRegistry:
22
+ """Thread-safe, self-cleaning registry of consumed approval-token fingerprints."""
23
+
24
+ def __init__(self, max_age_seconds: int = 900) -> None:
25
+ self._used: dict[str, float] = {}
26
+ self._lock = threading.Lock()
27
+ self._max_age = max_age_seconds
28
+
29
+ def mark_used(self, token_fingerprint: str) -> None:
30
+ """Record a token as consumed. Raises on duplicate."""
31
+ with self._lock:
32
+ self._cleanup()
33
+ if token_fingerprint in self._used:
34
+ raise WalletBackendError(
35
+ "Approval token has already been used. "
36
+ "Each approval token is single-use — request a new one."
37
+ )
38
+ self._used[token_fingerprint] = time.monotonic()
39
+
40
+ def _cleanup(self) -> None:
41
+ cutoff = time.monotonic() - self._max_age
42
+ expired = [k for k, t in self._used.items() if t < cutoff]
43
+ for k in expired:
44
+ del self._used[k]
45
+
46
+
47
+ # Module-level singleton — shared across the process.
48
+ _registry = NonceRegistry()
49
+
50
+
51
+ def require_single_use(token: str) -> None:
52
+ """Reject reused approval tokens.
53
+
54
+ Computes a SHA-256 fingerprint of the raw token string and checks it
55
+ against the registry. Safe to call from async or sync contexts because
56
+ the registry uses an ordinary ``threading.Lock``.
57
+ """
58
+ fp = hashlib.sha256(token.encode("utf-8")).hexdigest()[:16]
59
+ _registry.mark_used(fp)