@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,910 @@
1
+ """Host-side helpers for binding local EVM wallets to OpenClaw users."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import http.client
6
+ import json
7
+ import os
8
+ import secrets
9
+ import signal
10
+ import socket as socket_module
11
+ import subprocess
12
+ import time
13
+ from pathlib import Path
14
+ from typing import Any
15
+ from urllib.error import URLError
16
+ from urllib.parse import urlparse
17
+ from urllib.request import urlopen
18
+
19
+ from agent_wallet.config import (
20
+ normalize_evm_network,
21
+ resolve_boot_key,
22
+ resolve_evm_wallet_password,
23
+ resolve_openclaw_home,
24
+ resolve_wdk_evm_service_url,
25
+ settings,
26
+ )
27
+ from agent_wallet.file_ops import atomic_write_text
28
+ from agent_wallet.providers.wdk_evm_local import WdkEvmLocalClient
29
+ from agent_wallet.user_wallets import normalize_user_id
30
+ from agent_wallet.wallet_layer.base import WalletBackendError
31
+
32
+ LOCAL_WDK_EVM_HOSTS = {"127.0.0.1", "localhost", "::1"}
33
+ _INSTANCE_ID_FILENAME = "instance-id"
34
+
35
+
36
+ def _normalize_evm_network(value: str | None) -> str:
37
+ return normalize_evm_network(value)
38
+
39
+
40
+ def _resolve_service_url(service_url: str | None = None) -> str:
41
+ effective = (service_url or resolve_wdk_evm_service_url()).strip()
42
+ if not effective:
43
+ raise WalletBackendError("wdk_evm_service_url is required for EVM wallet host operations.")
44
+ return effective
45
+
46
+
47
+ def _paired_network(network: str) -> str | None:
48
+ mapping = {
49
+ "ethereum": "base",
50
+ "base": "ethereum",
51
+ }
52
+ return mapping.get(_normalize_evm_network(network))
53
+
54
+
55
+ class _UnixHealthConnection(http.client.HTTPConnection):
56
+ """Minimal HTTPConnection over AF_UNIX, for the unauthenticated /health probe."""
57
+
58
+ def __init__(self, socket_path: str, timeout: float = 1.5):
59
+ super().__init__("localhost", timeout=timeout)
60
+ self._socket_path = socket_path
61
+
62
+ def connect(self) -> None:
63
+ self.sock = socket_module.socket(socket_module.AF_UNIX, socket_module.SOCK_STREAM)
64
+ self.sock.settimeout(self.timeout)
65
+ self.sock.connect(self._socket_path)
66
+
67
+
68
+ def _health_url(service_url: str) -> str:
69
+ # Display/error-message use only now — unix:// targets are fetched via
70
+ # _UnixHealthConnection below, not urlopen, which has no unix-socket support.
71
+ return f"{service_url.rstrip('/')}/health"
72
+
73
+
74
+ def _service_health(service_url: str) -> dict[str, Any] | None:
75
+ """Return the parsed /health payload, or None if the service is down.
76
+
77
+ An empty dict means the service answered 200 but the body was unparseable —
78
+ treated as "running, version unknown" so we never restart on a parse blip.
79
+ """
80
+ parsed = urlparse(service_url)
81
+ try:
82
+ if parsed.scheme == "unix":
83
+ conn = _UnixHealthConnection(parsed.path, timeout=1.5)
84
+ try:
85
+ conn.request("GET", "/health")
86
+ response = conn.getresponse()
87
+ if response.status != 200:
88
+ return None
89
+ raw = response.read()
90
+ finally:
91
+ conn.close()
92
+ else:
93
+ with urlopen(_health_url(service_url), timeout=1.5) as response:
94
+ if int(getattr(response, "status", 0) or 0) != 200:
95
+ return None
96
+ raw = response.read()
97
+ except (URLError, TimeoutError, OSError, http.client.HTTPException):
98
+ return None
99
+ try:
100
+ payload = json.loads(raw.decode("utf-8"))
101
+ except (ValueError, UnicodeDecodeError):
102
+ return {}
103
+ return payload if isinstance(payload, dict) else {}
104
+
105
+
106
+ def _service_is_healthy(service_url: str) -> bool:
107
+ return _service_health(service_url) is not None
108
+
109
+
110
+ def _read_on_disk_service_version(wallet_root: Path) -> str | None:
111
+ """Version the launcher in wallet_root would report once (re)started."""
112
+ try:
113
+ pkg = json.loads((wallet_root / "package.json").read_text(encoding="utf-8"))
114
+ except (OSError, ValueError):
115
+ return None
116
+ version = str(pkg.get("version") or "").strip()
117
+ return version or None
118
+
119
+
120
+ def _expected_local_service_data_dir() -> Path:
121
+ configured = os.getenv("WDK_EVM_DATA_DIR", "").strip()
122
+ if configured:
123
+ return Path(configured).expanduser().resolve()
124
+ return (resolve_openclaw_home() / "wdk-evm-wallet").resolve()
125
+
126
+
127
+ def _expected_local_service_instance_id() -> str:
128
+ path = _expected_local_service_data_dir() / _INSTANCE_ID_FILENAME
129
+ try:
130
+ existing = path.read_text(encoding="utf-8").strip()
131
+ except OSError:
132
+ existing = ""
133
+ if existing:
134
+ return existing
135
+ generated = secrets.token_hex(16)
136
+ atomic_write_text(path, generated + "\n", mode=0o600)
137
+ return generated
138
+
139
+
140
+ def _should_restart_local_service(
141
+ health: dict[str, Any] | None,
142
+ *,
143
+ wallet_root: Path | None,
144
+ ) -> bool:
145
+ if health is None:
146
+ return False
147
+ expected_version = _read_on_disk_service_version(wallet_root) if wallet_root is not None else None
148
+ running_version = str(health.get("version") or "").strip()
149
+ return bool(expected_version and running_version and running_version != expected_version)
150
+
151
+
152
+ def _daemon_takeover_disabled() -> bool:
153
+ return os.getenv("OPENCLAW_EVM_DISABLE_DAEMON_TAKEOVER", "").strip().lower() in {
154
+ "1",
155
+ "true",
156
+ "yes",
157
+ "on",
158
+ }
159
+
160
+
161
+ def _takeover_refusal(reason: str) -> str:
162
+ return (
163
+ f"Refusing to stop wdk-evm-wallet: {reason}. "
164
+ "To clear it manually: check /health at the configured service URL for its pid, then kill <pid>."
165
+ )
166
+
167
+
168
+ def _process_exists(pid: int) -> bool:
169
+ try:
170
+ os.kill(pid, 0)
171
+ return True
172
+ except ProcessLookupError:
173
+ return False
174
+ except PermissionError:
175
+ return True
176
+
177
+
178
+ def _process_released_service(pid: int, service_url: str) -> bool:
179
+ if not _process_exists(pid):
180
+ return True
181
+ # A daemon signalled by a process other than its parent can remain
182
+ # briefly as a zombie. Once its health endpoint is gone it no longer
183
+ # blocks a fresh daemon from claiming the socket.
184
+ return _service_health(service_url) is None
185
+
186
+
187
+ def _resolve_stoppable_pid(current_health: dict[str, Any]) -> int:
188
+ """Return the daemon's reported PID, or 0 if it didn't report one."""
189
+ try:
190
+ pid = int(current_health.get("pid") or 0)
191
+ except (TypeError, ValueError):
192
+ return 0
193
+ return pid if pid > 0 else 0
194
+
195
+
196
+ def _stop_local_service(service_url: str, health: dict[str, Any] | None = None) -> None:
197
+ """Gracefully stop a local wdk-evm-wallet daemon so a fresh one can start.
198
+
199
+ SIGTERM the listener, wait for /health to drop, then SIGKILL as a fallback.
200
+ """
201
+ port = urlparse(service_url).port or 8081
202
+ current_health = health if health is not None else _service_health(service_url)
203
+ if not current_health or current_health.get("service") != "wdk-evm-wallet":
204
+ raise WalletBackendError(f"Refusing to stop an unidentified service on port {port}.")
205
+
206
+ if _daemon_takeover_disabled():
207
+ raise WalletBackendError(
208
+ _takeover_refusal("takeover is disabled by OPENCLAW_EVM_DISABLE_DAEMON_TAKEOVER")
209
+ )
210
+
211
+ owned_pid = _resolve_stoppable_pid(current_health)
212
+ if owned_pid <= 0:
213
+ raise WalletBackendError(
214
+ _takeover_refusal("the daemon's /health response did not include a pid")
215
+ )
216
+
217
+ try:
218
+ os.kill(owned_pid, 0)
219
+ except ProcessLookupError:
220
+ return
221
+ except PermissionError as exc:
222
+ raise WalletBackendError(
223
+ _takeover_refusal(f"pid {owned_pid} belongs to another user ({exc})")
224
+ ) from exc
225
+
226
+ try:
227
+ os.kill(owned_pid, signal.SIGTERM)
228
+ except ProcessLookupError:
229
+ pass
230
+ except PermissionError as exc:
231
+ raise WalletBackendError(f"Cannot stop stale wdk-evm-wallet (pid {owned_pid}): {exc}.") from exc
232
+
233
+ deadline = time.time() + 10.0
234
+ while time.time() < deadline:
235
+ if _process_released_service(owned_pid, service_url):
236
+ return
237
+ time.sleep(0.3)
238
+
239
+ # Re-check immediately before a hard stop. A PID that exited and was
240
+ # reused must never inherit permission from stale health.
241
+ refreshed_health = _service_health(service_url)
242
+ if (
243
+ not refreshed_health
244
+ or refreshed_health.get("service") != "wdk-evm-wallet"
245
+ or _resolve_stoppable_pid(refreshed_health) != owned_pid
246
+ ):
247
+ raise WalletBackendError(_takeover_refusal("process identity changed before the hard stop"))
248
+
249
+ try:
250
+ os.kill(owned_pid, signal.SIGKILL)
251
+ except ProcessLookupError:
252
+ pass
253
+ deadline = time.time() + 5.0
254
+ while time.time() < deadline:
255
+ if _process_released_service(owned_pid, service_url):
256
+ return
257
+ time.sleep(0.3)
258
+ raise WalletBackendError(f"Failed to stop stale wdk-evm-wallet on port {port}.")
259
+
260
+
261
+ def _is_local_service_url(service_url: str) -> bool:
262
+ parsed = urlparse(service_url)
263
+ if parsed.scheme == "unix":
264
+ # A unix socket is local by construction. Mirrors the same acceptance in
265
+ # scripts/bootstrap_openclaw_evm.py and providers/wdk_evm_local.py; without
266
+ # it _auto_start_local_service refuses the default service URL outright.
267
+ return bool(parsed.path)
268
+ return parsed.scheme in {"http", "https"} and parsed.hostname in LOCAL_WDK_EVM_HOSTS
269
+
270
+
271
+ def _resolve_local_wdk_evm_root() -> Path | None:
272
+ configured = os.getenv("OPENCLAW_EVM_WDK_WALLET_ROOT", "").strip()
273
+ candidates = [configured] if configured else []
274
+ candidates.extend(
275
+ [
276
+ str(Path(__file__).resolve().parents[2] / "wdk-evm-wallet"),
277
+ str(resolve_openclaw_home() / "agent-wallet-runtime" / "current" / "wdk-evm-wallet"),
278
+ ]
279
+ )
280
+ for candidate in candidates:
281
+ root = Path(candidate).expanduser()
282
+ if (root / "run-local.sh").exists():
283
+ return root
284
+ return None
285
+
286
+
287
+ def _auto_start_local_service(service_url: str, network: str) -> None:
288
+ wallet_root = _resolve_local_wdk_evm_root()
289
+ health = _service_health(service_url)
290
+ if health is not None:
291
+ # Already running. The daemon loads code once at boot (no hot-reload), so a
292
+ # long-running process keeps serving stale code after a release. Restart
293
+ # only when the local daemon no longer matches the expected launcher
294
+ # version — its socket path is scoped to this dataDir, so nothing foreign
295
+ # can answer here. Remote (non-local) healthy services we don't manage are
296
+ # left untouched.
297
+ if not _is_local_service_url(service_url):
298
+ return
299
+ if not _should_restart_local_service(health, wallet_root=wallet_root):
300
+ return
301
+ _stop_local_service(service_url, health)
302
+ if not _is_local_service_url(service_url):
303
+ raise WalletBackendError(
304
+ f"wdk-evm-wallet is unreachable at {_health_url(service_url)} and auto-start only supports localhost URLs."
305
+ )
306
+ if wallet_root is None:
307
+ raise WalletBackendError(
308
+ "wdk-evm-wallet is not healthy and the local launcher could not be found."
309
+ )
310
+ parsed = urlparse(service_url)
311
+ env = os.environ.copy()
312
+ if parsed.scheme == "unix":
313
+ env["WDK_EVM_TRANSPORT"] = "socket"
314
+ env["WDK_EVM_SOCKET_PATH"] = parsed.path
315
+ else:
316
+ env["WDK_EVM_TRANSPORT"] = "tcp"
317
+ env["HOST"] = parsed.hostname or "127.0.0.1"
318
+ env["PORT"] = str(parsed.port or 8081)
319
+ env["WDK_EVM_NETWORK"] = _normalize_evm_network(network)
320
+ env["WDK_EVM_INSTANCE_ID"] = _expected_local_service_instance_id()
321
+ process = subprocess.Popen( # noqa: S603
322
+ ["sh", str(wallet_root / "run-local.sh")],
323
+ cwd=str(wallet_root),
324
+ env=env,
325
+ stdin=subprocess.DEVNULL,
326
+ stdout=subprocess.DEVNULL,
327
+ stderr=subprocess.DEVNULL,
328
+ start_new_session=True,
329
+ )
330
+ deadline = time.time() + 30.0
331
+ while time.time() < deadline:
332
+ health = _service_health(service_url)
333
+ if health is not None:
334
+ return
335
+ if process.poll() is not None:
336
+ raise WalletBackendError("wdk-evm-wallet exited before becoming healthy.")
337
+ time.sleep(0.5)
338
+ raise WalletBackendError(
339
+ f"Timed out waiting for wdk-evm-wallet health at {_health_url(service_url)}."
340
+ )
341
+
342
+
343
+ def ensure_local_evm_service_ready(service_url: str, network: str) -> None:
344
+ """Public entry point for callers outside the OpenClaw user-wallet flow.
345
+
346
+ Thin wrapper around `_auto_start_local_service`, which was previously only
347
+ reachable through `ensure_user_evm_wallet_ready`/`resolve_user_evm_wallet_binding`
348
+ (the multi-user OpenClaw gateway/Hermes path). The single-agent factory
349
+ (`wallet_layer.factory.create_wallet_backend`) has no user_id and doesn't
350
+ need one — the underlying ownership/health checks are already keyed off
351
+ `service_url`/`OPENCLAW_HOME`, not the caller's user. Exposing this lets
352
+ both paths share one recovery implementation instead of drifting apart.
353
+
354
+ Raises `WalletBackendError` for anything the auto-start/eviction logic
355
+ can't resolve on its own (e.g. a foreign-home daemon occupying the port);
356
+ callers should let that surface as a clear tool error rather than a raw
357
+ connection failure.
358
+ """
359
+ _auto_start_local_service(service_url, network)
360
+
361
+
362
+ def _resolve_user_evm_wallet_dir(user_id: str) -> Path:
363
+ return resolve_openclaw_home() / "users" / normalize_user_id(user_id) / "wallets"
364
+
365
+
366
+ def resolve_user_evm_wallet_path(user_id: str, network: str | None = None) -> Path:
367
+ effective_network = _normalize_evm_network(network or settings.solana_network)
368
+ user_dir = _resolve_user_evm_wallet_dir(user_id)
369
+ return user_dir / f"evm-{effective_network}-agent.json"
370
+
371
+
372
+ def _write_wallet_binding(path: Path, payload: dict[str, Any]) -> None:
373
+ path.parent.mkdir(parents=True, exist_ok=True)
374
+ path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
375
+
376
+
377
+ def get_user_evm_wallet_binding(user_id: str, network: str | None = None) -> dict[str, Any]:
378
+ path = resolve_user_evm_wallet_path(user_id, network=network)
379
+ if not path.exists():
380
+ raise WalletBackendError(f"EVM wallet binding does not exist yet: {path}")
381
+ payload = json.loads(path.read_text(encoding="utf-8"))
382
+ if not isinstance(payload, dict) or not str(payload.get("wallet_id") or "").strip():
383
+ raise WalletBackendError(f"EVM wallet binding is invalid: {path}")
384
+ return payload
385
+
386
+
387
+ def resolve_user_evm_wallet_binding(
388
+ user_id: str,
389
+ *,
390
+ network: str | None = None,
391
+ service_url: str | None = None,
392
+ wallet_id: str | None = None,
393
+ account_index: int | None = None,
394
+ ) -> dict[str, Any]:
395
+ effective_network = _normalize_evm_network(network or settings.solana_network)
396
+ explicit_wallet_id = str(wallet_id or "").strip()
397
+ if explicit_wallet_id:
398
+ return ensure_user_evm_wallet_binding(
399
+ user_id,
400
+ network=effective_network,
401
+ service_url=service_url,
402
+ wallet_id=explicit_wallet_id,
403
+ account_index=account_index,
404
+ )
405
+ return get_user_evm_wallet_binding(user_id, network=effective_network)
406
+
407
+
408
+ def list_user_evm_wallet_bindings(user_id: str) -> list[dict[str, Any]]:
409
+ user_dir = _resolve_user_evm_wallet_dir(user_id)
410
+ if not user_dir.exists():
411
+ return []
412
+
413
+ bindings: list[dict[str, Any]] = []
414
+ for path in sorted(user_dir.glob("evm-*-agent.json")):
415
+ try:
416
+ payload = json.loads(path.read_text(encoding="utf-8"))
417
+ except Exception:
418
+ continue
419
+ wallet_id = str(payload.get("wallet_id") or "").strip()
420
+ if not wallet_id:
421
+ continue
422
+ bindings.append(payload)
423
+ return bindings
424
+
425
+
426
+ def _maybe_store_evm_wallet_password(password: str) -> bool:
427
+ value = str(password or "").strip()
428
+ if not value:
429
+ return False
430
+ boot_key = resolve_boot_key()
431
+ if not boot_key:
432
+ return False
433
+ from agent_wallet.sealed_keys import resolve_sealed_keys_path, seal_keys, unseal_keys
434
+
435
+ sealed_path = resolve_sealed_keys_path()
436
+ existing = unseal_keys(boot_key) if sealed_path.exists() else {}
437
+ if existing.get("wdk_evm_wallet_password") == value:
438
+ return False
439
+ seal_keys(boot_key, {**existing, "wdk_evm_wallet_password": value})
440
+ return True
441
+
442
+
443
+ def _ensure_evm_wallet_password() -> str:
444
+ existing = resolve_evm_wallet_password()
445
+ if existing:
446
+ return existing
447
+ boot_key = resolve_boot_key()
448
+ if not boot_key:
449
+ return ""
450
+ generated = secrets.token_urlsafe(24)
451
+ _maybe_store_evm_wallet_password(generated)
452
+ return generated
453
+
454
+
455
+ def _bind_network_pair(
456
+ user_id: str,
457
+ *,
458
+ wallet_id: str,
459
+ network: str,
460
+ service_url: str,
461
+ account_index: int,
462
+ address: str | None,
463
+ ) -> None:
464
+ paired = _paired_network(network)
465
+ if not paired:
466
+ return
467
+ bind_user_evm_wallet(
468
+ user_id,
469
+ wallet_id=wallet_id,
470
+ network=paired,
471
+ service_url=service_url,
472
+ account_index=account_index,
473
+ tolerate_locked=True,
474
+ fallback_address=address,
475
+ )
476
+
477
+
478
+ def bind_user_evm_wallet(
479
+ user_id: str,
480
+ *,
481
+ wallet_id: str,
482
+ network: str | None = None,
483
+ service_url: str | None = None,
484
+ account_index: int | None = None,
485
+ tolerate_locked: bool = False,
486
+ fallback_address: str | None = None,
487
+ ) -> dict[str, Any]:
488
+ effective_network = _normalize_evm_network(network or settings.solana_network)
489
+ effective_account_index = settings.wdk_evm_account_index if account_index is None else int(account_index)
490
+ effective_wallet_id = str(wallet_id or "").strip()
491
+ if not effective_wallet_id:
492
+ raise WalletBackendError("wallet_id is required for EVM wallet binding.")
493
+
494
+ client = WdkEvmLocalClient(_resolve_service_url(service_url))
495
+ wallet_meta = client.post_sync("/v1/evm/wallets/get", {"walletId": effective_wallet_id})
496
+ resolved_address = str(fallback_address or "").strip()
497
+ try:
498
+ address = client.post_sync(
499
+ "/v1/evm/address/resolve",
500
+ {
501
+ "walletId": effective_wallet_id,
502
+ "accountIndex": effective_account_index,
503
+ "network": effective_network,
504
+ },
505
+ )
506
+ except WalletBackendError as exc:
507
+ is_locked = exc.code == "wallet_locked" or "wallet is locked" in str(exc).strip().lower()
508
+ if not (tolerate_locked and is_locked):
509
+ raise
510
+ else:
511
+ resolved_address = str(address.get("address") or "").strip()
512
+ binding = {
513
+ "user_id": user_id,
514
+ "wallet_id": effective_wallet_id,
515
+ "label": str(wallet_meta.get("label") or "Agent EVM Wallet"),
516
+ "network": effective_network,
517
+ "account_index": effective_account_index,
518
+ "address": resolved_address,
519
+ "storage_format": "local_vault",
520
+ "service_kind": "wdk-evm-wallet",
521
+ "created_at": wallet_meta.get("createdAt"),
522
+ "updated_at": wallet_meta.get("updatedAt"),
523
+ }
524
+ _write_wallet_binding(resolve_user_evm_wallet_path(user_id, effective_network), binding)
525
+ return binding
526
+
527
+
528
+ def ensure_user_evm_wallet_binding(
529
+ user_id: str,
530
+ *,
531
+ network: str | None = None,
532
+ service_url: str | None = None,
533
+ wallet_id: str | None = None,
534
+ account_index: int | None = None,
535
+ ) -> dict[str, Any]:
536
+ effective_network = _normalize_evm_network(network or settings.solana_network)
537
+ path = resolve_user_evm_wallet_path(user_id, network=effective_network)
538
+ explicit_wallet_id = str(wallet_id or "").strip()
539
+ if path.exists():
540
+ existing = get_user_evm_wallet_binding(user_id, network=effective_network)
541
+ if explicit_wallet_id and str(existing.get("wallet_id") or "").strip() != explicit_wallet_id:
542
+ return bind_user_evm_wallet(
543
+ user_id,
544
+ wallet_id=explicit_wallet_id,
545
+ network=effective_network,
546
+ service_url=service_url,
547
+ account_index=account_index,
548
+ tolerate_locked=True,
549
+ fallback_address=str(existing.get("address") or "").strip() or None,
550
+ )
551
+ return existing
552
+
553
+ if explicit_wallet_id:
554
+ return bind_user_evm_wallet(
555
+ user_id,
556
+ wallet_id=explicit_wallet_id,
557
+ network=effective_network,
558
+ service_url=service_url,
559
+ account_index=account_index,
560
+ tolerate_locked=True,
561
+ )
562
+
563
+ bindings = list_user_evm_wallet_bindings(user_id)
564
+ if not bindings:
565
+ raise WalletBackendError(f"EVM wallet binding does not exist yet: {path}")
566
+
567
+ wallet_ids = {
568
+ str(binding.get("wallet_id") or "").strip()
569
+ for binding in bindings
570
+ if str(binding.get("wallet_id") or "").strip()
571
+ }
572
+ if not wallet_ids:
573
+ raise WalletBackendError(f"EVM wallet binding does not exist yet: {path}")
574
+ if len(wallet_ids) > 1:
575
+ raise WalletBackendError(
576
+ "Multiple EVM wallet bindings exist for this user. Set wdk_evm_wallet_id explicitly to auto-bind a new network."
577
+ )
578
+
579
+ return bind_user_evm_wallet(
580
+ user_id,
581
+ wallet_id=next(iter(wallet_ids)),
582
+ network=effective_network,
583
+ service_url=service_url,
584
+ account_index=account_index,
585
+ )
586
+
587
+
588
+ def ensure_user_evm_wallet_ready(
589
+ user_id: str,
590
+ *,
591
+ network: str | None = None,
592
+ service_url: str | None = None,
593
+ wallet_id: str | None = None,
594
+ account_index: int | None = None,
595
+ auto_start_service: bool = True,
596
+ ) -> dict[str, Any]:
597
+ effective_network = _normalize_evm_network(network or settings.solana_network)
598
+ effective_service_url = _resolve_service_url(service_url)
599
+ effective_account_index = settings.wdk_evm_account_index if account_index is None else int(account_index)
600
+ if auto_start_service:
601
+ _auto_start_local_service(effective_service_url, effective_network)
602
+ elif not _service_is_healthy(effective_service_url):
603
+ raise WalletBackendError(
604
+ f"wdk-evm-wallet is not healthy at {_health_url(effective_service_url)}."
605
+ )
606
+
607
+ client = WdkEvmLocalClient(effective_service_url)
608
+ explicit_wallet_id = str(wallet_id or "").strip()
609
+ binding: dict[str, Any] | None = None
610
+ if explicit_wallet_id:
611
+ binding = ensure_user_evm_wallet_binding(
612
+ user_id,
613
+ network=effective_network,
614
+ service_url=effective_service_url,
615
+ wallet_id=explicit_wallet_id,
616
+ account_index=effective_account_index,
617
+ )
618
+ else:
619
+ try:
620
+ binding = get_user_evm_wallet_binding(user_id, network=effective_network)
621
+ except WalletBackendError:
622
+ binding = None
623
+
624
+ if binding is None:
625
+ existing_bindings = list_user_evm_wallet_bindings(user_id)
626
+ wallet_ids = {
627
+ str(item.get("wallet_id") or "").strip()
628
+ for item in existing_bindings
629
+ if str(item.get("wallet_id") or "").strip()
630
+ }
631
+ if len(wallet_ids) > 1:
632
+ raise WalletBackendError(
633
+ "Multiple EVM wallet bindings exist for this user. Set wdk_evm_wallet_id explicitly to auto-bind a new network."
634
+ )
635
+ if wallet_ids:
636
+ binding = bind_user_evm_wallet(
637
+ user_id,
638
+ wallet_id=next(iter(wallet_ids)),
639
+ network=effective_network,
640
+ service_url=effective_service_url,
641
+ account_index=effective_account_index,
642
+ tolerate_locked=True,
643
+ fallback_address=str(existing_bindings[0].get("address") or "").strip() or None,
644
+ )
645
+ else:
646
+ service_wallets = client.list_wallets_sync()
647
+ service_wallet_ids = {
648
+ str(item.get("walletId") or "").strip()
649
+ for item in service_wallets
650
+ if str(item.get("walletId") or "").strip()
651
+ }
652
+ if len(service_wallet_ids) > 1:
653
+ raise WalletBackendError(
654
+ "Multiple local EVM vault wallets exist. Set wdk_evm_wallet_id explicitly before automatic switching."
655
+ )
656
+ if service_wallet_ids:
657
+ binding = bind_user_evm_wallet(
658
+ user_id,
659
+ wallet_id=next(iter(service_wallet_ids)),
660
+ network=effective_network,
661
+ service_url=effective_service_url,
662
+ account_index=effective_account_index,
663
+ tolerate_locked=True,
664
+ )
665
+ else:
666
+ password = _ensure_evm_wallet_password()
667
+ if not password:
668
+ raise WalletBackendError(
669
+ "EVM wallet is not set up yet and no sealed local EVM wallet password is available for automatic creation."
670
+ )
671
+ created = create_user_evm_wallet(
672
+ user_id,
673
+ password=password,
674
+ network=effective_network,
675
+ service_url=effective_service_url,
676
+ account_index=effective_account_index,
677
+ )
678
+ binding = get_user_evm_wallet_binding(user_id, network=effective_network)
679
+ _bind_network_pair(
680
+ user_id,
681
+ wallet_id=str(created.get("wallet_id") or ""),
682
+ network=effective_network,
683
+ service_url=effective_service_url,
684
+ account_index=effective_account_index,
685
+ address=str(created.get("address") or "").strip() or None,
686
+ )
687
+
688
+ resolved_wallet_id = str(binding.get("wallet_id") or explicit_wallet_id).strip()
689
+ if not resolved_wallet_id:
690
+ raise WalletBackendError("EVM wallet binding is missing wallet_id.")
691
+
692
+ def _resolve_address() -> str:
693
+ payload = client.post_sync(
694
+ "/v1/evm/address/resolve",
695
+ {
696
+ "walletId": resolved_wallet_id,
697
+ "accountIndex": effective_account_index,
698
+ "network": effective_network,
699
+ },
700
+ )
701
+ address = str(payload.get("address") or "").strip()
702
+ if not address:
703
+ raise WalletBackendError("wdk-evm-wallet did not return an address.")
704
+ return address
705
+
706
+ try:
707
+ resolved_address = _resolve_address()
708
+ except WalletBackendError as exc:
709
+ is_locked = exc.code == "wallet_locked" or "wallet is locked" in str(exc).strip().lower()
710
+ if not is_locked:
711
+ raise
712
+ password = resolve_evm_wallet_password()
713
+ if not password:
714
+ raise WalletBackendError(
715
+ "EVM wallet exists but cannot be unlocked automatically because no sealed local EVM wallet password is available."
716
+ ) from exc
717
+ unlock_user_evm_wallet(
718
+ user_id,
719
+ password=password,
720
+ network=effective_network,
721
+ service_url=effective_service_url,
722
+ wallet_id=resolved_wallet_id,
723
+ account_index=effective_account_index,
724
+ )
725
+ resolved_address = _resolve_address()
726
+
727
+ binding = bind_user_evm_wallet(
728
+ user_id,
729
+ wallet_id=resolved_wallet_id,
730
+ network=effective_network,
731
+ service_url=effective_service_url,
732
+ account_index=effective_account_index,
733
+ fallback_address=resolved_address,
734
+ )
735
+ _bind_network_pair(
736
+ user_id,
737
+ wallet_id=resolved_wallet_id,
738
+ network=effective_network,
739
+ service_url=effective_service_url,
740
+ account_index=effective_account_index,
741
+ address=resolved_address,
742
+ )
743
+ return binding
744
+
745
+
746
+ def create_user_evm_wallet(
747
+ user_id: str,
748
+ *,
749
+ password: str,
750
+ label: str | None = None,
751
+ network: str | None = None,
752
+ service_url: str | None = None,
753
+ reveal_seed_phrase: bool = False,
754
+ account_index: int | None = None,
755
+ ) -> dict[str, Any]:
756
+ effective_network = _normalize_evm_network(network or settings.solana_network)
757
+ effective_account_index = settings.wdk_evm_account_index if account_index is None else int(account_index)
758
+ client = WdkEvmLocalClient(_resolve_service_url(service_url))
759
+ created = client.post_sync(
760
+ "/v1/evm/wallets/create",
761
+ {
762
+ "label": (label or "").strip() or "Agent EVM Wallet",
763
+ "password": password,
764
+ "network": effective_network,
765
+ "revealSeedPhrase": bool(reveal_seed_phrase),
766
+ },
767
+ )
768
+ address = client.post_sync(
769
+ "/v1/evm/address/resolve",
770
+ {
771
+ "walletId": created["walletId"],
772
+ "accountIndex": effective_account_index,
773
+ "network": effective_network,
774
+ "password": password,
775
+ },
776
+ )
777
+ binding = {
778
+ "user_id": user_id,
779
+ "wallet_id": str(created["walletId"]),
780
+ "label": str(created.get("label") or "Agent EVM Wallet"),
781
+ "network": effective_network,
782
+ "account_index": effective_account_index,
783
+ "address": str(address.get("address") or ""),
784
+ "storage_format": "local_vault",
785
+ "service_kind": "wdk-evm-wallet",
786
+ "created_at": created.get("createdAt"),
787
+ "updated_at": created.get("updatedAt"),
788
+ }
789
+ _write_wallet_binding(resolve_user_evm_wallet_path(user_id, effective_network), binding)
790
+ _maybe_store_evm_wallet_password(password)
791
+ return {
792
+ **binding,
793
+ "unlocked": bool(created.get("unlocked", True)),
794
+ "unlock_expires_at": created.get("unlockExpiresAt"),
795
+ **({"seed_phrase": created["seedPhrase"]} if created.get("seedPhrase") else {}),
796
+ }
797
+
798
+
799
+ def import_user_evm_wallet(
800
+ user_id: str,
801
+ *,
802
+ password: str,
803
+ seed_phrase: str,
804
+ label: str | None = None,
805
+ network: str | None = None,
806
+ service_url: str | None = None,
807
+ account_index: int | None = None,
808
+ ) -> dict[str, Any]:
809
+ effective_network = _normalize_evm_network(network or settings.solana_network)
810
+ effective_account_index = settings.wdk_evm_account_index if account_index is None else int(account_index)
811
+ client = WdkEvmLocalClient(_resolve_service_url(service_url))
812
+ created = client.post_sync(
813
+ "/v1/evm/wallets/import",
814
+ {
815
+ "label": (label or "").strip() or "Agent EVM Wallet",
816
+ "password": password,
817
+ "seedPhrase": seed_phrase,
818
+ "network": effective_network,
819
+ },
820
+ )
821
+ address = client.post_sync(
822
+ "/v1/evm/address/resolve",
823
+ {
824
+ "walletId": created["walletId"],
825
+ "accountIndex": effective_account_index,
826
+ "network": effective_network,
827
+ "password": password,
828
+ },
829
+ )
830
+ binding = {
831
+ "user_id": user_id,
832
+ "wallet_id": str(created["walletId"]),
833
+ "label": str(created.get("label") or "Agent EVM Wallet"),
834
+ "network": effective_network,
835
+ "account_index": effective_account_index,
836
+ "address": str(address.get("address") or ""),
837
+ "storage_format": "local_vault",
838
+ "service_kind": "wdk-evm-wallet",
839
+ "created_at": created.get("createdAt"),
840
+ "updated_at": created.get("updatedAt"),
841
+ }
842
+ _write_wallet_binding(resolve_user_evm_wallet_path(user_id, effective_network), binding)
843
+ _maybe_store_evm_wallet_password(password)
844
+ return {
845
+ **binding,
846
+ "unlocked": bool(created.get("unlocked", True)),
847
+ "unlock_expires_at": created.get("unlockExpiresAt"),
848
+ }
849
+
850
+
851
+ def unlock_user_evm_wallet(
852
+ user_id: str,
853
+ *,
854
+ password: str,
855
+ network: str | None = None,
856
+ service_url: str | None = None,
857
+ wallet_id: str | None = None,
858
+ account_index: int | None = None,
859
+ ) -> dict[str, Any]:
860
+ binding = resolve_user_evm_wallet_binding(
861
+ user_id,
862
+ network=network,
863
+ service_url=service_url,
864
+ wallet_id=wallet_id,
865
+ account_index=account_index,
866
+ )
867
+ client = WdkEvmLocalClient(_resolve_service_url(service_url))
868
+ payload = client.post_sync(
869
+ "/v1/evm/wallets/unlock",
870
+ {
871
+ "walletId": binding["wallet_id"],
872
+ "password": password,
873
+ "timeoutSeconds": 0,
874
+ },
875
+ )
876
+ _maybe_store_evm_wallet_password(password)
877
+ return {
878
+ **binding,
879
+ "unlocked": bool(payload.get("unlocked", True)),
880
+ "unlock_expires_at": payload.get("unlockExpiresAt"),
881
+ }
882
+
883
+
884
+ def lock_user_evm_wallet(
885
+ user_id: str,
886
+ *,
887
+ network: str | None = None,
888
+ service_url: str | None = None,
889
+ wallet_id: str | None = None,
890
+ account_index: int | None = None,
891
+ ) -> dict[str, Any]:
892
+ binding = resolve_user_evm_wallet_binding(
893
+ user_id,
894
+ network=network,
895
+ service_url=service_url,
896
+ wallet_id=wallet_id,
897
+ account_index=account_index,
898
+ )
899
+ client = WdkEvmLocalClient(_resolve_service_url(service_url))
900
+ payload = client.post_sync(
901
+ "/v1/evm/wallets/lock",
902
+ {
903
+ "walletId": binding["wallet_id"],
904
+ },
905
+ )
906
+ return {
907
+ **binding,
908
+ "unlocked": bool(payload.get("unlocked", False)),
909
+ "unlock_expires_at": None,
910
+ }