@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,2705 @@
1
+ """Local EVM backend backed by the wdk-evm-wallet service."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
6
+ from typing import Any
7
+
8
+ from agent_wallet.config import normalize_evm_network
9
+ from agent_wallet.providers.evm_portfolio import build_portfolio_snapshot
10
+ from agent_wallet.providers.evm_activity import get_activity
11
+ from agent_wallet.exceptions import ProviderError
12
+ from agent_wallet.providers import dexscreener, lifi, tokenized_stocks
13
+ from agent_wallet.providers.wdk_evm_local import WdkEvmLocalClient
14
+ from agent_wallet.wallet_layer.base import AgentWalletBackend, WalletBackendError, WalletCapabilities
15
+
16
+
17
+ def _normalize_evm_network(value: str | None) -> str:
18
+ return normalize_evm_network(value)
19
+
20
+
21
+ def _lifi_chain_id_for_evm_network(network: str) -> str:
22
+ normalized = _normalize_evm_network(network)
23
+ if normalized == "base":
24
+ return "8453"
25
+ if normalized == "arc":
26
+ return "5042"
27
+ return "1"
28
+
29
+
30
+ def _normalize_x402_typed_data_value(value: Any) -> Any:
31
+ if isinstance(value, (bytes, bytearray)):
32
+ return "0x" + bytes(value).hex()
33
+ if isinstance(value, list):
34
+ return [_normalize_x402_typed_data_value(item) for item in value]
35
+ if isinstance(value, dict):
36
+ return {str(key): _normalize_x402_typed_data_value(item) for key, item in value.items()}
37
+ return value
38
+
39
+
40
+ def _extract_fee_wei(payload: dict[str, Any]) -> str | None:
41
+ for key in ("fee", "maxFee", "totalFee", "gasCost", "cost"):
42
+ value = payload.get(key)
43
+ if value is None:
44
+ continue
45
+ text = str(value).strip()
46
+ if text:
47
+ return text
48
+ return None
49
+
50
+
51
+ def _normalize_swap_route(quote: dict[str, Any]) -> Any:
52
+ for key in ("routePlan", "route", "priceRoute"):
53
+ value = quote.get(key)
54
+ if value is not None:
55
+ return value
56
+ return None
57
+
58
+
59
+ def _normalize_token_metadata(payload: Any, token_address: str | None = None) -> dict[str, Any] | None:
60
+ if not isinstance(payload, dict):
61
+ return None
62
+ address = str(payload.get("address") or token_address or "").strip()
63
+ name = payload.get("name")
64
+ symbol = payload.get("symbol")
65
+ decimals = payload.get("decimals")
66
+ normalized: dict[str, Any] = {
67
+ "address": address,
68
+ "name": str(name) if name is not None else None,
69
+ "symbol": str(symbol) if symbol is not None else None,
70
+ "decimals": int(decimals) if decimals is not None else None,
71
+ "verified": bool(payload.get("verified")),
72
+ "source": str(payload.get("source") or "erc20-rpc"),
73
+ }
74
+ return normalized
75
+
76
+
77
+ _BASE_USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
78
+
79
+
80
+ def _filter_pairs_to_chain(pairs: list[dict[str, Any]], chain: str) -> list[dict[str, Any]]:
81
+ return [p for p in pairs if str(p.get("chainId") or "").lower() == chain]
82
+
83
+
84
+ def _pair_has_token(pair: dict[str, Any], address_lower: str) -> bool:
85
+ return any(
86
+ str((pair.get(side) or {}).get("address") or "").lower() == address_lower
87
+ for side in ("baseToken", "quoteToken")
88
+ )
89
+
90
+
91
+ def _first_exact_stock(registry_result: dict[str, Any] | None) -> dict[str, Any] | None:
92
+ for match in (registry_result or {}).get("matches") or []:
93
+ if match.get("exact_match"):
94
+ return match
95
+ return None
96
+
97
+
98
+ def _normalize_swap_allowance(payload: Any) -> dict[str, Any] | None:
99
+ if not isinstance(payload, dict):
100
+ return None
101
+ return {
102
+ "spender": str(payload.get("spender") or "").strip() or None,
103
+ "current_allowance_raw": str(payload.get("currentAllowance") or "0"),
104
+ "required_allowance_raw": str(payload.get("requiredAllowance") or "0"),
105
+ "approval_required": bool(payload.get("approvalRequired")),
106
+ "approval_sequence": list(payload.get("approvalSequence") or []),
107
+ }
108
+
109
+
110
+ def _normalize_swap_simulation(payload: Any) -> dict[str, Any] | None:
111
+ if not isinstance(payload, dict):
112
+ return None
113
+ return {
114
+ "ok": payload.get("ok"),
115
+ "skipped": bool(payload.get("skipped")),
116
+ "reason": str(payload.get("reason") or "").strip() or None,
117
+ "message": str(payload.get("message") or "").strip() or None,
118
+ "details": dict(payload.get("details") or {}) if isinstance(payload.get("details"), dict) else None,
119
+ }
120
+
121
+
122
+ def _normalize_aave_operation(value: str) -> str:
123
+ operation = str(value or "").strip().lower()
124
+ if operation not in {"supply", "withdraw", "borrow", "repay"}:
125
+ raise WalletBackendError("Aave operation must be one of: supply, withdraw, borrow, repay.")
126
+ return operation
127
+
128
+
129
+ def _normalize_lido_operation(value: str) -> str:
130
+ operation = str(value or "").strip().lower()
131
+ if operation not in {"stake_eth_for_wsteth", "wrap_steth", "unwrap_wsteth"}:
132
+ raise WalletBackendError(
133
+ "Lido operation must be one of: stake_eth_for_wsteth, wrap_steth, unwrap_wsteth."
134
+ )
135
+ return operation
136
+
137
+
138
+ def _normalize_lido_withdrawal_operation(value: str) -> str:
139
+ operation = str(value or "").strip().lower()
140
+ if operation not in {"request_withdrawal_steth", "request_withdrawal_wsteth", "claim_withdrawal"}:
141
+ raise WalletBackendError(
142
+ "Lido withdrawal operation must be one of: request_withdrawal_steth, request_withdrawal_wsteth, claim_withdrawal."
143
+ )
144
+ return operation
145
+
146
+
147
+ def _normalize_morpho_vault_operation(value: str) -> str:
148
+ operation = str(value or "").strip().lower()
149
+ if operation not in {"supply", "withdraw"}:
150
+ raise WalletBackendError("Morpho vault operation must be one of: supply, withdraw.")
151
+ return operation
152
+
153
+
154
+ def _normalize_morpho_market_operation(value: str) -> str:
155
+ operation = str(value or "").strip().lower()
156
+ if operation not in {"supply_collateral", "borrow", "repay", "withdraw_collateral"}:
157
+ raise WalletBackendError(
158
+ "Morpho market operation must be one of: supply_collateral, borrow, repay, withdraw_collateral."
159
+ )
160
+ return operation
161
+
162
+
163
+ def _normalize_aave_payload(
164
+ *,
165
+ chain: str,
166
+ network: str,
167
+ wallet_id: str,
168
+ address: str,
169
+ operation: str,
170
+ token_address: str,
171
+ amount_raw: str,
172
+ data: dict[str, Any],
173
+ sign_only: bool,
174
+ ) -> dict[str, Any]:
175
+ result = dict(data.get("result") or {})
176
+ request = dict(data.get("operationRequest") or {})
177
+ token = str(request.get("token") or token_address)
178
+ amount = str(request.get("amount") or amount_raw)
179
+ return {
180
+ "chain": chain,
181
+ "network": network,
182
+ "asset_type": "evm-aave-v3",
183
+ "asset": "ERC20",
184
+ "wallet": wallet_id,
185
+ "from_address": str(data.get("address") or address),
186
+ "protocol": str(data.get("protocol") or "aave-v3"),
187
+ "operation": str(data.get("operation") or operation),
188
+ "token_address": token,
189
+ "amount_raw": amount,
190
+ "amount_ui": str(data.get("amountFormatted")) if data.get("amountFormatted") is not None else None,
191
+ "estimated_fee_wei": str(data.get("estimatedFeeWei")) if data.get("estimatedFeeWei") is not None else None,
192
+ "estimated_operation_fee_wei": (
193
+ str(data.get("estimatedOperationFeeWei"))
194
+ if data.get("estimatedOperationFeeWei") is not None
195
+ else None
196
+ ),
197
+ "estimated_approval_fee_wei": str(data.get("estimatedApprovalFeeWei") or "0"),
198
+ "fee_estimate_available": bool(data.get("feeEstimateAvailable", True)),
199
+ "fee_estimate_error": data.get("feeEstimateError"),
200
+ "execution_supported": not sign_only,
201
+ "quote_fingerprint": str(data.get("quoteFingerprint") or "").strip() or None,
202
+ "allowance": _normalize_swap_allowance(data.get("allowance")),
203
+ "token_metadata": _normalize_token_metadata(data.get("tokenMetadata"), token),
204
+ "hash": result.get("hash"),
205
+ "approve_hash": result.get("approveHash"),
206
+ "reset_allowance_hash": result.get("resetAllowanceHash"),
207
+ "result": result,
208
+ "chain_id": int(data.get("chainId") or 0),
209
+ "source": "wdk-evm-wallet",
210
+ }
211
+
212
+
213
+ def _normalize_lido_payload(
214
+ *,
215
+ chain: str,
216
+ network: str,
217
+ wallet_id: str,
218
+ address: str,
219
+ operation: str,
220
+ amount_raw: str,
221
+ data: dict[str, Any],
222
+ sign_only: bool,
223
+ ) -> dict[str, Any]:
224
+ result = dict(data.get("result") or {})
225
+ request = dict(data.get("operationRequest") or {})
226
+ amount = str(request.get("amount") or amount_raw)
227
+ return {
228
+ "chain": chain,
229
+ "network": network,
230
+ "asset_type": "evm-lido-staking",
231
+ "asset": "ETH",
232
+ "wallet": wallet_id,
233
+ "from_address": str(data.get("address") or address),
234
+ "protocol": str(data.get("protocol") or "lido"),
235
+ "operation": str(data.get("operation") or operation),
236
+ "amount_raw": amount,
237
+ "amount_ui": str(data.get("amountFormatted")) if data.get("amountFormatted") is not None else None,
238
+ "expected_output_amount_raw": str(data.get("expectedOutputAmountRaw") or "0"),
239
+ "expected_output_amount_ui": (
240
+ str(data.get("expectedOutputAmountFormatted"))
241
+ if data.get("expectedOutputAmountFormatted") is not None
242
+ else None
243
+ ),
244
+ "estimated_fee_wei": str(data.get("estimatedFeeWei")) if data.get("estimatedFeeWei") is not None else None,
245
+ "estimated_operation_fee_wei": (
246
+ str(data.get("estimatedOperationFeeWei"))
247
+ if data.get("estimatedOperationFeeWei") is not None
248
+ else None
249
+ ),
250
+ "estimated_approval_fee_wei": str(data.get("estimatedApprovalFeeWei") or "0"),
251
+ "fee_estimate_available": bool(data.get("feeEstimateAvailable", True)),
252
+ "fee_estimate_error": data.get("feeEstimateError"),
253
+ "execution_supported": not sign_only,
254
+ "quote_fingerprint": str(data.get("quoteFingerprint") or "").strip() or None,
255
+ "allowance": _normalize_swap_allowance(data.get("allowance")),
256
+ "input_asset": _normalize_token_metadata(data.get("inputAsset")),
257
+ "output_asset": _normalize_token_metadata(data.get("outputAsset")),
258
+ "contracts": dict(data.get("contracts") or {}),
259
+ "referral_address": str(data.get("referralAddress") or "").strip() or None,
260
+ "simulation": _normalize_swap_simulation(data.get("simulation")),
261
+ "hash": result.get("hash"),
262
+ "approve_hash": result.get("approveHash"),
263
+ "reset_allowance_hash": result.get("resetAllowanceHash"),
264
+ "result": result,
265
+ "chain_id": int(data.get("chainId") or 0),
266
+ "source": "wdk-evm-wallet",
267
+ }
268
+
269
+
270
+ def _normalize_lido_withdrawal_payload(
271
+ *,
272
+ chain: str,
273
+ network: str,
274
+ wallet_id: str,
275
+ address: str,
276
+ operation: str,
277
+ amount_raw: str | None,
278
+ request_id: str | None,
279
+ data: dict[str, Any],
280
+ sign_only: bool,
281
+ ) -> dict[str, Any]:
282
+ result = dict(data.get("result") or {})
283
+ request = dict(data.get("operationRequest") or {})
284
+ resolved_amount = (
285
+ str(request.get("amount"))
286
+ if request.get("amount") is not None
287
+ else (str(amount_raw) if amount_raw is not None else None)
288
+ )
289
+ resolved_request_id = (
290
+ str(request.get("requestId"))
291
+ if request.get("requestId") is not None
292
+ else (str(request_id) if request_id is not None else None)
293
+ )
294
+ return {
295
+ "chain": chain,
296
+ "network": network,
297
+ "asset_type": "evm-lido-withdrawal-queue",
298
+ "asset": "ETH",
299
+ "wallet": wallet_id,
300
+ "from_address": str(data.get("address") or address),
301
+ "protocol": str(data.get("protocol") or "lido"),
302
+ "operation": str(data.get("operation") or operation),
303
+ "amount_raw": resolved_amount,
304
+ "amount_ui": str(data.get("amountFormatted")) if data.get("amountFormatted") is not None else None,
305
+ "request_id": resolved_request_id,
306
+ "queued_steth_amount_raw": (
307
+ str(data.get("queuedStEthAmountRaw")) if data.get("queuedStEthAmountRaw") is not None else None
308
+ ),
309
+ "queued_steth_amount_ui": (
310
+ str(data.get("queuedStEthAmountFormatted"))
311
+ if data.get("queuedStEthAmountFormatted") is not None
312
+ else None
313
+ ),
314
+ "estimated_fee_wei": str(data.get("estimatedFeeWei")) if data.get("estimatedFeeWei") is not None else None,
315
+ "estimated_operation_fee_wei": (
316
+ str(data.get("estimatedOperationFeeWei"))
317
+ if data.get("estimatedOperationFeeWei") is not None
318
+ else None
319
+ ),
320
+ "estimated_approval_fee_wei": str(data.get("estimatedApprovalFeeWei") or "0"),
321
+ "fee_estimate_available": bool(data.get("feeEstimateAvailable", True)),
322
+ "fee_estimate_error": data.get("feeEstimateError"),
323
+ "execution_supported": not sign_only,
324
+ "quote_fingerprint": str(data.get("quoteFingerprint") or "").strip() or None,
325
+ "allowance": _normalize_swap_allowance(data.get("allowance")),
326
+ "input_asset": _normalize_token_metadata(data.get("inputAsset")),
327
+ "queue_asset": _normalize_token_metadata(data.get("queueAsset")),
328
+ "withdrawal_queue": str(data.get("withdrawalQueue") or "").strip() or None,
329
+ "withdrawal_request": dict(data.get("withdrawalRequest") or {}),
330
+ "simulation": _normalize_swap_simulation(data.get("simulation")),
331
+ "hash": result.get("hash"),
332
+ "approve_hash": result.get("approveHash"),
333
+ "reset_allowance_hash": result.get("resetAllowanceHash"),
334
+ "result": result,
335
+ "chain_id": int(data.get("chainId") or 0),
336
+ "source": "wdk-evm-wallet",
337
+ }
338
+
339
+
340
+ def _normalize_morpho_payload(
341
+ *,
342
+ chain: str,
343
+ network: str,
344
+ wallet_id: str,
345
+ address: str,
346
+ operation: str,
347
+ token_address: str,
348
+ amount_raw: str | None,
349
+ native_amount_raw: str | None,
350
+ data: dict[str, Any],
351
+ sign_only: bool,
352
+ ) -> dict[str, Any]:
353
+ result = dict(data.get("result") or {})
354
+ request = dict(data.get("operationRequest") or {})
355
+ requirements = dict(data.get("requirements") or {})
356
+ resolved_amount = (
357
+ str(request.get("amount"))
358
+ if request.get("amount") is not None
359
+ else (str(amount_raw) if amount_raw is not None else None)
360
+ )
361
+ resolved_native_amount = (
362
+ str(request.get("nativeAmount"))
363
+ if request.get("nativeAmount") is not None
364
+ else (str(native_amount_raw) if native_amount_raw is not None else None)
365
+ )
366
+ target = dict(data.get("target") or {})
367
+ surface = str(data.get("surface") or target.get("type") or "").strip().lower() or None
368
+ asset_type = "evm-morpho-vault" if surface == "vault" else "evm-morpho-market"
369
+ return {
370
+ "chain": chain,
371
+ "network": network,
372
+ "asset_type": asset_type,
373
+ "asset": "ERC20",
374
+ "wallet": wallet_id,
375
+ "from_address": str(data.get("address") or address),
376
+ "protocol": str(data.get("protocol") or "morpho"),
377
+ "surface": surface,
378
+ "operation": str(data.get("operation") or operation),
379
+ "target": target,
380
+ "token_address": str(request.get("token") or token_address),
381
+ "amount_raw": resolved_amount,
382
+ "native_amount_raw": resolved_native_amount,
383
+ "amount_ui": str(data.get("amountFormatted")) if data.get("amountFormatted") is not None else None,
384
+ "native_amount_ui": (
385
+ str(data.get("nativeAmountFormatted"))
386
+ if data.get("nativeAmountFormatted") is not None
387
+ else None
388
+ ),
389
+ "estimated_fee_wei": str(data.get("estimatedFeeWei")) if data.get("estimatedFeeWei") is not None else None,
390
+ "estimated_operation_fee_wei": (
391
+ str(data.get("estimatedOperationFeeWei"))
392
+ if data.get("estimatedOperationFeeWei") is not None
393
+ else None
394
+ ),
395
+ "estimated_requirements_fee_wei": (
396
+ str(data.get("estimatedRequirementsFeeWei"))
397
+ if data.get("estimatedRequirementsFeeWei") is not None
398
+ else None
399
+ ),
400
+ "fee_estimate_available": bool(data.get("feeEstimateAvailable", True)),
401
+ "fee_estimate_error": data.get("feeEstimateError"),
402
+ "execution_supported": bool(data.get("executionSupported", True)) and not sign_only,
403
+ "quote_fingerprint": str(data.get("quoteFingerprint") or "").strip() or None,
404
+ "requirements": {
405
+ "required": bool(requirements.get("required")),
406
+ "requirement_count": int(requirements.get("requirementCount") or 0),
407
+ "approval_required": bool(requirements.get("approvalRequired")),
408
+ "authorization_required": bool(requirements.get("authorizationRequired")),
409
+ "sequence": list(requirements.get("sequence") or []),
410
+ },
411
+ "token_metadata": _normalize_token_metadata(
412
+ data.get("tokenMetadata"),
413
+ str(request.get("token") or token_address),
414
+ ),
415
+ "hash": result.get("hash"),
416
+ "result": result,
417
+ "chain_id": int(data.get("chainId") or 0),
418
+ "source": "wdk-evm-wallet",
419
+ }
420
+
421
+
422
+ def _normalize_lifi_cross_chain_payload(
423
+ *,
424
+ chain: str,
425
+ network: str,
426
+ wallet_id: str,
427
+ data: dict[str, Any],
428
+ token_in: str,
429
+ destination_chain: str,
430
+ output_token: str,
431
+ destination_address: str,
432
+ amount_in_raw: str,
433
+ slippage: float | int | None,
434
+ sign_only: bool,
435
+ ) -> dict[str, Any]:
436
+ quote = dict(data.get("quote") or {})
437
+ estimate = dict(quote.get("estimate") or {})
438
+ return {
439
+ "chain": chain,
440
+ "network": network,
441
+ "asset_type": "evm-lifi-cross-chain-swap",
442
+ "asset": "EVM",
443
+ "wallet": wallet_id,
444
+ "from_address": str(data.get("address") or ""),
445
+ "source_chain": str(data.get("sourceChain") or network),
446
+ "destination_chain": str(destination_chain or data.get("destinationChain")),
447
+ "destination_chain_id": str(data.get("destinationChainId") or destination_chain),
448
+ "token_in": str((data.get("swapRequest") or {}).get("tokenIn") or token_in),
449
+ "output_token": str((data.get("swapRequest") or {}).get("outputToken") or output_token),
450
+ "destination_address": str(
451
+ (data.get("swapRequest") or {}).get("destinationAddress") or destination_address
452
+ ),
453
+ "input_amount_raw": str((data.get("swapRequest") or {}).get("tokenInAmount") or amount_in_raw),
454
+ "input_amount_ui": str(data.get("inputAmountFormatted")) if data.get("inputAmountFormatted") is not None else None,
455
+ "estimated_output_amount_raw": str(estimate.get("toAmount") or data.get("minimumOutputAmountRaw") or "0"),
456
+ "estimated_output_amount_ui": (
457
+ str(data.get("outputAmountFormatted")) if data.get("outputAmountFormatted") is not None else None
458
+ ),
459
+ "estimated_fee_wei": str(data.get("estimatedFeeWei")) if data.get("estimatedFeeWei") is not None else None,
460
+ "estimated_swap_fee_wei": str(data.get("estimatedSwapFeeWei")) if data.get("estimatedSwapFeeWei") is not None else None,
461
+ "estimated_approval_fee_wei": str(data.get("estimatedApprovalFeeWei") or "0"),
462
+ "fee_estimate_available": bool(data.get("feeEstimateAvailable", True)),
463
+ "fee_estimate_error": data.get("feeEstimateError"),
464
+ "slippage": data.get("slippage") if data.get("slippage") is not None else slippage,
465
+ "minimum_output_amount_raw": str(data.get("minimumOutputAmountRaw") or estimate.get("toAmountMin") or "0"),
466
+ "swap_provider": str(data.get("protocol") or "lifi"),
467
+ "execution_supported": bool(data.get("executionSupported")) and not sign_only,
468
+ "route_plan": quote,
469
+ "quote_fingerprint": str(data.get("quoteFingerprint") or "").strip() or None,
470
+ "router": str(data.get("router") or "").strip() or None,
471
+ "quote_type": str(data.get("quoteType") or quote.get("type") or "").strip() or None,
472
+ "quote_id": str(data.get("quoteId") or quote.get("id") or "").strip() or None,
473
+ "tool": str(data.get("tool") or quote.get("tool") or "").strip() or None,
474
+ "tool_details": data.get("toolDetails") or quote.get("toolDetails"),
475
+ "allowance": _normalize_swap_allowance(data.get("allowance")),
476
+ "simulation": _normalize_swap_simulation(data.get("simulation")),
477
+ "swap_transaction": {
478
+ "to": str((data.get("swapTransaction") or {}).get("to") or "").strip() or None,
479
+ "value": str((data.get("swapTransaction") or {}).get("value") or "0"),
480
+ "data_hash": str((data.get("swapTransaction") or {}).get("dataHash") or "").strip() or None,
481
+ },
482
+ "token_in_metadata": _normalize_token_metadata(
483
+ data.get("tokenInMetadata"),
484
+ str((data.get("swapRequest") or {}).get("tokenIn") or token_in),
485
+ ),
486
+ "output_token_metadata": _normalize_token_metadata(
487
+ data.get("outputTokenMetadata"),
488
+ str((data.get("swapRequest") or {}).get("outputToken") or output_token),
489
+ ),
490
+ "quote": quote,
491
+ "chain_id": int(data.get("chainId") or 0),
492
+ "source": "wdk-evm-wallet",
493
+ }
494
+
495
+
496
+ def _sanitize_provider_url(value: Any) -> str | None:
497
+ raw = str(value or "").strip()
498
+ if not raw:
499
+ return None
500
+ try:
501
+ split = urlsplit(raw)
502
+ except Exception:
503
+ return raw
504
+ query = []
505
+ for key, item in parse_qsl(split.query, keep_blank_values=True):
506
+ if key.lower() in {"token", "apikey", "api_key"}:
507
+ query.append((key, "***"))
508
+ else:
509
+ query.append((key, item))
510
+ return urlunsplit((split.scheme, split.netloc, split.path, urlencode(query), split.fragment))
511
+
512
+
513
+ class WdkEvmLocalWalletBackend(AgentWalletBackend):
514
+ """EVM backend that delegates signing and execution to a local WDK service."""
515
+
516
+ name = "wdk_evm_local"
517
+
518
+ def __init__(
519
+ self,
520
+ *,
521
+ service_url: str,
522
+ wallet_id: str,
523
+ network: str,
524
+ account_index: int = 0,
525
+ sign_only: bool = False,
526
+ address: str | None = None,
527
+ ):
528
+ self.client = WdkEvmLocalClient(service_url)
529
+ self.wallet_id = str(wallet_id or "").strip()
530
+ if not self.wallet_id:
531
+ raise WalletBackendError("WDK EVM wallet id is not configured.")
532
+ self.network = _normalize_evm_network(network)
533
+ self.account_index = int(account_index)
534
+ self.sign_only = bool(sign_only)
535
+ self.address = address.strip() if isinstance(address, str) and address.strip() else None
536
+ self.chain = "evm"
537
+ self.custody_model = "local_service_vault"
538
+
539
+ def with_network(self, network: str) -> "WdkEvmLocalWalletBackend":
540
+ return WdkEvmLocalWalletBackend(
541
+ service_url=self.client.base_url,
542
+ wallet_id=self.wallet_id,
543
+ network=_normalize_evm_network(network),
544
+ account_index=self.account_index,
545
+ sign_only=self.sign_only,
546
+ address=self.address,
547
+ )
548
+
549
+ async def get_address(self) -> str | None:
550
+ if self.address:
551
+ return self.address
552
+ data = await self.client.post(
553
+ "/v1/evm/address/resolve",
554
+ {
555
+ "walletId": self.wallet_id,
556
+ "accountIndex": self.account_index,
557
+ "network": self.network,
558
+ },
559
+ )
560
+ address = str(data.get("address") or "").strip()
561
+ if not address:
562
+ raise WalletBackendError("wdk-evm-wallet did not return an address.")
563
+ self.address = address
564
+ return address
565
+
566
+ def sign_x402_evm_exact_typed_data(
567
+ self,
568
+ *,
569
+ domain: dict[str, Any],
570
+ types: dict[str, Any],
571
+ primary_type: str,
572
+ message: dict[str, Any],
573
+ ) -> bytes:
574
+ data = self.client.post_sync(
575
+ "/v1/evm/x402/exact/sign",
576
+ {
577
+ "walletId": self.wallet_id,
578
+ "accountIndex": self.account_index,
579
+ "network": self.network,
580
+ "domain": domain,
581
+ "types": types,
582
+ "primaryType": primary_type,
583
+ "message": _normalize_x402_typed_data_value(message),
584
+ },
585
+ )
586
+ signature = str(data.get("signature") or "").strip()
587
+ if not signature:
588
+ raise WalletBackendError("wdk-evm-wallet did not return an x402 EVM signature.")
589
+ if signature.startswith("0x"):
590
+ signature = signature[2:]
591
+ try:
592
+ return bytes.fromhex(signature)
593
+ except ValueError as exc:
594
+ raise WalletBackendError("wdk-evm-wallet returned an invalid x402 EVM signature.") from exc
595
+
596
+ async def _imd_post(self, path: str, extra: dict[str, Any]) -> dict[str, Any]:
597
+ return await self.client.post(
598
+ path,
599
+ {
600
+ "walletId": self.wallet_id,
601
+ "accountIndex": self.account_index,
602
+ "network": self.network,
603
+ **extra,
604
+ },
605
+ )
606
+
607
+ async def get_imd_account_state(self) -> dict[str, Any]:
608
+ return await self._imd_post("/v1/evm/imd/state", {})
609
+
610
+ async def sign_imd_permit2(self, permit: dict[str, Any]) -> dict[str, Any]:
611
+ data = await self._imd_post("/v1/evm/imd/permit2/sign", {"permit": permit})
612
+ if not str(data.get("signature") or "").startswith("0x"):
613
+ raise WalletBackendError("wdk-evm-wallet did not return an IMD Permit2 signature.")
614
+ return data
615
+
616
+ async def sign_imd_quote_approval(self, quote_approval: dict[str, Any]) -> dict[str, Any]:
617
+ data = await self._imd_post("/v1/evm/imd/quote-approval/sign", {"quoteApproval": quote_approval})
618
+ if not str(data.get("signature") or "").startswith("0x"):
619
+ raise WalletBackendError("wdk-evm-wallet did not return an IMD quote approval signature.")
620
+ return data
621
+
622
+ async def quote_imd_permit2_approval(self, amount_raw: str) -> dict[str, Any]:
623
+ return await self._imd_post("/v1/evm/imd/approve/quote", {"amount": str(amount_raw)})
624
+
625
+ async def approve_imd_for_permit2(self, amount_raw: str) -> dict[str, Any]:
626
+ return await self._imd_post("/v1/evm/imd/approve/send", {"amount": str(amount_raw)})
627
+
628
+ async def sign_message(self, message: bytes | str) -> str:
629
+ text = message.decode("utf-8") if isinstance(message, bytes) else str(message)
630
+ if not text:
631
+ raise WalletBackendError("message must be a non-empty string.")
632
+ data = await self.client.post(
633
+ "/v1/evm/message/sign",
634
+ {
635
+ "walletId": self.wallet_id,
636
+ "accountIndex": self.account_index,
637
+ "network": self.network,
638
+ "message": text,
639
+ },
640
+ )
641
+ signature = str(data.get("signature") or "").strip()
642
+ if not signature:
643
+ raise WalletBackendError("wdk-evm-wallet did not return a message signature.")
644
+ return signature
645
+
646
+ async def get_balance(self, address: str | None = None) -> dict[str, Any]:
647
+ resolved_address = await self.get_address()
648
+ if address is not None and address.strip() and address.strip() != resolved_address:
649
+ raise WalletBackendError(
650
+ "wdk_evm_local only supports the configured default EVM account address."
651
+ )
652
+ data = await self.client.post(
653
+ "/v1/evm/balance/get",
654
+ {
655
+ "walletId": self.wallet_id,
656
+ "address": resolved_address,
657
+ "accountIndex": self.account_index,
658
+ "network": self.network,
659
+ },
660
+ )
661
+ result = {
662
+ "chain": self.chain,
663
+ "network": self.network,
664
+ "address": str(data.get("address") or resolved_address or ""),
665
+ "balance_wei": str(data.get("balance") or "0"),
666
+ "balance_native": str(data.get("balanceFormatted") or "0"),
667
+ "asset": str(data.get("nativeSymbol") or "ETH"),
668
+ "chain_id": int(data.get("chainId") or 0),
669
+ "source": "wdk-evm-wallet",
670
+ }
671
+ try:
672
+ portfolio = await build_portfolio_snapshot(
673
+ address=result["address"],
674
+ network=self.network,
675
+ native_symbol=result["asset"],
676
+ native_balance_wei=result["balance_wei"],
677
+ native_balance=result["balance_native"],
678
+ )
679
+ except Exception as exc:
680
+ result["portfolio_error"] = str(exc)
681
+ result["tokens"] = []
682
+ result["token_count"] = 0
683
+ result["assets"] = [
684
+ {
685
+ "asset_type": "native",
686
+ "symbol": result["asset"],
687
+ "amount_raw": result["balance_wei"],
688
+ "amount_ui": result["balance_native"],
689
+ "price_usd": None,
690
+ "value_usd": None,
691
+ "pricing_source": None,
692
+ }
693
+ ]
694
+ result["asset_count"] = 1
695
+ result["priced_asset_count"] = 0
696
+ result["balance_usd"] = None
697
+ result["total_value_usd"] = None
698
+ result["native_price_usd"] = None
699
+ result["native_value_usd"] = None
700
+ return result
701
+
702
+ result.update(
703
+ {
704
+ "native_price_usd": portfolio.get("native_price_usd"),
705
+ "native_value_usd": portfolio.get("native_value_usd"),
706
+ "tokens": list(portfolio.get("tokens") or []),
707
+ "token_count": int(portfolio.get("token_count") or 0),
708
+ "assets": list(portfolio.get("assets") or []),
709
+ "asset_count": int(portfolio.get("asset_count") or 0),
710
+ "priced_asset_count": int(portfolio.get("priced_asset_count") or 0),
711
+ "balance_usd": portfolio.get("balance_usd"),
712
+ "total_value_usd": portfolio.get("total_value_usd"),
713
+ "pricing_source": portfolio.get("pricing_source"),
714
+ "token_discovery_source": portfolio.get("token_discovery_source"),
715
+ }
716
+ )
717
+ return result
718
+
719
+ async def get_transaction_activity(
720
+ self, *, page_size: int = 20, direction: str = "both", include_nfts: bool = False,
721
+ outgoing_page_key: str = "", incoming_page_key: str = "",
722
+ ) -> dict[str, Any]:
723
+ address = await self.get_address()
724
+ if not address:
725
+ raise WalletBackendError("No active EVM wallet address is configured.")
726
+ return await get_activity(
727
+ self.network, address, page_size=page_size, direction=direction, include_nfts=include_nfts,
728
+ outgoing_page_key=outgoing_page_key, incoming_page_key=incoming_page_key,
729
+ receipt_lookup=self.get_evm_transaction_receipt,
730
+ )
731
+
732
+ async def get_evm_network_info(self) -> dict[str, Any]:
733
+ data = await self.client.get("/v1/evm/network")
734
+ profiles = data.get("profiles") or {}
735
+ return {
736
+ "chain": self.chain,
737
+ "network": self.network,
738
+ "configured_network": self.network,
739
+ "service_active_network": str(data.get("activeNetwork") or "").strip() or None,
740
+ "available_networks": sorted(str(key) for key in profiles.keys()),
741
+ "agent_selectable_networks": ["ethereum", "base", "robinhood", "arc"],
742
+ "swap_supported_networks": ["ethereum", "base", "robinhood"],
743
+ "network_profiles": {
744
+ str(network): {
745
+ **dict(profile),
746
+ "providerUrl": _sanitize_provider_url((profile or {}).get("providerUrl")),
747
+ }
748
+ for network, profile in profiles.items()
749
+ if isinstance(profile, dict)
750
+ },
751
+ "selected_profile": {
752
+ **dict(data.get("selectedProfile") or {}),
753
+ "providerUrl": _sanitize_provider_url((data.get("selectedProfile") or {}).get("providerUrl")),
754
+ }
755
+ if isinstance(data.get("selectedProfile"), dict)
756
+ else data.get("selectedProfile"),
757
+ "source": "wdk-evm-wallet",
758
+ }
759
+
760
+ async def get_lifi_supported_chains(self) -> dict[str, Any]:
761
+ chains = await lifi.fetch_supported_chains()
762
+ supported = lifi.format_openclaw_supported_chains(chains)
763
+ return {
764
+ "provider": "lifi",
765
+ "chain": "cross-chain",
766
+ "network": "mainnet",
767
+ "supported_by_openclaw": lifi.OPENCLAW_SUPPORTED_CHAINS,
768
+ "chain_count": len(supported),
769
+ "chains": supported,
770
+ "source": "lifi",
771
+ }
772
+
773
+ async def get_lifi_quote(
774
+ self,
775
+ *,
776
+ from_chain: str,
777
+ to_chain: str,
778
+ from_token: str,
779
+ to_token: str,
780
+ amount_in_raw: str,
781
+ from_address: str | None = None,
782
+ to_address: str | None = None,
783
+ slippage: float | int | None = None,
784
+ allow_bridges: list[str] | None = None,
785
+ deny_bridges: list[str] | None = None,
786
+ prefer_bridges: list[str] | None = None,
787
+ ) -> dict[str, Any]:
788
+ from_chain_id = lifi.normalize_chain_id(from_chain, field_name="from_chain")
789
+ to_chain_id = lifi.normalize_chain_id(to_chain, field_name="to_chain")
790
+ current_chain_id = _lifi_chain_id_for_evm_network(self.network)
791
+ resolved_from_address = str(from_address or "").strip()
792
+ resolved_to_address = str(to_address or "").strip()
793
+ wallet_address: str | None = None
794
+ if from_chain_id == current_chain_id and not resolved_from_address:
795
+ wallet_address = await self.get_address()
796
+ resolved_from_address = str(wallet_address or "").strip()
797
+ if to_chain_id == current_chain_id and not resolved_to_address:
798
+ wallet_address = wallet_address or await self.get_address()
799
+ resolved_to_address = str(wallet_address or "").strip()
800
+ if not resolved_from_address:
801
+ raise WalletBackendError("from_address is required when the LI.FI source chain is not the active EVM network.")
802
+ if not resolved_to_address:
803
+ raise WalletBackendError("to_address is required when the LI.FI destination chain is not the active EVM network.")
804
+
805
+ payload = await lifi.fetch_quote(
806
+ from_chain=from_chain_id,
807
+ to_chain=to_chain_id,
808
+ from_token=from_token,
809
+ to_token=to_token,
810
+ amount_in_raw=amount_in_raw,
811
+ from_address=resolved_from_address,
812
+ to_address=resolved_to_address,
813
+ slippage=slippage,
814
+ allow_bridges=allow_bridges,
815
+ deny_bridges=deny_bridges,
816
+ prefer_bridges=prefer_bridges,
817
+ )
818
+ return {
819
+ "provider": "lifi",
820
+ "chain": "cross-chain",
821
+ "network": "mainnet",
822
+ "active_evm_network": self.network,
823
+ "from_chain": lifi.chain_name_for_id(from_chain_id),
824
+ "to_chain": lifi.chain_name_for_id(to_chain_id),
825
+ "from_chain_id": from_chain_id,
826
+ "to_chain_id": to_chain_id,
827
+ "from_token": lifi.normalize_token_address(from_token, chain_id=from_chain_id),
828
+ "to_token": lifi.normalize_token_address(to_token, chain_id=to_chain_id),
829
+ "amount_in_raw": amount_in_raw,
830
+ "from_address": resolved_from_address,
831
+ "to_address": resolved_to_address,
832
+ "slippage": slippage,
833
+ "allow_bridges": allow_bridges,
834
+ "deny_bridges": deny_bridges,
835
+ "prefer_bridges": prefer_bridges,
836
+ "tool": payload.get("tool"),
837
+ "tool_details": payload.get("toolDetails"),
838
+ "action": payload.get("action"),
839
+ "estimate": payload.get("estimate"),
840
+ "included_steps": payload.get("includedSteps"),
841
+ "transaction_request": payload.get("transactionRequest"),
842
+ "quote": payload,
843
+ "source": "lifi",
844
+ }
845
+
846
+ async def get_lifi_transfer_status(
847
+ self,
848
+ *,
849
+ tx_hash: str,
850
+ bridge: str | None = None,
851
+ from_chain: str | None = None,
852
+ to_chain: str | None = None,
853
+ ) -> dict[str, Any]:
854
+ payload = await lifi.fetch_transfer_status(
855
+ tx_hash=tx_hash,
856
+ bridge=bridge,
857
+ from_chain=from_chain,
858
+ to_chain=to_chain,
859
+ )
860
+ return {
861
+ "provider": "lifi",
862
+ "chain": "cross-chain",
863
+ "network": "mainnet",
864
+ "tx_hash": tx_hash,
865
+ "bridge": bridge,
866
+ "from_chain": from_chain,
867
+ "to_chain": to_chain,
868
+ "status": payload.get("status"),
869
+ "substatus": payload.get("substatus"),
870
+ "sending": payload.get("sending"),
871
+ "receiving": payload.get("receiving"),
872
+ "transfer": payload,
873
+ "source": "lifi",
874
+ }
875
+
876
+ async def get_evm_token_balance(self, token_address: str) -> dict[str, Any]:
877
+ resolved_address = await self.get_address()
878
+ data = await self.client.post(
879
+ "/v1/evm/token-balance/get",
880
+ {
881
+ "walletId": self.wallet_id,
882
+ "address": resolved_address,
883
+ "accountIndex": self.account_index,
884
+ "network": self.network,
885
+ "tokenAddress": token_address,
886
+ },
887
+ )
888
+ return {
889
+ "chain": self.chain,
890
+ "network": self.network,
891
+ "address": str(data.get("address") or resolved_address or ""),
892
+ "token_address": str(data.get("tokenAddress") or token_address),
893
+ "balance_raw": str(data.get("balance") or "0"),
894
+ "balance_ui": str(data.get("balanceFormatted")) if data.get("balanceFormatted") is not None else None,
895
+ "token_metadata": _normalize_token_metadata(
896
+ data.get("tokenMetadata"),
897
+ str(data.get("tokenAddress") or token_address),
898
+ ),
899
+ "chain_id": int(data.get("chainId") or 0),
900
+ "source": "wdk-evm-wallet",
901
+ }
902
+
903
+ async def get_evm_token_metadata(self, token_address: str) -> dict[str, Any]:
904
+ data = await self.client.post(
905
+ "/v1/evm/token-metadata/get",
906
+ {
907
+ "network": self.network,
908
+ "tokenAddress": token_address,
909
+ },
910
+ )
911
+ resolved = _normalize_token_metadata(
912
+ data.get("tokenMetadata"),
913
+ str(data.get("tokenAddress") or token_address),
914
+ )
915
+ return {
916
+ "chain": self.chain,
917
+ "network": self.network,
918
+ "token_address": str(data.get("tokenAddress") or token_address),
919
+ "token_metadata": resolved,
920
+ "chain_id": int(data.get("chainId") or 0),
921
+ "source": "wdk-evm-wallet",
922
+ }
923
+
924
+ async def get_evm_fee_rates(self) -> dict[str, Any]:
925
+ data = await self.client.post(
926
+ "/v1/evm/fee-rates/get",
927
+ {"network": self.network},
928
+ )
929
+ return {
930
+ "chain": self.chain,
931
+ "network": self.network,
932
+ "chain_id": int(data.get("chainId") or 0),
933
+ "gas_price_wei": str(data.get("gasPrice") or "0"),
934
+ "fee_rates": data.get("feeRates") or {},
935
+ "source": "wdk-evm-wallet",
936
+ }
937
+
938
+ async def get_evm_transaction_receipt(self, tx_hash: str) -> dict[str, Any]:
939
+ data = await self.client.post(
940
+ "/v1/evm/transaction/receipt/get",
941
+ {
942
+ "network": self.network,
943
+ "txHash": tx_hash,
944
+ },
945
+ )
946
+ return {
947
+ "chain": self.chain,
948
+ "network": self.network,
949
+ "chain_id": int(data.get("chainId") or 0),
950
+ "tx_hash": tx_hash,
951
+ "found": bool(data.get("found")),
952
+ "status": data.get("status"),
953
+ "receipt": data.get("receipt"),
954
+ "source": "wdk-evm-wallet",
955
+ }
956
+
957
+ async def get_evm_aave_account(self) -> dict[str, Any]:
958
+ resolved_address = await self.get_address()
959
+ data = await self.client.post(
960
+ "/v1/evm/aave/account/get",
961
+ {
962
+ "walletId": self.wallet_id,
963
+ "address": resolved_address,
964
+ "accountIndex": self.account_index,
965
+ "network": self.network,
966
+ },
967
+ )
968
+ return {
969
+ "chain": self.chain,
970
+ "network": self.network,
971
+ "address": str(data.get("address") or resolved_address or ""),
972
+ "protocol": str(data.get("protocol") or "aave-v3"),
973
+ "account_data": dict(data.get("accountData") or {}),
974
+ "chain_id": int(data.get("chainId") or 0),
975
+ "source": "wdk-evm-wallet",
976
+ }
977
+
978
+ async def get_evm_aave_reserves(self) -> dict[str, Any]:
979
+ data = await self.client.post(
980
+ "/v1/evm/aave/reserves/get",
981
+ {
982
+ "walletId": self.wallet_id,
983
+ "accountIndex": self.account_index,
984
+ "network": self.network,
985
+ },
986
+ )
987
+ return {
988
+ "chain": self.chain,
989
+ "network": self.network,
990
+ "protocol": str(data.get("protocol") or "aave-v3"),
991
+ "chain_id": int(data.get("chainId") or 0),
992
+ "pool": str(data.get("pool") or "").strip() or None,
993
+ "pool_addresses_provider": str(data.get("poolAddressesProvider") or "").strip() or None,
994
+ "ui_pool_data_provider": str(data.get("uiPoolDataProvider") or "").strip() or None,
995
+ "price_oracle": str(data.get("priceOracle") or "").strip() or None,
996
+ "base_currency_info": dict(data.get("baseCurrencyInfo") or {}),
997
+ "reserve_count": int(data.get("reserveCount") or 0),
998
+ "reserves": list(data.get("reserves") or []),
999
+ "source": "wdk-evm-wallet",
1000
+ }
1001
+
1002
+ async def get_evm_aave_positions(self) -> dict[str, Any]:
1003
+ resolved_address = await self.get_address()
1004
+ data = await self.client.post(
1005
+ "/v1/evm/aave/positions/get",
1006
+ {
1007
+ "walletId": self.wallet_id,
1008
+ "address": resolved_address,
1009
+ "accountIndex": self.account_index,
1010
+ "network": self.network,
1011
+ },
1012
+ )
1013
+ return {
1014
+ "chain": self.chain,
1015
+ "network": self.network,
1016
+ "address": str(data.get("address") or resolved_address or ""),
1017
+ "protocol": str(data.get("protocol") or "aave-v3"),
1018
+ "chain_id": int(data.get("chainId") or 0),
1019
+ "emode_category_id": str(data.get("eModeCategoryId") or "0"),
1020
+ "account_data": dict(data.get("accountData") or {}),
1021
+ "base_currency_info": dict(data.get("baseCurrencyInfo") or {}),
1022
+ "position_count": int(data.get("positionCount") or 0),
1023
+ "positions": list(data.get("positions") or []),
1024
+ "source": "wdk-evm-wallet",
1025
+ }
1026
+
1027
+ async def get_evm_lido_overview(self) -> dict[str, Any]:
1028
+ resolved_address = await self.get_address()
1029
+ data = await self.client.post(
1030
+ "/v1/evm/lido/overview/get",
1031
+ {
1032
+ "walletId": self.wallet_id,
1033
+ "address": resolved_address,
1034
+ "accountIndex": self.account_index,
1035
+ "network": self.network,
1036
+ },
1037
+ )
1038
+ return {
1039
+ "chain": self.chain,
1040
+ "network": self.network,
1041
+ "protocol": str(data.get("protocol") or "lido"),
1042
+ "preferred_position_token": str(data.get("preferredPositionToken") or "wstETH"),
1043
+ "chain_id": int(data.get("chainId") or 0),
1044
+ "staking_asset": dict(data.get("stakingAsset") or {}),
1045
+ "referral_address": str(data.get("referralAddress") or "").strip() or None,
1046
+ "contracts": dict(data.get("contracts") or {}),
1047
+ "steth_metadata": dict(data.get("stEthMetadata") or {}),
1048
+ "wsteth_metadata": dict(data.get("wstEthMetadata") or {}),
1049
+ "sample_rates": dict(data.get("sampleRates") or {}),
1050
+ "staking_apr": dict(data.get("stakingApr") or {}) if isinstance(data.get("stakingApr"), dict) else None,
1051
+ "staking_apr_error": (
1052
+ dict(data.get("stakingAprError") or {})
1053
+ if isinstance(data.get("stakingAprError"), dict)
1054
+ else None
1055
+ ),
1056
+ "source": "wdk-evm-wallet",
1057
+ }
1058
+
1059
+ async def get_evm_lido_positions(self) -> dict[str, Any]:
1060
+ resolved_address = await self.get_address()
1061
+ data = await self.client.post(
1062
+ "/v1/evm/lido/positions/get",
1063
+ {
1064
+ "walletId": self.wallet_id,
1065
+ "address": resolved_address,
1066
+ "accountIndex": self.account_index,
1067
+ "network": self.network,
1068
+ },
1069
+ )
1070
+ return {
1071
+ "chain": self.chain,
1072
+ "network": self.network,
1073
+ "address": str(data.get("address") or resolved_address or ""),
1074
+ "protocol": str(data.get("protocol") or "lido"),
1075
+ "preferred_position_token": str(data.get("preferredPositionToken") or "wstETH"),
1076
+ "chain_id": int(data.get("chainId") or 0),
1077
+ "contracts": dict(data.get("contracts") or {}),
1078
+ "native_balance_wei": str(data.get("nativeBalanceWei") or "0"),
1079
+ "native_balance_ui": str(data.get("nativeBalanceFormatted") or "0"),
1080
+ "steth_equivalent_total_raw": str(data.get("stEthEquivalentTotalRaw") or "0"),
1081
+ "steth_equivalent_total_ui": str(data.get("stEthEquivalentTotalFormatted") or "0"),
1082
+ "position_count": int(data.get("positionCount") or 0),
1083
+ "positions": list(data.get("positions") or []),
1084
+ "source": "wdk-evm-wallet",
1085
+ }
1086
+
1087
+ async def get_evm_lido_withdrawal_requests(self) -> dict[str, Any]:
1088
+ resolved_address = await self.get_address()
1089
+ data = await self.client.post(
1090
+ "/v1/evm/lido/withdrawals/get",
1091
+ {
1092
+ "walletId": self.wallet_id,
1093
+ "address": resolved_address,
1094
+ "accountIndex": self.account_index,
1095
+ "network": self.network,
1096
+ },
1097
+ )
1098
+ return {
1099
+ "chain": self.chain,
1100
+ "network": self.network,
1101
+ "address": str(data.get("address") or resolved_address or ""),
1102
+ "protocol": str(data.get("protocol") or "lido"),
1103
+ "chain_id": int(data.get("chainId") or 0),
1104
+ "withdrawal_queue": str(data.get("withdrawalQueue") or "").strip() or None,
1105
+ "request_count": int(data.get("requestCount") or 0),
1106
+ "claimable_count": int(data.get("claimableCount") or 0),
1107
+ "requests": list(data.get("requests") or []),
1108
+ "source": "wdk-evm-wallet",
1109
+ }
1110
+
1111
+ async def get_evm_morpho_vaults(
1112
+ self,
1113
+ *,
1114
+ vault_address: str | None = None,
1115
+ limit: int | None = None,
1116
+ listed_only: bool = True,
1117
+ asset_address: str | None = None,
1118
+ min_tvl_usd: float | int | None = None,
1119
+ min_net_apy: float | int | None = None,
1120
+ order_by: str | None = None,
1121
+ order_direction: str | None = None,
1122
+ ) -> dict[str, Any]:
1123
+ payload: dict[str, Any] = {
1124
+ "network": self.network,
1125
+ "listedOnly": bool(listed_only),
1126
+ }
1127
+ if isinstance(vault_address, str) and vault_address.strip():
1128
+ payload["vaultAddress"] = vault_address.strip()
1129
+ if limit is not None:
1130
+ payload["limit"] = int(limit)
1131
+ if isinstance(asset_address, str) and asset_address.strip():
1132
+ payload["assetAddress"] = asset_address.strip()
1133
+ if min_tvl_usd is not None:
1134
+ payload["minTotalAssetsUsd"] = min_tvl_usd
1135
+ if min_net_apy is not None:
1136
+ payload["minNetApy"] = min_net_apy
1137
+ if isinstance(order_by, str) and order_by.strip():
1138
+ payload["orderBy"] = order_by.strip()
1139
+ if isinstance(order_direction, str) and order_direction.strip():
1140
+ payload["orderDirection"] = order_direction.strip()
1141
+ data = await self.client.post("/v1/evm/morpho/vaults/get", payload)
1142
+ return {
1143
+ "chain": self.chain,
1144
+ "network": self.network,
1145
+ "protocol": str(data.get("protocol") or "morpho"),
1146
+ "chain_id": int(data.get("chainId") or 0),
1147
+ "listed_only": bool(data.get("listedOnly", listed_only)),
1148
+ "requested_limit": int(data.get("requestedLimit") or 0),
1149
+ "order_by": data.get("orderBy"),
1150
+ "order_direction": data.get("orderDirection"),
1151
+ "asset_address_filter": data.get("assetAddressFilter"),
1152
+ "min_tvl_usd": data.get("minTotalAssetsUsd"),
1153
+ "min_net_apy": data.get("minNetApy"),
1154
+ "found": bool(data.get("found")) if "found" in data else None,
1155
+ "vault_count": int(data.get("vaultCount") or 0),
1156
+ "vault": dict(data.get("vault") or {}) if isinstance(data.get("vault"), dict) else None,
1157
+ "vaults": list(data.get("vaults") or []),
1158
+ "source": "wdk-evm-wallet",
1159
+ }
1160
+
1161
+ async def get_evm_morpho_markets(
1162
+ self,
1163
+ *,
1164
+ market_id: str | None = None,
1165
+ limit: int | None = None,
1166
+ listed_only: bool = True,
1167
+ search: str | None = None,
1168
+ collateral_asset_address: str | None = None,
1169
+ loan_asset_address: str | None = None,
1170
+ min_supply_usd: float | int | None = None,
1171
+ min_net_supply_apy: float | int | None = None,
1172
+ order_by: str | None = None,
1173
+ order_direction: str | None = None,
1174
+ ) -> dict[str, Any]:
1175
+ payload: dict[str, Any] = {
1176
+ "network": self.network,
1177
+ "listedOnly": bool(listed_only),
1178
+ }
1179
+ if isinstance(market_id, str) and market_id.strip():
1180
+ payload["marketId"] = market_id.strip()
1181
+ if limit is not None:
1182
+ payload["limit"] = int(limit)
1183
+ if isinstance(search, str) and search.strip():
1184
+ payload["search"] = search.strip()
1185
+ if isinstance(collateral_asset_address, str) and collateral_asset_address.strip():
1186
+ payload["collateralAssetAddress"] = collateral_asset_address.strip()
1187
+ if isinstance(loan_asset_address, str) and loan_asset_address.strip():
1188
+ payload["loanAssetAddress"] = loan_asset_address.strip()
1189
+ if min_supply_usd is not None:
1190
+ payload["minSupplyAssetsUsd"] = min_supply_usd
1191
+ if min_net_supply_apy is not None:
1192
+ payload["minNetSupplyApy"] = min_net_supply_apy
1193
+ if isinstance(order_by, str) and order_by.strip():
1194
+ payload["orderBy"] = order_by.strip()
1195
+ if isinstance(order_direction, str) and order_direction.strip():
1196
+ payload["orderDirection"] = order_direction.strip()
1197
+ data = await self.client.post("/v1/evm/morpho/markets/get", payload)
1198
+ return {
1199
+ "chain": self.chain,
1200
+ "network": self.network,
1201
+ "protocol": str(data.get("protocol") or "morpho"),
1202
+ "chain_id": int(data.get("chainId") or 0),
1203
+ "listed_only": bool(data.get("listedOnly", listed_only)),
1204
+ "requested_limit": int(data.get("requestedLimit") or 0),
1205
+ "order_by": data.get("orderBy"),
1206
+ "order_direction": data.get("orderDirection"),
1207
+ "search": data.get("search"),
1208
+ "collateral_asset_filter": data.get("collateralAssetFilter"),
1209
+ "loan_asset_filter": data.get("loanAssetFilter"),
1210
+ "min_supply_usd": data.get("minSupplyAssetsUsd"),
1211
+ "min_net_supply_apy": data.get("minNetSupplyApy"),
1212
+ "found": bool(data.get("found")) if "found" in data else None,
1213
+ "market_count": int(data.get("marketCount") or 0),
1214
+ "market": dict(data.get("market") or {}) if isinstance(data.get("market"), dict) else None,
1215
+ "markets": list(data.get("markets") or []),
1216
+ "source": "wdk-evm-wallet",
1217
+ }
1218
+
1219
+ async def get_evm_morpho_positions(self) -> dict[str, Any]:
1220
+ resolved_address = await self.get_address()
1221
+ data = await self.client.post(
1222
+ "/v1/evm/morpho/positions/get",
1223
+ {
1224
+ "walletId": self.wallet_id,
1225
+ "address": resolved_address,
1226
+ "accountIndex": self.account_index,
1227
+ "network": self.network,
1228
+ },
1229
+ )
1230
+ return {
1231
+ "chain": self.chain,
1232
+ "network": self.network,
1233
+ "address": str(data.get("address") or resolved_address or ""),
1234
+ "protocol": str(data.get("protocol") or "morpho"),
1235
+ "chain_id": int(data.get("chainId") or 0),
1236
+ "market_position_count": int(data.get("marketPositionCount") or 0),
1237
+ "vault_position_count": int(data.get("vaultPositionCount") or 0),
1238
+ "hidden_dust_vault_position_count": int(data.get("hiddenDustVaultPositionCount") or 0),
1239
+ "dust_threshold_usd": data.get("dustThresholdUsd"),
1240
+ "market_positions": list(data.get("marketPositions") or []),
1241
+ "vault_positions": list(data.get("vaultPositions") or []),
1242
+ "source": "wdk-evm-wallet",
1243
+ }
1244
+
1245
+ async def get_morpho_rebalance_report(
1246
+ self,
1247
+ *,
1248
+ networks: list[str] | None = None,
1249
+ min_tvl_usd: float | int | None = None,
1250
+ candidate_limit: int | None = None,
1251
+ include_migration_cost: bool = True,
1252
+ ) -> dict[str, Any]:
1253
+ resolved_address = await self.get_address()
1254
+ payload: dict[str, Any] = {
1255
+ "walletId": self.wallet_id,
1256
+ "address": resolved_address,
1257
+ "accountIndex": self.account_index,
1258
+ }
1259
+ if not include_migration_cost:
1260
+ payload["includeMigrationCost"] = False
1261
+ if networks:
1262
+ payload["networks"] = [str(network).strip().lower() for network in networks]
1263
+ if min_tvl_usd is not None:
1264
+ payload["minTvlUsd"] = min_tvl_usd
1265
+ if candidate_limit is not None:
1266
+ payload["candidateLimit"] = int(candidate_limit)
1267
+ data = await self.client.post("/v1/evm/morpho/rebalance-report/get", payload)
1268
+ return {
1269
+ "chain": self.chain,
1270
+ "protocol": str(data.get("protocol") or "morpho"),
1271
+ "address": str(data.get("address") or resolved_address or ""),
1272
+ "scanned_at": data.get("scannedAt"),
1273
+ "networks": list(data.get("networks") or []),
1274
+ "criteria": dict(data.get("criteria") or {}),
1275
+ "position_count": int(data.get("positionCount") or 0),
1276
+ "opportunity_count": int(data.get("opportunityCount") or 0),
1277
+ "network_reports": list(data.get("networkReports") or []),
1278
+ "source": "wdk-evm-wallet",
1279
+ }
1280
+
1281
+ async def preview_evm_aave_operation(
1282
+ self,
1283
+ *,
1284
+ operation: str,
1285
+ token_address: str,
1286
+ amount_raw: str,
1287
+ ) -> dict[str, Any]:
1288
+ normalized_operation = _normalize_aave_operation(operation)
1289
+ resolved_address = await self.get_address()
1290
+ data = await self.client.post(
1291
+ f"/v1/evm/aave/{normalized_operation}/quote",
1292
+ {
1293
+ "walletId": self.wallet_id,
1294
+ "address": resolved_address,
1295
+ "accountIndex": self.account_index,
1296
+ "network": self.network,
1297
+ "tokenAddress": token_address,
1298
+ "amount": amount_raw,
1299
+ },
1300
+ )
1301
+ return _normalize_aave_payload(
1302
+ chain=self.chain,
1303
+ network=self.network,
1304
+ wallet_id=self.wallet_id,
1305
+ address=resolved_address,
1306
+ operation=normalized_operation,
1307
+ token_address=token_address,
1308
+ amount_raw=amount_raw,
1309
+ data=data,
1310
+ sign_only=self.sign_only,
1311
+ )
1312
+
1313
+ async def send_evm_aave_operation(
1314
+ self,
1315
+ *,
1316
+ operation: str,
1317
+ token_address: str,
1318
+ amount_raw: str,
1319
+ expected_quote_fingerprint: str | None = None,
1320
+ ) -> dict[str, Any]:
1321
+ if self.sign_only:
1322
+ raise WalletBackendError("wdk_evm_local is configured as sign_only.")
1323
+ normalized_operation = _normalize_aave_operation(operation)
1324
+ data = await self.client.post(
1325
+ f"/v1/evm/aave/{normalized_operation}/send",
1326
+ {
1327
+ "walletId": self.wallet_id,
1328
+ "accountIndex": self.account_index,
1329
+ "network": self.network,
1330
+ "tokenAddress": token_address,
1331
+ "amount": amount_raw,
1332
+ **(
1333
+ {"expectedQuoteFingerprint": expected_quote_fingerprint}
1334
+ if isinstance(expected_quote_fingerprint, str) and expected_quote_fingerprint.strip()
1335
+ else {}
1336
+ ),
1337
+ },
1338
+ )
1339
+ return {
1340
+ **_normalize_aave_payload(
1341
+ chain=self.chain,
1342
+ network=self.network,
1343
+ wallet_id=self.wallet_id,
1344
+ address=await self.get_address(),
1345
+ operation=normalized_operation,
1346
+ token_address=token_address,
1347
+ amount_raw=amount_raw,
1348
+ data=data,
1349
+ sign_only=self.sign_only,
1350
+ ),
1351
+ "broadcasted": True,
1352
+ "confirmed": bool(data.get("confirmed")),
1353
+ "confirmation_status": data.get("confirmation_status"),
1354
+ "tx_hash": data.get("tx_hash"),
1355
+ }
1356
+
1357
+ async def preview_evm_lido_operation(
1358
+ self,
1359
+ *,
1360
+ operation: str,
1361
+ amount_raw: str,
1362
+ ) -> dict[str, Any]:
1363
+ normalized_operation = _normalize_lido_operation(operation)
1364
+ resolved_address = await self.get_address()
1365
+ data = await self.client.post(
1366
+ f"/v1/evm/lido/{normalized_operation}/quote",
1367
+ {
1368
+ "walletId": self.wallet_id,
1369
+ "address": resolved_address,
1370
+ "accountIndex": self.account_index,
1371
+ "network": self.network,
1372
+ "amount": amount_raw,
1373
+ },
1374
+ )
1375
+ return _normalize_lido_payload(
1376
+ chain=self.chain,
1377
+ network=self.network,
1378
+ wallet_id=self.wallet_id,
1379
+ address=resolved_address,
1380
+ operation=normalized_operation,
1381
+ amount_raw=amount_raw,
1382
+ data=data,
1383
+ sign_only=self.sign_only,
1384
+ )
1385
+
1386
+ async def send_evm_lido_operation(
1387
+ self,
1388
+ *,
1389
+ operation: str,
1390
+ amount_raw: str,
1391
+ expected_quote_fingerprint: str | None = None,
1392
+ ) -> dict[str, Any]:
1393
+ if self.sign_only:
1394
+ raise WalletBackendError("wdk_evm_local is configured as sign_only.")
1395
+ normalized_operation = _normalize_lido_operation(operation)
1396
+ data = await self.client.post(
1397
+ f"/v1/evm/lido/{normalized_operation}/send",
1398
+ {
1399
+ "walletId": self.wallet_id,
1400
+ "accountIndex": self.account_index,
1401
+ "network": self.network,
1402
+ "amount": amount_raw,
1403
+ **(
1404
+ {"expectedQuoteFingerprint": expected_quote_fingerprint}
1405
+ if isinstance(expected_quote_fingerprint, str) and expected_quote_fingerprint.strip()
1406
+ else {}
1407
+ ),
1408
+ },
1409
+ )
1410
+ return {
1411
+ **_normalize_lido_payload(
1412
+ chain=self.chain,
1413
+ network=self.network,
1414
+ wallet_id=self.wallet_id,
1415
+ address=await self.get_address(),
1416
+ operation=normalized_operation,
1417
+ amount_raw=amount_raw,
1418
+ data=data,
1419
+ sign_only=self.sign_only,
1420
+ ),
1421
+ "broadcasted": True,
1422
+ "confirmed": bool(data.get("confirmed")),
1423
+ "confirmation_status": data.get("confirmation_status"),
1424
+ "tx_hash": data.get("tx_hash"),
1425
+ }
1426
+
1427
+ async def preview_evm_lido_withdrawal(
1428
+ self,
1429
+ *,
1430
+ operation: str,
1431
+ amount_raw: str | None = None,
1432
+ request_id: str | None = None,
1433
+ ) -> dict[str, Any]:
1434
+ normalized_operation = _normalize_lido_withdrawal_operation(operation)
1435
+ resolved_address = await self.get_address()
1436
+ payload: dict[str, Any] = {
1437
+ "walletId": self.wallet_id,
1438
+ "address": resolved_address,
1439
+ "accountIndex": self.account_index,
1440
+ "network": self.network,
1441
+ }
1442
+ if amount_raw is not None:
1443
+ payload["amount"] = amount_raw
1444
+ if request_id is not None:
1445
+ payload["requestId"] = request_id
1446
+ data = await self.client.post(
1447
+ f"/v1/evm/lido/{normalized_operation}/quote",
1448
+ payload,
1449
+ )
1450
+ return _normalize_lido_withdrawal_payload(
1451
+ chain=self.chain,
1452
+ network=self.network,
1453
+ wallet_id=self.wallet_id,
1454
+ address=resolved_address,
1455
+ operation=normalized_operation,
1456
+ amount_raw=amount_raw,
1457
+ request_id=request_id,
1458
+ data=data,
1459
+ sign_only=self.sign_only,
1460
+ )
1461
+
1462
+ async def send_evm_lido_withdrawal(
1463
+ self,
1464
+ *,
1465
+ operation: str,
1466
+ amount_raw: str | None = None,
1467
+ request_id: str | None = None,
1468
+ expected_quote_fingerprint: str | None = None,
1469
+ ) -> dict[str, Any]:
1470
+ if self.sign_only:
1471
+ raise WalletBackendError("wdk_evm_local is configured as sign_only.")
1472
+ normalized_operation = _normalize_lido_withdrawal_operation(operation)
1473
+ payload: dict[str, Any] = {
1474
+ "walletId": self.wallet_id,
1475
+ "accountIndex": self.account_index,
1476
+ "network": self.network,
1477
+ }
1478
+ if amount_raw is not None:
1479
+ payload["amount"] = amount_raw
1480
+ if request_id is not None:
1481
+ payload["requestId"] = request_id
1482
+ if isinstance(expected_quote_fingerprint, str) and expected_quote_fingerprint.strip():
1483
+ payload["expectedQuoteFingerprint"] = expected_quote_fingerprint
1484
+ data = await self.client.post(
1485
+ f"/v1/evm/lido/{normalized_operation}/send",
1486
+ payload,
1487
+ )
1488
+ return {
1489
+ **_normalize_lido_withdrawal_payload(
1490
+ chain=self.chain,
1491
+ network=self.network,
1492
+ wallet_id=self.wallet_id,
1493
+ address=await self.get_address(),
1494
+ operation=normalized_operation,
1495
+ amount_raw=amount_raw,
1496
+ request_id=request_id,
1497
+ data=data,
1498
+ sign_only=self.sign_only,
1499
+ ),
1500
+ "broadcasted": True,
1501
+ "confirmed": bool(data.get("confirmed")),
1502
+ "confirmation_status": data.get("confirmation_status"),
1503
+ "tx_hash": data.get("tx_hash"),
1504
+ }
1505
+
1506
+ async def preview_evm_morpho_vault_operation(
1507
+ self,
1508
+ *,
1509
+ operation: str,
1510
+ token_address: str,
1511
+ vault_address: str | None = None,
1512
+ vault_preset: str | None = None,
1513
+ amount_raw: str | None = None,
1514
+ native_amount_raw: str | None = None,
1515
+ ) -> dict[str, Any]:
1516
+ normalized_operation = _normalize_morpho_vault_operation(operation)
1517
+ resolved_address = await self.get_address()
1518
+ payload: dict[str, Any] = {
1519
+ "walletId": self.wallet_id,
1520
+ "address": resolved_address,
1521
+ "accountIndex": self.account_index,
1522
+ "network": self.network,
1523
+ "tokenAddress": token_address,
1524
+ }
1525
+ if isinstance(vault_address, str) and vault_address.strip():
1526
+ payload["vaultAddress"] = vault_address.strip()
1527
+ if isinstance(vault_preset, str) and vault_preset.strip():
1528
+ payload["vaultPreset"] = vault_preset.strip()
1529
+ if amount_raw is not None:
1530
+ payload["amount"] = amount_raw
1531
+ if native_amount_raw is not None:
1532
+ payload["nativeAmount"] = native_amount_raw
1533
+ data = await self.client.post(
1534
+ f"/v1/evm/morpho/vault/{normalized_operation}/quote",
1535
+ payload,
1536
+ )
1537
+ return _normalize_morpho_payload(
1538
+ chain=self.chain,
1539
+ network=self.network,
1540
+ wallet_id=self.wallet_id,
1541
+ address=resolved_address,
1542
+ operation=normalized_operation,
1543
+ token_address=token_address,
1544
+ amount_raw=amount_raw,
1545
+ native_amount_raw=native_amount_raw,
1546
+ data=data,
1547
+ sign_only=self.sign_only,
1548
+ )
1549
+
1550
+ async def send_evm_morpho_vault_operation(
1551
+ self,
1552
+ *,
1553
+ operation: str,
1554
+ token_address: str,
1555
+ vault_address: str | None = None,
1556
+ vault_preset: str | None = None,
1557
+ amount_raw: str | None = None,
1558
+ native_amount_raw: str | None = None,
1559
+ expected_quote_fingerprint: str | None = None,
1560
+ ) -> dict[str, Any]:
1561
+ if self.sign_only:
1562
+ raise WalletBackendError("wdk_evm_local is configured as sign_only.")
1563
+ normalized_operation = _normalize_morpho_vault_operation(operation)
1564
+ payload: dict[str, Any] = {
1565
+ "walletId": self.wallet_id,
1566
+ "accountIndex": self.account_index,
1567
+ "network": self.network,
1568
+ "tokenAddress": token_address,
1569
+ }
1570
+ if isinstance(vault_address, str) and vault_address.strip():
1571
+ payload["vaultAddress"] = vault_address.strip()
1572
+ if isinstance(vault_preset, str) and vault_preset.strip():
1573
+ payload["vaultPreset"] = vault_preset.strip()
1574
+ if amount_raw is not None:
1575
+ payload["amount"] = amount_raw
1576
+ if native_amount_raw is not None:
1577
+ payload["nativeAmount"] = native_amount_raw
1578
+ if isinstance(expected_quote_fingerprint, str) and expected_quote_fingerprint.strip():
1579
+ payload["expectedQuoteFingerprint"] = expected_quote_fingerprint.strip()
1580
+ data = await self.client.post(
1581
+ f"/v1/evm/morpho/vault/{normalized_operation}/send",
1582
+ payload,
1583
+ )
1584
+ return {
1585
+ **_normalize_morpho_payload(
1586
+ chain=self.chain,
1587
+ network=self.network,
1588
+ wallet_id=self.wallet_id,
1589
+ address=await self.get_address(),
1590
+ operation=normalized_operation,
1591
+ token_address=token_address,
1592
+ amount_raw=amount_raw,
1593
+ native_amount_raw=native_amount_raw,
1594
+ data=data,
1595
+ sign_only=self.sign_only,
1596
+ ),
1597
+ "broadcasted": True,
1598
+ "confirmed": bool(data.get("confirmed")),
1599
+ "confirmation_status": data.get("confirmation_status"),
1600
+ "tx_hash": data.get("tx_hash"),
1601
+ }
1602
+
1603
+ async def preview_evm_morpho_market_operation(
1604
+ self,
1605
+ *,
1606
+ operation: str,
1607
+ token_address: str,
1608
+ market_id: str | None = None,
1609
+ market_preset: str | None = None,
1610
+ amount_raw: str | None = None,
1611
+ native_amount_raw: str | None = None,
1612
+ ) -> dict[str, Any]:
1613
+ normalized_operation = _normalize_morpho_market_operation(operation)
1614
+ resolved_address = await self.get_address()
1615
+ payload: dict[str, Any] = {
1616
+ "walletId": self.wallet_id,
1617
+ "address": resolved_address,
1618
+ "accountIndex": self.account_index,
1619
+ "network": self.network,
1620
+ "tokenAddress": token_address,
1621
+ }
1622
+ if isinstance(market_id, str) and market_id.strip():
1623
+ payload["marketId"] = market_id.strip()
1624
+ if isinstance(market_preset, str) and market_preset.strip():
1625
+ payload["marketPreset"] = market_preset.strip()
1626
+ if amount_raw is not None:
1627
+ payload["amount"] = amount_raw
1628
+ if native_amount_raw is not None:
1629
+ payload["nativeAmount"] = native_amount_raw
1630
+ data = await self.client.post(
1631
+ f"/v1/evm/morpho/market/{normalized_operation}/quote",
1632
+ payload,
1633
+ )
1634
+ return _normalize_morpho_payload(
1635
+ chain=self.chain,
1636
+ network=self.network,
1637
+ wallet_id=self.wallet_id,
1638
+ address=resolved_address,
1639
+ operation=normalized_operation,
1640
+ token_address=token_address,
1641
+ amount_raw=amount_raw,
1642
+ native_amount_raw=native_amount_raw,
1643
+ data=data,
1644
+ sign_only=self.sign_only,
1645
+ )
1646
+
1647
+ async def send_evm_morpho_market_operation(
1648
+ self,
1649
+ *,
1650
+ operation: str,
1651
+ token_address: str,
1652
+ market_id: str | None = None,
1653
+ market_preset: str | None = None,
1654
+ amount_raw: str | None = None,
1655
+ native_amount_raw: str | None = None,
1656
+ expected_quote_fingerprint: str | None = None,
1657
+ ) -> dict[str, Any]:
1658
+ if self.sign_only:
1659
+ raise WalletBackendError("wdk_evm_local is configured as sign_only.")
1660
+ normalized_operation = _normalize_morpho_market_operation(operation)
1661
+ payload: dict[str, Any] = {
1662
+ "walletId": self.wallet_id,
1663
+ "accountIndex": self.account_index,
1664
+ "network": self.network,
1665
+ "tokenAddress": token_address,
1666
+ }
1667
+ if isinstance(market_id, str) and market_id.strip():
1668
+ payload["marketId"] = market_id.strip()
1669
+ if isinstance(market_preset, str) and market_preset.strip():
1670
+ payload["marketPreset"] = market_preset.strip()
1671
+ if amount_raw is not None:
1672
+ payload["amount"] = amount_raw
1673
+ if native_amount_raw is not None:
1674
+ payload["nativeAmount"] = native_amount_raw
1675
+ if isinstance(expected_quote_fingerprint, str) and expected_quote_fingerprint.strip():
1676
+ payload["expectedQuoteFingerprint"] = expected_quote_fingerprint.strip()
1677
+ data = await self.client.post(
1678
+ f"/v1/evm/morpho/market/{normalized_operation}/send",
1679
+ payload,
1680
+ )
1681
+ return {
1682
+ **_normalize_morpho_payload(
1683
+ chain=self.chain,
1684
+ network=self.network,
1685
+ wallet_id=self.wallet_id,
1686
+ address=await self.get_address(),
1687
+ operation=normalized_operation,
1688
+ token_address=token_address,
1689
+ amount_raw=amount_raw,
1690
+ native_amount_raw=native_amount_raw,
1691
+ data=data,
1692
+ sign_only=self.sign_only,
1693
+ ),
1694
+ "broadcasted": True,
1695
+ "confirmed": bool(data.get("confirmed")),
1696
+ "confirmation_status": data.get("confirmation_status"),
1697
+ "tx_hash": data.get("tx_hash"),
1698
+ }
1699
+
1700
+ async def get_evm_swap_quote(
1701
+ self,
1702
+ *,
1703
+ token_in: str,
1704
+ token_out: str,
1705
+ amount_in_raw: str,
1706
+ ) -> dict[str, Any]:
1707
+ resolved_address = await self.get_address()
1708
+ data = await self.client.post(
1709
+ "/v1/evm/swap/quote",
1710
+ {
1711
+ "walletId": self.wallet_id,
1712
+ "address": resolved_address,
1713
+ "accountIndex": self.account_index,
1714
+ "network": self.network,
1715
+ "tokenIn": token_in,
1716
+ "tokenOut": token_out,
1717
+ "tokenInAmount": amount_in_raw,
1718
+ },
1719
+ )
1720
+ quote = dict(data.get("quote") or {})
1721
+ return {
1722
+ "chain": self.chain,
1723
+ "network": self.network,
1724
+ "address": str(data.get("address") or resolved_address or ""),
1725
+ "token_in": str((data.get("swapRequest") or {}).get("tokenIn") or token_in),
1726
+ "token_out": str((data.get("swapRequest") or {}).get("tokenOut") or token_out),
1727
+ "amount_in_raw": str((data.get("swapRequest") or {}).get("tokenInAmount") or amount_in_raw),
1728
+ "amount_in_ui": str(data.get("inputAmountFormatted")) if data.get("inputAmountFormatted") is not None else None,
1729
+ "estimated_output_amount_raw": str(quote.get("tokenOutAmount") or "0"),
1730
+ "estimated_output_amount_ui": (
1731
+ str(data.get("outputAmountFormatted")) if data.get("outputAmountFormatted") is not None else None
1732
+ ),
1733
+ "quote": quote,
1734
+ "protocol": str(data.get("protocol") or "velora"),
1735
+ "execution_supported": bool(data.get("executionSupported")) and not self.sign_only,
1736
+ "quote_fingerprint": str(data.get("quoteFingerprint") or "").strip() or None,
1737
+ "router": str(data.get("router") or "").strip() or None,
1738
+ "estimated_fee_wei": (
1739
+ str(data.get("estimatedFeeWei"))
1740
+ if data.get("estimatedFeeWei") is not None
1741
+ else (_extract_fee_wei(quote) if _extract_fee_wei(quote) is not None else None)
1742
+ ),
1743
+ "estimated_swap_fee_wei": (
1744
+ str(data.get("estimatedSwapFeeWei"))
1745
+ if data.get("estimatedSwapFeeWei") is not None
1746
+ else (_extract_fee_wei(quote) if _extract_fee_wei(quote) is not None else None)
1747
+ ),
1748
+ "estimated_approval_fee_wei": str(data.get("estimatedApprovalFeeWei") or "0"),
1749
+ "fee_estimate_available": bool(data.get("feeEstimateAvailable", True)),
1750
+ "fee_estimate_error": data.get("feeEstimateError"),
1751
+ "slippage_bps": int(data.get("slippageBps") or 0) if data.get("slippageBps") is not None else None,
1752
+ "minimum_output_amount_raw": (
1753
+ str(data.get("minimumOutputAmountRaw"))
1754
+ if data.get("minimumOutputAmountRaw") is not None
1755
+ else None
1756
+ ),
1757
+ "allowance": _normalize_swap_allowance(data.get("allowance")),
1758
+ "simulation": _normalize_swap_simulation(data.get("simulation")),
1759
+ "swap_transaction": {
1760
+ "to": str((data.get("swapTransaction") or {}).get("to") or "").strip() or None,
1761
+ "value": str((data.get("swapTransaction") or {}).get("value") or "0"),
1762
+ "data_hash": str((data.get("swapTransaction") or {}).get("dataHash") or "").strip() or None,
1763
+ },
1764
+ "token_in_metadata": _normalize_token_metadata(
1765
+ data.get("tokenInMetadata"),
1766
+ str((data.get("swapRequest") or {}).get("tokenIn") or token_in),
1767
+ ),
1768
+ "token_out_metadata": _normalize_token_metadata(
1769
+ data.get("tokenOutMetadata"),
1770
+ str((data.get("swapRequest") or {}).get("tokenOut") or token_out),
1771
+ ),
1772
+ "chain_id": int(data.get("chainId") or 0),
1773
+ "source": "wdk-evm-wallet",
1774
+ }
1775
+
1776
+ async def preview_evm_swap(
1777
+ self,
1778
+ *,
1779
+ token_in: str,
1780
+ token_out: str,
1781
+ amount_in_raw: str,
1782
+ ) -> dict[str, Any]:
1783
+ resolved_address = await self.get_address()
1784
+ data = await self.client.post(
1785
+ "/v1/evm/swap/quote",
1786
+ {
1787
+ "walletId": self.wallet_id,
1788
+ "address": resolved_address,
1789
+ "accountIndex": self.account_index,
1790
+ "network": self.network,
1791
+ "tokenIn": token_in,
1792
+ "tokenOut": token_out,
1793
+ "tokenInAmount": amount_in_raw,
1794
+ },
1795
+ )
1796
+ quote = dict(data.get("quote") or {})
1797
+ return {
1798
+ "chain": self.chain,
1799
+ "network": self.network,
1800
+ "asset_type": "evm-swap",
1801
+ "asset": "ERC20",
1802
+ "wallet": self.wallet_id,
1803
+ "from_address": resolved_address,
1804
+ "token_in": str((data.get("swapRequest") or {}).get("tokenIn") or token_in),
1805
+ "token_out": str((data.get("swapRequest") or {}).get("tokenOut") or token_out),
1806
+ "input_amount_raw": str((data.get("swapRequest") or {}).get("tokenInAmount") or amount_in_raw),
1807
+ "input_amount_ui": str(data.get("inputAmountFormatted")) if data.get("inputAmountFormatted") is not None else None,
1808
+ "estimated_output_amount_raw": str(quote.get("tokenOutAmount") or "0"),
1809
+ "estimated_output_amount_ui": (
1810
+ str(data.get("outputAmountFormatted")) if data.get("outputAmountFormatted") is not None else None
1811
+ ),
1812
+ "estimated_fee_wei": (
1813
+ str(data.get("estimatedFeeWei"))
1814
+ if data.get("estimatedFeeWei") is not None
1815
+ else (_extract_fee_wei(quote) if _extract_fee_wei(quote) is not None else None)
1816
+ ),
1817
+ "estimated_swap_fee_wei": (
1818
+ str(data.get("estimatedSwapFeeWei"))
1819
+ if data.get("estimatedSwapFeeWei") is not None
1820
+ else (_extract_fee_wei(quote) if _extract_fee_wei(quote) is not None else None)
1821
+ ),
1822
+ "estimated_approval_fee_wei": str(data.get("estimatedApprovalFeeWei") or "0"),
1823
+ "fee_estimate_available": bool(data.get("feeEstimateAvailable", True)),
1824
+ "fee_estimate_error": data.get("feeEstimateError"),
1825
+ "slippage_bps": int(data.get("slippageBps") or 0) if data.get("slippageBps") is not None else None,
1826
+ "minimum_output_amount_raw": (
1827
+ str(data.get("minimumOutputAmountRaw"))
1828
+ if data.get("minimumOutputAmountRaw") is not None
1829
+ else None
1830
+ ),
1831
+ "swap_provider": str(data.get("protocol") or "velora"),
1832
+ "execution_supported": bool(data.get("executionSupported")) and not self.sign_only,
1833
+ "route_plan": _normalize_swap_route(quote),
1834
+ "quote_fingerprint": str(data.get("quoteFingerprint") or "").strip() or None,
1835
+ "router": str(data.get("router") or "").strip() or None,
1836
+ "allowance": _normalize_swap_allowance(data.get("allowance")),
1837
+ "simulation": _normalize_swap_simulation(data.get("simulation")),
1838
+ "swap_transaction": {
1839
+ "to": str((data.get("swapTransaction") or {}).get("to") or "").strip() or None,
1840
+ "value": str((data.get("swapTransaction") or {}).get("value") or "0"),
1841
+ "data_hash": str((data.get("swapTransaction") or {}).get("dataHash") or "").strip() or None,
1842
+ },
1843
+ "token_in_metadata": _normalize_token_metadata(
1844
+ data.get("tokenInMetadata"),
1845
+ str((data.get("swapRequest") or {}).get("tokenIn") or token_in),
1846
+ ),
1847
+ "token_out_metadata": _normalize_token_metadata(
1848
+ data.get("tokenOutMetadata"),
1849
+ str((data.get("swapRequest") or {}).get("tokenOut") or token_out),
1850
+ ),
1851
+ "quote": quote,
1852
+ "chain_id": int(data.get("chainId") or 0),
1853
+ "source": "wdk-evm-wallet",
1854
+ }
1855
+
1856
+ async def send_evm_swap(
1857
+ self,
1858
+ *,
1859
+ token_in: str,
1860
+ token_out: str,
1861
+ amount_in_raw: str,
1862
+ expected_quote_fingerprint: str | None = None,
1863
+ minimum_output_amount_raw: str | None = None,
1864
+ ) -> dict[str, Any]:
1865
+ if self.sign_only:
1866
+ raise WalletBackendError("wdk_evm_local is configured as sign_only.")
1867
+ data = await self.client.post(
1868
+ "/v1/evm/swap/send",
1869
+ {
1870
+ "walletId": self.wallet_id,
1871
+ "accountIndex": self.account_index,
1872
+ "network": self.network,
1873
+ "tokenIn": token_in,
1874
+ "tokenOut": token_out,
1875
+ "tokenInAmount": amount_in_raw,
1876
+ **(
1877
+ {"expectedQuoteFingerprint": expected_quote_fingerprint}
1878
+ if isinstance(expected_quote_fingerprint, str) and expected_quote_fingerprint.strip()
1879
+ else {}
1880
+ ),
1881
+ **(
1882
+ {"minimumTokenOutAmount": minimum_output_amount_raw}
1883
+ if isinstance(minimum_output_amount_raw, str) and minimum_output_amount_raw.strip()
1884
+ else {}
1885
+ ),
1886
+ },
1887
+ )
1888
+ result = dict(data.get("result") or {})
1889
+ return {
1890
+ "chain": self.chain,
1891
+ "network": self.network,
1892
+ "asset_type": "evm-swap",
1893
+ "asset": "ERC20",
1894
+ "wallet": self.wallet_id,
1895
+ "from_address": await self.get_address(),
1896
+ "token_in": str((data.get("swapRequest") or {}).get("tokenIn") or token_in),
1897
+ "token_out": str((data.get("swapRequest") or {}).get("tokenOut") or token_out),
1898
+ "input_amount_raw": str((data.get("swapRequest") or {}).get("tokenInAmount") or amount_in_raw),
1899
+ "input_amount_ui": str(data.get("inputAmountFormatted")) if data.get("inputAmountFormatted") is not None else None,
1900
+ "output_amount_raw": str(result.get("tokenOutAmount") or "0"),
1901
+ "estimated_output_amount_raw": str(result.get("tokenOutAmount") or "0"),
1902
+ "estimated_output_amount_ui": (
1903
+ str(data.get("outputAmountFormatted")) if data.get("outputAmountFormatted") is not None else None
1904
+ ),
1905
+ "estimated_fee_wei": str(data.get("estimatedFeeWei") or result.get("fee") or "0"),
1906
+ "estimated_swap_fee_wei": str(data.get("estimatedSwapFeeWei") or result.get("swapFee") or "0"),
1907
+ "estimated_approval_fee_wei": str(data.get("estimatedApprovalFeeWei") or result.get("approvalFee") or "0"),
1908
+ "slippage_bps": int(data.get("slippageBps") or 0) if data.get("slippageBps") is not None else None,
1909
+ "minimum_output_amount_raw": (
1910
+ str(data.get("minimumOutputAmountRaw"))
1911
+ if data.get("minimumOutputAmountRaw") is not None
1912
+ else None
1913
+ ),
1914
+ "swap_provider": str(data.get("protocol") or "velora"),
1915
+ "quote_fingerprint": str(data.get("quoteFingerprint") or "").strip() or None,
1916
+ "router": str(data.get("router") or "").strip() or None,
1917
+ "allowance": _normalize_swap_allowance(data.get("allowance")),
1918
+ "simulation": _normalize_swap_simulation(data.get("simulation")),
1919
+ "swap_transaction": {
1920
+ "to": str((data.get("swapTransaction") or {}).get("to") or "").strip() or None,
1921
+ "value": str((data.get("swapTransaction") or {}).get("value") or "0"),
1922
+ "data_hash": str((data.get("swapTransaction") or {}).get("dataHash") or "").strip() or None,
1923
+ },
1924
+ "token_in_metadata": _normalize_token_metadata(
1925
+ data.get("tokenInMetadata"),
1926
+ str((data.get("swapRequest") or {}).get("tokenIn") or token_in),
1927
+ ),
1928
+ "token_out_metadata": _normalize_token_metadata(
1929
+ data.get("tokenOutMetadata"),
1930
+ str((data.get("swapRequest") or {}).get("tokenOut") or token_out),
1931
+ ),
1932
+ "hash": result.get("hash"),
1933
+ "approve_hash": result.get("approveHash"),
1934
+ "reset_allowance_hash": result.get("resetAllowanceHash"),
1935
+ "result": result,
1936
+ "chain_id": int(data.get("chainId") or 0),
1937
+ "broadcasted": True,
1938
+ "confirmed": bool(data.get("confirmed")),
1939
+ "confirmation_status": data.get("confirmation_status"),
1940
+ "tx_hash": data.get("tx_hash"),
1941
+ "source": "wdk-evm-wallet",
1942
+ }
1943
+
1944
+ def _normalize_uniswap_quote_payload(self, data: dict[str, Any], token_in: str, token_out: str, amount_in_raw: str) -> dict[str, Any]:
1945
+ return {
1946
+ "chain": self.chain,
1947
+ "network": self.network,
1948
+ "address": str(data.get("address") or ""),
1949
+ "token_in": str(data.get("tokenIn") or token_in),
1950
+ "token_out": str(data.get("tokenOut") or token_out),
1951
+ "amount_in_raw": str(data.get("tokenInAmount") or amount_in_raw),
1952
+ "amount_in_ui": str(data.get("inputAmountFormatted")) if data.get("inputAmountFormatted") is not None else None,
1953
+ "estimated_output_amount_raw": str(data.get("outputAmount") or "0"),
1954
+ "estimated_output_amount_ui": str(data.get("outputAmountFormatted")) if data.get("outputAmountFormatted") is not None else None,
1955
+ "minimum_output_amount_raw": str(data.get("minimumOutputAmountRaw")) if data.get("minimumOutputAmountRaw") is not None else None,
1956
+ "slippage_bps": int(data.get("slippageBps")) if data.get("slippageBps") is not None else None,
1957
+ "protocol": str(data.get("protocol") or "uniswap"),
1958
+ "routing": str(data.get("routing") or "CLASSIC"),
1959
+ "execution_kind": str(data.get("executionKind") or "classic"),
1960
+ "permit_required": bool(data.get("permitRequired")),
1961
+ "allowance": _normalize_swap_allowance(data.get("allowance")),
1962
+ "router": str(data.get("router") or "").strip() or None,
1963
+ "quote_fingerprint": str(data.get("quoteFingerprint") or "").strip() or None,
1964
+ "gas_fee_usd": str(data.get("gasFeeUSD")) if data.get("gasFeeUSD") is not None else None,
1965
+ "estimated_fee_wei": str(data.get("estimatedFeeWei")) if data.get("estimatedFeeWei") is not None else None,
1966
+ "execution_supported": bool(data.get("executionSupported")) and not self.sign_only,
1967
+ "token_in_metadata": _normalize_token_metadata(data.get("tokenInMetadata"), token_in),
1968
+ "token_out_metadata": _normalize_token_metadata(data.get("tokenOutMetadata"), token_out),
1969
+ "chain_id": int(data.get("chainId") or 0),
1970
+ "source": str(data.get("source") or "wdk-evm-wallet"),
1971
+ }
1972
+
1973
+ async def get_uniswap_swap_quote(
1974
+ self,
1975
+ *,
1976
+ token_in: str,
1977
+ token_out: str,
1978
+ amount_in_raw: str,
1979
+ slippage_bps: int | None = None,
1980
+ ) -> dict[str, Any]:
1981
+ resolved_address = await self.get_address()
1982
+ body: dict[str, Any] = {
1983
+ "walletId": self.wallet_id,
1984
+ "address": resolved_address,
1985
+ "accountIndex": self.account_index,
1986
+ "network": self.network,
1987
+ "tokenIn": token_in,
1988
+ "tokenOut": token_out,
1989
+ "tokenInAmount": amount_in_raw,
1990
+ }
1991
+ if slippage_bps is not None:
1992
+ body["slippageBps"] = slippage_bps
1993
+ data = await self.client.post("/v1/evm/uniswap/swap/quote", body)
1994
+ return self._normalize_uniswap_quote_payload(data, token_in, token_out, amount_in_raw)
1995
+
1996
+ async def preview_uniswap_swap(
1997
+ self,
1998
+ *,
1999
+ token_in: str,
2000
+ token_out: str,
2001
+ amount_in_raw: str,
2002
+ slippage_bps: int | None = None,
2003
+ ) -> dict[str, Any]:
2004
+ resolved_address = await self.get_address()
2005
+ body: dict[str, Any] = {
2006
+ "walletId": self.wallet_id,
2007
+ "address": resolved_address,
2008
+ "accountIndex": self.account_index,
2009
+ "network": self.network,
2010
+ "tokenIn": token_in,
2011
+ "tokenOut": token_out,
2012
+ "tokenInAmount": amount_in_raw,
2013
+ }
2014
+ if slippage_bps is not None:
2015
+ body["slippageBps"] = slippage_bps
2016
+ data = await self.client.post("/v1/evm/uniswap/swap/quote", body)
2017
+ payload = self._normalize_uniswap_quote_payload(data, token_in, token_out, amount_in_raw)
2018
+ prepared_transaction = data.get("swapTransaction")
2019
+ if isinstance(prepared_transaction, dict):
2020
+ swap_transaction = {
2021
+ "to": str(prepared_transaction.get("to") or "").strip() or payload["router"],
2022
+ "value": str(prepared_transaction.get("value") or "0"),
2023
+ "data_hash": str(prepared_transaction.get("dataHash") or "").strip() or None,
2024
+ }
2025
+ else:
2026
+ swap_transaction = {
2027
+ "to": payload["router"],
2028
+ "value": "0",
2029
+ "data_hash": None,
2030
+ }
2031
+ return {
2032
+ **payload,
2033
+ "asset_type": "evm-uniswap-swap",
2034
+ "asset": "ERC20",
2035
+ "wallet": self.wallet_id,
2036
+ "from_address": resolved_address,
2037
+ "input_amount_raw": payload["amount_in_raw"],
2038
+ "input_amount_ui": payload["amount_in_ui"],
2039
+ "swap_provider": payload["protocol"],
2040
+ "route_plan": None,
2041
+ "swap_transaction": swap_transaction,
2042
+ }
2043
+
2044
+ async def search_uniswap_pairs(
2045
+ self,
2046
+ *,
2047
+ query: str | None = None,
2048
+ token_address: str | None = None,
2049
+ chain: str | None = None,
2050
+ dex_id: str | None = None,
2051
+ all_chains: bool = False,
2052
+ limit: int = 10,
2053
+ ) -> dict[str, Any]:
2054
+ query = query.strip() if isinstance(query, str) else None
2055
+ token_address = token_address.strip() if isinstance(token_address, str) else None
2056
+ if not query and not token_address:
2057
+ raise WalletBackendError("Either query or token_address is required.")
2058
+ resolved_chain = (chain or self.network).strip().lower()
2059
+ canonical_stocks: dict[str, Any] | None = None
2060
+ if query and not all_chains and tokenized_stocks.is_supported_network(resolved_chain):
2061
+ try:
2062
+ canonical_stocks = await tokenized_stocks.find_tokenized_stocks(
2063
+ query, network=resolved_chain, limit=3
2064
+ )
2065
+ except ProviderError:
2066
+ canonical_stocks = None
2067
+ if token_address:
2068
+ pairs = await dexscreener.get_pairs_for_token(chain=resolved_chain, token_address=token_address)
2069
+ else:
2070
+ pairs = await dexscreener.search_pairs(query)
2071
+ if not all_chains:
2072
+ pairs = _filter_pairs_to_chain(pairs, resolved_chain)
2073
+ if not pairs:
2074
+ # DexScreener search returns at most ~30 pairs across *all* chains, so
2075
+ # a chain's results are often cut before this filter; a chain-qualified
2076
+ # query surfaces them.
2077
+ pairs = _filter_pairs_to_chain(
2078
+ await dexscreener.search_pairs(f"{query} {resolved_chain}"), resolved_chain
2079
+ )
2080
+ exact_stock = _first_exact_stock(canonical_stocks)
2081
+ if exact_stock is not None:
2082
+ canonical_address = exact_stock["address"].lower()
2083
+ if not any(_pair_has_token(pair, canonical_address) for pair in pairs):
2084
+ pairs = (
2085
+ await dexscreener.get_pairs_for_token(
2086
+ chain=resolved_chain, token_address=exact_stock["address"]
2087
+ )
2088
+ + pairs
2089
+ )
2090
+ if dex_id:
2091
+ wanted_dex = dex_id.strip().lower()
2092
+ pairs = [p for p in pairs if str(p.get("dexId") or "").lower() == wanted_dex]
2093
+ bounded_limit = max(1, min(int(limit or 10), 30))
2094
+ normalized = [dexscreener.normalize_pair(pair) for pair in pairs[:bounded_limit]]
2095
+ canonical_addresses: set[str] = set()
2096
+ if tokenized_stocks.is_supported_network(resolved_chain) and not all_chains:
2097
+ try:
2098
+ canonical_addresses = await tokenized_stocks.canonical_address_set(resolved_chain)
2099
+ except ProviderError:
2100
+ canonical_addresses = set()
2101
+ if canonical_addresses:
2102
+ for pair in normalized:
2103
+ for side in ("base_token", "quote_token"):
2104
+ token = pair.get(side) or {}
2105
+ token["canonical_tokenized_stock"] = (
2106
+ str(token.get("address") or "").lower() in canonical_addresses
2107
+ )
2108
+ result: dict[str, Any] = {
2109
+ "chain": None if all_chains else resolved_chain,
2110
+ "all_chains": all_chains,
2111
+ "query": query,
2112
+ "token_address": token_address,
2113
+ "dex_id": dex_id,
2114
+ "count": len(normalized),
2115
+ "pairs": normalized,
2116
+ "source": "dexscreener",
2117
+ }
2118
+ if _first_exact_stock(canonical_stocks) is not None:
2119
+ result["canonical_tokenized_stocks"] = canonical_stocks
2120
+ result["hint"] = (
2121
+ "This query matches the issuer's canonical tokenized-stock registry. Use the "
2122
+ "canonical address from canonical_tokenized_stocks, not a ticker match; pairs "
2123
+ "whose token has canonical_tokenized_stock=false are not issued by that issuer."
2124
+ )
2125
+ return result
2126
+
2127
+ async def get_evm_tokenized_stock(
2128
+ self,
2129
+ *,
2130
+ query: str,
2131
+ network: str | None = None,
2132
+ limit: int = 5,
2133
+ ) -> dict[str, Any]:
2134
+ resolved_network = (network or self.network).strip().lower()
2135
+ try:
2136
+ data = await tokenized_stocks.find_tokenized_stocks(query, network=resolved_network, limit=limit)
2137
+ except ProviderError as exc:
2138
+ raise WalletBackendError(str(exc)) from exc
2139
+ exact = _first_exact_stock(data)
2140
+ if exact is not None:
2141
+ try:
2142
+ pairs = await dexscreener.get_pairs_for_token(
2143
+ chain=resolved_network, token_address=exact["address"]
2144
+ )
2145
+ except ProviderError:
2146
+ pairs = []
2147
+ venues = sorted(
2148
+ (dexscreener.normalize_pair(pair) for pair in pairs),
2149
+ key=lambda pair: float(pair.get("liquidity_usd") or 0),
2150
+ reverse=True,
2151
+ )[:5]
2152
+ data["liquidity"] = {
2153
+ "source": "dexscreener",
2154
+ "total_liquidity_usd": round(sum(float(p.get("liquidity_usd") or 0) for p in venues), 2),
2155
+ "top_venues": [
2156
+ {
2157
+ "dex_id": p.get("dex_id"),
2158
+ "labels": p.get("labels"),
2159
+ "pair_address": p.get("pair_address"),
2160
+ "pair": f"{(p.get('base_token') or {}).get('symbol')}/{(p.get('quote_token') or {}).get('symbol')}",
2161
+ "price_usd": p.get("price_usd"),
2162
+ "liquidity_usd": p.get("liquidity_usd"),
2163
+ "volume_24h_usd": (p.get("volume_usd") or {}).get("h24"),
2164
+ }
2165
+ for p in venues
2166
+ ],
2167
+ }
2168
+ usdc = _BASE_USDC if resolved_network == "base" else None
2169
+ data["next_step"] = {
2170
+ "tool": "get_evm_swap_quote",
2171
+ "description": (
2172
+ "Ask the user for the amount and funding asset if not given, then quote "
2173
+ f"token_in=<funding asset> -> token_out={exact['address']} on {resolved_network} "
2174
+ "(Velora aggregates Aerodrome and Uniswap pools; get_uniswap_swap_quote is the "
2175
+ "alternative). Show the quote and wait for explicit confirmation before swapping."
2176
+ ),
2177
+ "token_out": exact["address"],
2178
+ "token_out_decimals": exact.get("decimals"),
2179
+ "suggested_token_in": usdc,
2180
+ }
2181
+ elif not data.get("matches"):
2182
+ data["hint"] = (
2183
+ "No canonical tokenized stock matched. Do not substitute a DEX search hit or another "
2184
+ "issuer's token without telling the user it is a different product."
2185
+ )
2186
+ return data
2187
+
2188
+ async def get_uniswap_liquidity_pools(
2189
+ self,
2190
+ *,
2191
+ protocol: str,
2192
+ pool_parameters: dict[str, Any] | None = None,
2193
+ pool_references: list[dict[str, Any]] | None = None,
2194
+ page_size: int = 20,
2195
+ current_page: int = 1,
2196
+ ) -> dict[str, Any]:
2197
+ if protocol not in {"V3", "V4"}:
2198
+ raise WalletBackendError("protocol must be V3 or V4.")
2199
+ if (pool_parameters is None) == (pool_references is None):
2200
+ raise WalletBackendError("Provide exactly one of pool_parameters or pool_references.")
2201
+ if pool_parameters is not None and not isinstance(pool_parameters, dict):
2202
+ raise WalletBackendError("pool_parameters must be an object.")
2203
+ if pool_references is not None:
2204
+ if not isinstance(pool_references, list) or not 1 <= len(pool_references) <= 20:
2205
+ raise WalletBackendError("pool_references must contain between 1 and 20 objects.")
2206
+ if any(not isinstance(reference, dict) for reference in pool_references):
2207
+ raise WalletBackendError("pool_references must contain only objects.")
2208
+ if not isinstance(page_size, int) or not 1 <= page_size <= 20:
2209
+ raise WalletBackendError("page_size must be an integer between 1 and 20.")
2210
+ if not isinstance(current_page, int) or current_page < 1:
2211
+ raise WalletBackendError("current_page must be a positive integer.")
2212
+ body: dict[str, Any] = {
2213
+ "network": self.network,
2214
+ "protocol": protocol,
2215
+ "pageSize": page_size,
2216
+ "currentPage": current_page,
2217
+ }
2218
+ if pool_parameters is not None:
2219
+ body["poolParameters"] = pool_parameters
2220
+ else:
2221
+ body["poolReferences"] = pool_references
2222
+ data = await self.client.post("/v1/evm/uniswap/liquidity/pools", body)
2223
+ return dict(data)
2224
+
2225
+ async def get_uniswap_liquidity_positions(
2226
+ self,
2227
+ *,
2228
+ protocol: str = "V3",
2229
+ limit: int = 20,
2230
+ ) -> dict[str, Any]:
2231
+ if protocol not in {"V3", "V4"}:
2232
+ raise WalletBackendError("protocol must be V3 or V4.")
2233
+ if not isinstance(limit, int) or not 1 <= limit <= 100:
2234
+ raise WalletBackendError("limit must be an integer between 1 and 100.")
2235
+ data = await self.client.post(
2236
+ "/v1/evm/uniswap/liquidity/positions",
2237
+ {
2238
+ "walletId": self.wallet_id,
2239
+ "address": await self.get_address(),
2240
+ "accountIndex": self.account_index,
2241
+ "network": self.network,
2242
+ "protocol": protocol,
2243
+ "limit": limit,
2244
+ },
2245
+ )
2246
+ return dict(data)
2247
+
2248
+ async def send_uniswap_swap(
2249
+ self,
2250
+ *,
2251
+ token_in: str,
2252
+ token_out: str,
2253
+ amount_in_raw: str,
2254
+ slippage_bps: int | None = None,
2255
+ expected_quote_fingerprint: str | None = None,
2256
+ minimum_output_amount_raw: str | None = None,
2257
+ ) -> dict[str, Any]:
2258
+ if self.sign_only:
2259
+ raise WalletBackendError("wdk_evm_local is configured as sign_only.")
2260
+ body: dict[str, Any] = {
2261
+ "walletId": self.wallet_id,
2262
+ "accountIndex": self.account_index,
2263
+ "network": self.network,
2264
+ "tokenIn": token_in,
2265
+ "tokenOut": token_out,
2266
+ "tokenInAmount": amount_in_raw,
2267
+ }
2268
+ if slippage_bps is not None:
2269
+ body["slippageBps"] = slippage_bps
2270
+ if isinstance(expected_quote_fingerprint, str) and expected_quote_fingerprint.strip():
2271
+ body["expectedQuoteFingerprint"] = expected_quote_fingerprint.strip()
2272
+ if isinstance(minimum_output_amount_raw, str) and minimum_output_amount_raw.strip():
2273
+ body["minimumTokenOutAmount"] = minimum_output_amount_raw.strip()
2274
+ data = await self.client.post("/v1/evm/uniswap/swap/send", body)
2275
+ result = dict(data.get("result") or {})
2276
+ order_id = str(result.get("orderId") or "").strip() or None
2277
+ return {
2278
+ "chain": self.chain,
2279
+ "network": self.network,
2280
+ "asset_type": "evm-uniswap-swap",
2281
+ "asset": "ERC20",
2282
+ "wallet": self.wallet_id,
2283
+ "from_address": await self.get_address(),
2284
+ "token_in": str(data.get("tokenIn") or token_in),
2285
+ "token_out": str(data.get("tokenOut") or token_out),
2286
+ "input_amount_raw": str(data.get("tokenInAmount") or amount_in_raw),
2287
+ "input_amount_ui": str(data.get("inputAmountFormatted")) if data.get("inputAmountFormatted") is not None else None,
2288
+ "estimated_output_amount_raw": str(data.get("outputAmount") or "0"),
2289
+ "estimated_output_amount_ui": str(data.get("outputAmountFormatted")) if data.get("outputAmountFormatted") is not None else None,
2290
+ "slippage_bps": int(data.get("slippageBps")) if data.get("slippageBps") is not None else None,
2291
+ "minimum_output_amount_raw": str(data.get("minimumOutputAmountRaw")) if data.get("minimumOutputAmountRaw") is not None else None,
2292
+ "swap_provider": str(data.get("protocol") or "uniswap"),
2293
+ "routing": str(data.get("routing") or "CLASSIC"),
2294
+ "execution_kind": str(data.get("executionKind") or "classic"),
2295
+ "quote_fingerprint": str(data.get("quoteFingerprint") or "").strip() or None,
2296
+ "router": str(data.get("router") or "").strip() or None,
2297
+ "allowance": _normalize_swap_allowance(data.get("allowance")),
2298
+ "simulation": _normalize_swap_simulation(data.get("simulation")),
2299
+ "swap_transaction": {
2300
+ "to": str((data.get("swapTransaction") or {}).get("to") or "").strip() or None,
2301
+ "value": str((data.get("swapTransaction") or {}).get("value") or "0"),
2302
+ "data_hash": str((data.get("swapTransaction") or {}).get("dataHash") or "").strip() or None,
2303
+ },
2304
+ "token_in_metadata": _normalize_token_metadata(data.get("tokenInMetadata"), token_in),
2305
+ "token_out_metadata": _normalize_token_metadata(data.get("tokenOutMetadata"), token_out),
2306
+ "hash": result.get("hash"),
2307
+ "order_id": order_id,
2308
+ "order_status": str(result.get("orderStatus") or "").strip() or None,
2309
+ "approve_hash": result.get("approveHash"),
2310
+ "reset_allowance_hash": result.get("resetAllowanceHash"),
2311
+ "result": result,
2312
+ "chain_id": int(data.get("chainId") or 0),
2313
+ "broadcasted": bool(result.get("hash")),
2314
+ "order_submitted": order_id is not None,
2315
+ "confirmed": bool(data.get("confirmed")),
2316
+ "confirmation_status": data.get("confirmation_status"),
2317
+ "tx_hash": data.get("tx_hash"),
2318
+ "source": str(data.get("source") or "wdk-evm-wallet"),
2319
+ }
2320
+
2321
+ def _normalize_uniswap_liquidity_payload(
2322
+ self,
2323
+ data: dict[str, Any],
2324
+ *,
2325
+ action: str,
2326
+ protocol: str,
2327
+ ) -> dict[str, Any]:
2328
+ transaction = dict(data.get("transaction") or {})
2329
+ result = dict(data.get("result") or {})
2330
+ request = dict(data.get("request") or {})
2331
+ return {
2332
+ "chain": self.chain,
2333
+ "network": self.network,
2334
+ "asset_type": "evm-uniswap-liquidity",
2335
+ "protocol": str(data.get("protocol") or "uniswap"),
2336
+ "liquidity_action": str(data.get("liquidityAction") or action),
2337
+ "liquidity_protocol": str(data.get("liquidityProtocol") or protocol).upper(),
2338
+ "from_address": str(data.get("address") or "").strip() or None,
2339
+ "request": request,
2340
+ "request_id": str(data.get("requestId") or "").strip() or None,
2341
+ "token0": data.get("token0"),
2342
+ "token1": data.get("token1"),
2343
+ "tick_lower": data.get("tickLower"),
2344
+ "tick_upper": data.get("tickUpper"),
2345
+ "adjusted_min_price": data.get("adjustedMinPrice"),
2346
+ "adjusted_max_price": data.get("adjustedMaxPrice"),
2347
+ "position_token_id": str(data.get("positionTokenId") or "").strip() or None,
2348
+ "position_manager": str(data.get("positionManager") or "").strip() or None,
2349
+ "gas_fee": str(data.get("gasFee")) if data.get("gasFee") is not None else None,
2350
+ "approvals": list(data.get("approvals") or []),
2351
+ "approval_results": list(data.get("approvalResults") or []),
2352
+ "simulation": _normalize_swap_simulation(data.get("simulation")),
2353
+ "transaction": {
2354
+ "to": str(transaction.get("to") or "").strip() or None,
2355
+ "value": str(transaction.get("value") or "0"),
2356
+ "data_hash": str(transaction.get("dataHash") or "").strip() or None,
2357
+ },
2358
+ "hash": result.get("hash"),
2359
+ "result": result,
2360
+ "chain_id": int(data.get("chainId") or 0),
2361
+ "broadcasted": bool(result.get("hash")),
2362
+ "confirmed": bool(data.get("confirmed")),
2363
+ "confirmation_status": data.get("confirmation_status"),
2364
+ "tx_hash": data.get("tx_hash"),
2365
+ "source": str(data.get("source") or "wdk-evm-wallet"),
2366
+ }
2367
+
2368
+ async def preview_uniswap_liquidity(
2369
+ self,
2370
+ *,
2371
+ action: str,
2372
+ protocol: str,
2373
+ request: dict[str, Any],
2374
+ ) -> dict[str, Any]:
2375
+ if not isinstance(request, dict):
2376
+ raise WalletBackendError("Uniswap liquidity request must be an object.")
2377
+ data = await self.client.post(
2378
+ "/v1/evm/uniswap/liquidity/quote",
2379
+ {
2380
+ "walletId": self.wallet_id,
2381
+ "address": await self.get_address(),
2382
+ "accountIndex": self.account_index,
2383
+ "network": self.network,
2384
+ "action": action,
2385
+ "protocol": protocol,
2386
+ "request": request,
2387
+ },
2388
+ )
2389
+ normalized = self._normalize_uniswap_liquidity_payload(data, action=action, protocol=protocol)
2390
+ normalized["from_address"] = await self.get_address()
2391
+ normalized["execution_supported"] = not self.sign_only
2392
+ return normalized
2393
+
2394
+ async def send_uniswap_liquidity(
2395
+ self,
2396
+ *,
2397
+ action: str,
2398
+ protocol: str,
2399
+ request: dict[str, Any],
2400
+ ) -> dict[str, Any]:
2401
+ if self.sign_only:
2402
+ raise WalletBackendError("wdk_evm_local is configured as sign_only.")
2403
+ if not isinstance(request, dict):
2404
+ raise WalletBackendError("Uniswap liquidity request must be an object.")
2405
+ data = await self.client.post(
2406
+ "/v1/evm/uniswap/liquidity/send",
2407
+ {
2408
+ "walletId": self.wallet_id,
2409
+ "accountIndex": self.account_index,
2410
+ "network": self.network,
2411
+ "action": action,
2412
+ "protocol": protocol,
2413
+ "request": request,
2414
+ },
2415
+ )
2416
+ normalized = self._normalize_uniswap_liquidity_payload(data, action=action, protocol=protocol)
2417
+ normalized["from_address"] = await self.get_address()
2418
+ return normalized
2419
+
2420
+ async def preview_evm_lifi_cross_chain_swap(
2421
+ self,
2422
+ *,
2423
+ token_in: str,
2424
+ destination_chain: str,
2425
+ output_token: str,
2426
+ destination_address: str,
2427
+ amount_in_raw: str,
2428
+ slippage: float | int | None = None,
2429
+ allow_bridges: list[str] | None = None,
2430
+ deny_bridges: list[str] | None = None,
2431
+ prefer_bridges: list[str] | None = None,
2432
+ ) -> dict[str, Any]:
2433
+ resolved_address = await self.get_address()
2434
+ data = await self.client.post(
2435
+ "/v1/evm/lifi/quote",
2436
+ {
2437
+ "walletId": self.wallet_id,
2438
+ "address": resolved_address,
2439
+ "accountIndex": self.account_index,
2440
+ "network": self.network,
2441
+ "tokenIn": token_in,
2442
+ "destinationChain": destination_chain,
2443
+ "outputToken": output_token,
2444
+ "destinationAddress": destination_address,
2445
+ "tokenInAmount": amount_in_raw,
2446
+ **({"slippage": slippage} if slippage is not None else {}),
2447
+ **({"allowBridges": allow_bridges} if allow_bridges is not None else {}),
2448
+ **({"denyBridges": deny_bridges} if deny_bridges is not None else {}),
2449
+ **({"preferBridges": prefer_bridges} if prefer_bridges is not None else {}),
2450
+ },
2451
+ )
2452
+ data.setdefault("address", resolved_address)
2453
+ return _normalize_lifi_cross_chain_payload(
2454
+ chain=self.chain,
2455
+ network=self.network,
2456
+ wallet_id=self.wallet_id,
2457
+ data=data,
2458
+ token_in=token_in,
2459
+ destination_chain=destination_chain,
2460
+ output_token=output_token,
2461
+ destination_address=destination_address,
2462
+ amount_in_raw=amount_in_raw,
2463
+ slippage=slippage,
2464
+ sign_only=self.sign_only,
2465
+ )
2466
+
2467
+ async def send_evm_lifi_cross_chain_swap(
2468
+ self,
2469
+ *,
2470
+ token_in: str,
2471
+ destination_chain: str,
2472
+ output_token: str,
2473
+ destination_address: str,
2474
+ amount_in_raw: str,
2475
+ slippage: float | int | None = None,
2476
+ allow_bridges: list[str] | None = None,
2477
+ deny_bridges: list[str] | None = None,
2478
+ prefer_bridges: list[str] | None = None,
2479
+ minimum_output_amount_raw: str | None = None,
2480
+ ) -> dict[str, Any]:
2481
+ if self.sign_only:
2482
+ raise WalletBackendError("wdk_evm_local is configured as sign_only.")
2483
+ data = await self.client.post(
2484
+ "/v1/evm/lifi/send",
2485
+ {
2486
+ "walletId": self.wallet_id,
2487
+ "accountIndex": self.account_index,
2488
+ "network": self.network,
2489
+ "tokenIn": token_in,
2490
+ "destinationChain": destination_chain,
2491
+ "outputToken": output_token,
2492
+ "destinationAddress": destination_address,
2493
+ "tokenInAmount": amount_in_raw,
2494
+ **({"slippage": slippage} if slippage is not None else {}),
2495
+ **({"allowBridges": allow_bridges} if allow_bridges is not None else {}),
2496
+ **({"denyBridges": deny_bridges} if deny_bridges is not None else {}),
2497
+ **({"preferBridges": prefer_bridges} if prefer_bridges is not None else {}),
2498
+ **(
2499
+ {"minimumTokenOutAmount": minimum_output_amount_raw}
2500
+ if isinstance(minimum_output_amount_raw, str) and minimum_output_amount_raw.strip()
2501
+ else {}
2502
+ ),
2503
+ },
2504
+ )
2505
+ result = dict(data.get("result") or {})
2506
+ data.setdefault("address", await self.get_address())
2507
+ shaped = _normalize_lifi_cross_chain_payload(
2508
+ chain=self.chain,
2509
+ network=self.network,
2510
+ wallet_id=self.wallet_id,
2511
+ data=data,
2512
+ token_in=token_in,
2513
+ destination_chain=destination_chain,
2514
+ output_token=output_token,
2515
+ destination_address=destination_address,
2516
+ amount_in_raw=amount_in_raw,
2517
+ slippage=slippage,
2518
+ sign_only=self.sign_only,
2519
+ )
2520
+ return {
2521
+ **shaped,
2522
+ "output_amount_raw": str(result.get("tokenOutAmount") or shaped.get("estimated_output_amount_raw") or "0"),
2523
+ "estimated_fee_wei": str(data.get("estimatedFeeWei") or result.get("fee") or shaped.get("estimated_fee_wei") or "0"),
2524
+ "estimated_swap_fee_wei": str(data.get("estimatedSwapFeeWei") or result.get("swapFee") or shaped.get("estimated_swap_fee_wei") or "0"),
2525
+ "estimated_approval_fee_wei": str(data.get("estimatedApprovalFeeWei") or result.get("approvalFee") or shaped.get("estimated_approval_fee_wei") or "0"),
2526
+ "hash": result.get("hash"),
2527
+ "approve_hash": result.get("approveHash"),
2528
+ "reset_allowance_hash": result.get("resetAllowanceHash"),
2529
+ "result": result,
2530
+ "broadcasted": True,
2531
+ "confirmed": bool(data.get("confirmed")),
2532
+ "confirmation_status": data.get("confirmation_status"),
2533
+ "tx_hash": data.get("tx_hash"),
2534
+ }
2535
+
2536
+ async def preview_evm_native_transfer(
2537
+ self,
2538
+ *,
2539
+ recipient: str,
2540
+ amount_wei: str,
2541
+ ) -> dict[str, Any]:
2542
+ data = await self.client.post(
2543
+ "/v1/evm/transfer/quote",
2544
+ {
2545
+ "walletId": self.wallet_id,
2546
+ "accountIndex": self.account_index,
2547
+ "network": self.network,
2548
+ "to": recipient,
2549
+ "value": amount_wei,
2550
+ },
2551
+ )
2552
+ quote = dict(data.get("quote") or {})
2553
+ return {
2554
+ "chain": self.chain,
2555
+ "network": self.network,
2556
+ "asset_type": "evm-native-transfer",
2557
+ "asset": "ETH",
2558
+ "wallet": self.wallet_id,
2559
+ "from_address": await self.get_address(),
2560
+ "recipient": recipient,
2561
+ "amount_wei": str(amount_wei),
2562
+ "estimated_fee_wei": _extract_fee_wei(quote),
2563
+ "quote": quote,
2564
+ "chain_id": int(data.get("chainId") or 0),
2565
+ "source": "wdk-evm-wallet",
2566
+ }
2567
+
2568
+ async def send_evm_native_transfer(
2569
+ self,
2570
+ *,
2571
+ recipient: str,
2572
+ amount_wei: str,
2573
+ ) -> dict[str, Any]:
2574
+ if self.sign_only:
2575
+ raise WalletBackendError("wdk_evm_local is configured as sign_only.")
2576
+ data = await self.client.post(
2577
+ "/v1/evm/transfer/send",
2578
+ {
2579
+ "walletId": self.wallet_id,
2580
+ "accountIndex": self.account_index,
2581
+ "network": self.network,
2582
+ "to": recipient,
2583
+ "value": amount_wei,
2584
+ },
2585
+ )
2586
+ result = dict(data.get("result") or {})
2587
+ return {
2588
+ "chain": self.chain,
2589
+ "network": self.network,
2590
+ "asset_type": "evm-native-transfer",
2591
+ "asset": "ETH",
2592
+ "wallet": self.wallet_id,
2593
+ "from_address": await self.get_address(),
2594
+ "recipient": recipient,
2595
+ "amount_wei": str(amount_wei),
2596
+ "estimated_fee_wei": _extract_fee_wei(result),
2597
+ "hash": result.get("hash"),
2598
+ "result": result,
2599
+ "chain_id": int(data.get("chainId") or 0),
2600
+ "broadcasted": True,
2601
+ "confirmed": bool(data.get("confirmed")),
2602
+ "confirmation_status": data.get("confirmation_status"),
2603
+ "tx_hash": data.get("tx_hash"),
2604
+ # The daemon puts duplicate_warning at the top level for native and
2605
+ # token transfers (unlike the buffered-defi family, where it rides
2606
+ # inside `result`), so it has to be forwarded explicitly here.
2607
+ "duplicate_warning": data.get("duplicate_warning"),
2608
+ "source": "wdk-evm-wallet",
2609
+ }
2610
+
2611
+ async def preview_evm_token_transfer(
2612
+ self,
2613
+ *,
2614
+ token_address: str,
2615
+ recipient: str,
2616
+ amount_raw: str,
2617
+ ) -> dict[str, Any]:
2618
+ data = await self.client.post(
2619
+ "/v1/evm/token-transfer/quote",
2620
+ {
2621
+ "walletId": self.wallet_id,
2622
+ "accountIndex": self.account_index,
2623
+ "network": self.network,
2624
+ "tokenAddress": token_address,
2625
+ "recipient": recipient,
2626
+ "amount": amount_raw,
2627
+ },
2628
+ )
2629
+ quote = dict(data.get("quote") or {})
2630
+ return {
2631
+ "chain": self.chain,
2632
+ "network": self.network,
2633
+ "asset_type": "evm-token-transfer",
2634
+ "wallet": self.wallet_id,
2635
+ "from_address": await self.get_address(),
2636
+ "recipient": recipient,
2637
+ "token_address": token_address,
2638
+ "amount_raw": str(amount_raw),
2639
+ "amount_ui": str(data.get("amountFormatted")) if data.get("amountFormatted") is not None else None,
2640
+ "estimated_fee_wei": _extract_fee_wei(quote),
2641
+ "token_metadata": _normalize_token_metadata(data.get("tokenMetadata"), token_address),
2642
+ "quote": quote,
2643
+ "chain_id": int(data.get("chainId") or 0),
2644
+ "source": "wdk-evm-wallet",
2645
+ }
2646
+
2647
+ async def send_evm_token_transfer(
2648
+ self,
2649
+ *,
2650
+ token_address: str,
2651
+ recipient: str,
2652
+ amount_raw: str,
2653
+ ) -> dict[str, Any]:
2654
+ if self.sign_only:
2655
+ raise WalletBackendError("wdk_evm_local is configured as sign_only.")
2656
+ data = await self.client.post(
2657
+ "/v1/evm/token-transfer/send",
2658
+ {
2659
+ "walletId": self.wallet_id,
2660
+ "accountIndex": self.account_index,
2661
+ "network": self.network,
2662
+ "tokenAddress": token_address,
2663
+ "recipient": recipient,
2664
+ "amount": amount_raw,
2665
+ },
2666
+ )
2667
+ result = dict(data.get("result") or {})
2668
+ return {
2669
+ "chain": self.chain,
2670
+ "network": self.network,
2671
+ "asset_type": "evm-token-transfer",
2672
+ "wallet": self.wallet_id,
2673
+ "from_address": await self.get_address(),
2674
+ "recipient": recipient,
2675
+ "token_address": token_address,
2676
+ "amount_raw": str(amount_raw),
2677
+ "amount_ui": str(data.get("amountFormatted")) if data.get("amountFormatted") is not None else None,
2678
+ "estimated_fee_wei": _extract_fee_wei(result),
2679
+ "token_metadata": _normalize_token_metadata(data.get("tokenMetadata"), token_address),
2680
+ "hash": result.get("hash"),
2681
+ "result": result,
2682
+ "chain_id": int(data.get("chainId") or 0),
2683
+ "broadcasted": True,
2684
+ "confirmed": bool(data.get("confirmed")),
2685
+ "confirmation_status": data.get("confirmation_status"),
2686
+ "tx_hash": data.get("tx_hash"),
2687
+ # Top-level on the daemon side, same as the native transfer above.
2688
+ "duplicate_warning": data.get("duplicate_warning"),
2689
+ "source": "wdk-evm-wallet",
2690
+ }
2691
+
2692
+ def get_capabilities(self) -> WalletCapabilities:
2693
+ return WalletCapabilities(
2694
+ backend=self.name,
2695
+ chain=self.chain,
2696
+ custody_model=self.custody_model,
2697
+ sign_only=self.sign_only,
2698
+ has_signer=True,
2699
+ can_get_address=True,
2700
+ can_get_balance=True,
2701
+ can_sign_message=False,
2702
+ can_sign_transaction=not self.sign_only,
2703
+ can_send_transaction=not self.sign_only,
2704
+ external_dependencies=["wdk-evm-wallet", "evm-rpc"],
2705
+ )