@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,8 @@
1
+ {
2
+ "name": "onecraft-hedera-treasury-guard",
3
+ "private": true,
4
+ "type": "module",
5
+ "dependencies": {
6
+ "@hiero-ledger/sdk": "2.91.0"
7
+ }
8
+ }
@@ -0,0 +1,22 @@
1
+ ---
2
+ name: onecraft-hedera-treasury
3
+ description: Preview or prepare policy-limited testnet HBAR top-ups with OneCraft Treasury Guard.
4
+ ---
5
+
6
+ # OneCraft Treasury Guard
7
+
8
+ Use `node bin/openclaw-agent-wallet.mjs hedera-treasury` from the OneCraft
9
+ checkout. Ask for the local policy path if the operator uses a custom location.
10
+ Each command below uses the CLI prefix above.
11
+
12
+ 1. Use `preview [--policy <path>] [--spend-units <integer>]` to check the
13
+ reserve against the configured target and inspect the quote. Amounts are
14
+ in SAUCE base units and HBAR tinybars.
15
+ 2. Report `hold` or a policy rejection. If the user requests preparation
16
+ after reviewing a `top_up` decision, run `prepare` with the same options.
17
+ Share the fresh plan ID, exact spend, minimum HBAR output, fee cap, and expiry.
18
+ 3. Give the operator the `execute <plan-id> [--policy <path>]` command to run
19
+ locally. Leave the approval and private-key prompts to the operator.
20
+ Never request keys in chat or automate the execution prompt.
21
+ 4. Use `status <plan-id>` for the saved result and HashScan URL. When a
22
+ submission is unconfirmed, report the URL so the operator can reconcile it.
@@ -0,0 +1,106 @@
1
+ import { lookup, resolve4 } from "node:dns/promises";
2
+ import { Agent, request as httpsRequest } from "node:https";
3
+ import { Readable } from "node:stream";
4
+ import { integer, ROUTER, TESTNET_SAUCE, WRAPPED_HBAR } from "./treasury-policy.mjs";
5
+
6
+ const MIRROR = "https://testnet.mirrornode.hedera.com";
7
+ const GET_AMOUNTS_OUT = "d06ca61f";
8
+
9
+ const mirrorAgent = new Agent({
10
+ keepAlive: true,
11
+ lookup(hostname, options, callback) {
12
+ // The public mirror can resolve via DNS when the system host lookup stalls.
13
+ const addresses = resolve4(hostname).then(ips => ips.map(address => ({ address, family: 4 })));
14
+ Promise.any([lookup(hostname, { all: true }), addresses]).then(results => {
15
+ if (options.all) callback(null, results);
16
+ else callback(null, results[0].address, results[0].family);
17
+ }, callback);
18
+ },
19
+ });
20
+
21
+ function fetchMirror(url, { method, headers, body, signal }) {
22
+ return new Promise((resolve, reject) => {
23
+ const req = httpsRequest(url, { agent: mirrorAgent, method, headers, signal }, res => {
24
+ const status = res.statusCode;
25
+ if (status !== 200) {
26
+ res.resume();
27
+ resolve({ ok: false, status });
28
+ return;
29
+ }
30
+ resolve(new Response(Readable.toWeb(res), { status }));
31
+ });
32
+ req.once("error", reject);
33
+ req.end(body);
34
+ });
35
+ }
36
+
37
+ const word = (number) => BigInt(number).toString(16).padStart(64, "0");
38
+
39
+ // These testnet entities all use shard 0 and realm 0.
40
+ export function evmEntity(id) {
41
+ return `0x${word(id.split(".")[2]).slice(-40)}`;
42
+ }
43
+
44
+ export function createMarket(fetchImpl = fetchMirror) {
45
+ async function request(path, body) {
46
+ let response;
47
+ try {
48
+ response = await fetchImpl(`${MIRROR}${path}`, {
49
+ method: body ? "POST" : "GET",
50
+ headers: body ? { "content-type": "application/json" } : undefined,
51
+ body: body ? JSON.stringify(body) : undefined,
52
+ signal: AbortSignal.timeout(10_000),
53
+ redirect: "error",
54
+ });
55
+ } catch {
56
+ throw new Error("The Hedera testnet mirror node could not be reached.");
57
+ }
58
+ if (!response.ok) throw new Error(`Hedera testnet mirror request failed (HTTP ${response.status}).`);
59
+ return response.json();
60
+ }
61
+
62
+ return {
63
+ async account(id) {
64
+ const account = await request(`/api/v1/accounts/${id}`);
65
+ if (account.account !== id || account.deleted !== false) throw new Error("Hedera testnet account is unavailable.");
66
+ return account;
67
+ },
68
+
69
+ async quote(spend) {
70
+ const path = [TESTNET_SAUCE, WRAPPED_HBAR].map(id => word(evmEntity(id)));
71
+ const data = `0x${GET_AMOUNTS_OUT}${word(spend)}${word(64)}${word(2)}${path.join("")}`;
72
+ const { result } = await request("/api/v1/contracts/call", {
73
+ to: evmEntity(ROUTER), data, estimate: false, block: "latest",
74
+ });
75
+ if (!/^0x[0-9a-f]{256}$/i.test(result ?? "")) throw new Error("Invalid SaucerSwap quote response.");
76
+ const words = result.slice(2).match(/.{64}/g).map(value => BigInt(`0x${value}`));
77
+ const [offset, length, amountIn, amountOut] = words;
78
+ if (offset !== 32n || length !== 2n || amountIn !== spend || amountOut <= 0n) {
79
+ throw new Error("SaucerSwap returned an inconsistent quote.");
80
+ }
81
+ return integer(amountOut.toString(), "Quoted output");
82
+ },
83
+
84
+ async availableInput(id) {
85
+ const [asset, tokenBalances, tokenAllowances] = await Promise.all([
86
+ request(`/api/v1/tokens/${TESTNET_SAUCE}`),
87
+ request(`/api/v1/accounts/${id}/tokens?token.id=${TESTNET_SAUCE}`),
88
+ request(`/api/v1/accounts/${id}/allowances/tokens?spender.id=${ROUTER}&token.id=${TESTNET_SAUCE}`),
89
+ ]);
90
+ const fees = asset.custom_fees;
91
+ if (asset.token_id !== TESTNET_SAUCE || asset.type !== "FUNGIBLE_COMMON" || asset.deleted !== false ||
92
+ Number(asset.decimals) !== 6 || asset.fee_schedule_key !== null ||
93
+ !["fixed_fees", "fractional_fees"].every(key => Array.isArray(fees?.[key]) && fees[key].length === 0) ||
94
+ (fees.royalty_fees !== undefined && (!Array.isArray(fees.royalty_fees) || fees.royalty_fees.length > 0))) {
95
+ throw new Error("Testnet SAUCE token metadata or fees do not match the supported policy.");
96
+ }
97
+ const balance = tokenBalances.tokens.find(token => token.token_id === TESTNET_SAUCE);
98
+ const allowance = tokenAllowances.allowances.find(entry =>
99
+ entry.spender === ROUTER && entry.token_id === TESTNET_SAUCE && entry.owner === id);
100
+ return {
101
+ balance: integer(balance?.balance ?? 0, "SAUCE balance"),
102
+ allowance: integer(allowance?.amount ?? 0, "SaucerSwap SAUCE allowance"),
103
+ };
104
+ },
105
+ };
106
+ }
@@ -0,0 +1,120 @@
1
+ import { ROUTER } from "./treasury-policy.mjs";
2
+ import { evmEntity } from "./hedera-mirror-client.mjs";
3
+
4
+ export async function loadSdk() {
5
+ try {
6
+ return await import("@hiero-ledger/sdk");
7
+ } catch (error) {
8
+ if (error.code !== "ERR_MODULE_NOT_FOUND") throw error;
9
+ throw new Error(
10
+ "Hedera signing requires the opt-in SDK. In integrations/hedera/treasury-guard, run npm ci --ignore-scripts.",
11
+ );
12
+ }
13
+ }
14
+
15
+ export function accountPrivateKey(sdk, text, publicKey) {
16
+ let key;
17
+ try {
18
+ const keyText = text.trim().replace(/^0x/i, "");
19
+ if (keyText.length === 64 && publicKey?._type === "ED25519") {
20
+ key = sdk.PrivateKey.fromStringED25519(keyText);
21
+ } else if (keyText.length === 64 && publicKey?._type === "ECDSA_SECP256K1") {
22
+ key = sdk.PrivateKey.fromStringECDSA(keyText);
23
+ } else {
24
+ key = sdk.PrivateKey.fromStringDer(keyText);
25
+ }
26
+ } catch {
27
+ throw new Error("Invalid Hedera testnet private key.");
28
+ }
29
+ if (!publicKey?.key || key.publicKey.toStringRaw() !== publicKey.key.toLowerCase()) {
30
+ throw new Error("The private key does not match the testnet account's single signing key.");
31
+ }
32
+ return key;
33
+ }
34
+
35
+ export function buildSwap(sdk, plan, transactionId) {
36
+ const parameters = new sdk.ContractFunctionParameters()
37
+ .addUint256(plan.spend_units)
38
+ .addUint256(plan.min_out_tinybars)
39
+ .addAddressArray(plan.path.map(evmEntity))
40
+ .addAddress(plan.recipient)
41
+ .addUint256(Math.floor(plan.expires_at_ms / 1000));
42
+
43
+ return new sdk.ContractExecuteTransaction()
44
+ .setContractId(ROUTER)
45
+ .setGas(450_000)
46
+ .setMaxTransactionFee(sdk.Hbar.fromTinybars(plan.max_fee_tinybars))
47
+ .setTransactionId(transactionId)
48
+ .setTransactionValidDuration(60)
49
+ .setRegenerateTransactionId(false)
50
+ .setFunction("swapExactTokensForETH", parameters);
51
+ }
52
+
53
+ export function transactionProof(transactionId) {
54
+ const id = transactionId.toString();
55
+ return {
56
+ transaction_id: id,
57
+ hashscan_url: `https://hashscan.io/testnet/transaction/${id.replace(/@(\d+)\.(\d+)$/, "-$1-$2")}`,
58
+ };
59
+ }
60
+
61
+ export async function submitSwap(sdk, plan, id, key, recordAttempt) {
62
+ const account = sdk.AccountId.fromString(plan.account_id);
63
+ const client = sdk.Client.forTestnet().setOperator(account, key);
64
+ try {
65
+ const transactionId = sdk.TransactionId.generate(account);
66
+ const swap = buildSwap(sdk, plan, transactionId);
67
+ const proof = transactionProof(transactionId);
68
+ await recordAttempt(proof);
69
+ if (Date.now() >= Math.floor(plan.expires_at_ms / 1000) * 1000) {
70
+ return { state: "expired_before_submission", ...proof };
71
+ }
72
+ try {
73
+ const response = await swap.execute(client);
74
+ const receipt = await response.getReceipt(client);
75
+ if (receipt.status.toString() !== "SUCCESS") {
76
+ return { state: "failed", status: receipt.status.toString(), ...proof };
77
+ }
78
+ } catch (error) {
79
+ if (error instanceof sdk.ReceiptStatusError) {
80
+ return { state: "failed", status: error.status.toString(), ...proof };
81
+ }
82
+ return { state: "unconfirmed", ...proof };
83
+ }
84
+ const result = { state: "confirmed", ...proof };
85
+ if (plan.audit_topic_id) result.audit = await submitAudit(sdk, client, account, plan, id, proof);
86
+ return result;
87
+ } finally {
88
+ client.close();
89
+ }
90
+ }
91
+
92
+ async function submitAudit(sdk, client, account, plan, id, swapProof) {
93
+ const transactionId = sdk.TransactionId.generate(account);
94
+ const proof = transactionProof(transactionId);
95
+ const topic = { topic_id: plan.audit_topic_id, ...proof };
96
+ try {
97
+ const response = await new sdk.TopicMessageSubmitTransaction()
98
+ .setTopicId(plan.audit_topic_id)
99
+ .setMessage(JSON.stringify({
100
+ type: "onecraft.treasury.top_up",
101
+ plan_id: id,
102
+ swap_transaction_id: swapProof.transaction_id,
103
+ spend_units: plan.spend_units,
104
+ min_out_tinybars: plan.min_out_tinybars,
105
+ }))
106
+ .setTransactionId(transactionId)
107
+ .setRegenerateTransactionId(false)
108
+ .setMaxTransactionFee(sdk.Hbar.fromTinybars(plan.max_audit_fee_tinybars))
109
+ // A payer limit with no denominations disallows additional topic fees.
110
+ .addCustomFeeLimit(new sdk.CustomFeeLimit({ accountId: account, fees: [] }))
111
+ .execute(client);
112
+ const receipt = await response.getReceipt(client);
113
+ return { state: "confirmed", sequence: receipt.topicSequenceNumber.toString(), ...topic };
114
+ } catch (error) {
115
+ if (error instanceof sdk.ReceiptStatusError) {
116
+ return { state: "failed", status: error.status.toString(), ...topic };
117
+ }
118
+ return { state: "unconfirmed", ...topic };
119
+ }
120
+ }
@@ -0,0 +1,177 @@
1
+ import { mkdir, readFile, rmdir, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { createInterface } from "node:readline/promises";
4
+ import { Writable } from "node:stream";
5
+ import { parseArgs } from "node:util";
6
+ import { digest, integer, NETWORK, policyFromJson, preview, TESTNET_SAUCE, verifyPrepared } from "./treasury-policy.mjs";
7
+ import { createMarket } from "./hedera-mirror-client.mjs";
8
+
9
+ const HELP = `OneCraft Treasury Guard (Hedera testnet)
10
+
11
+ Usage:
12
+ wallet hedera-treasury quote [--spend-units <integer>]
13
+ wallet hedera-treasury preview [--policy <file>] [--spend-units <integer>]
14
+ wallet hedera-treasury prepare [--policy <file>] [--spend-units <integer>]
15
+ wallet hedera-treasury execute <plan-id> [--policy <file>]
16
+ wallet hedera-treasury status <plan-id>
17
+
18
+ The policy defaults to hedera-treasury/policy.json under OPENCLAW_HOME
19
+ (typically ~/.openclaw). One SAUCE is 1000000 units. One HBAR is
20
+ 100000000 tinybars. Execution requires interactive approval and a testnet key.`;
21
+
22
+ async function readJson(file) {
23
+ return JSON.parse(await readFile(file, "utf8"));
24
+ }
25
+
26
+ async function readOptionalJson(file) {
27
+ try {
28
+ return await readJson(file);
29
+ } catch (error) {
30
+ if (error.code !== "ENOENT") throw error;
31
+ return null;
32
+ }
33
+ }
34
+
35
+ function writeNewJson(path, value) {
36
+ return writeFile(path, JSON.stringify(value, null, 2) + "\n", { flag: "wx", mode: 0o600 });
37
+ }
38
+
39
+ async function prompt(label, { hidden = false } = {}) {
40
+ const output = hidden
41
+ ? new Writable({ write(_chunk, _encoding, done) { done(); } })
42
+ : process.stderr;
43
+ const terminal = createInterface({ input: process.stdin, output, terminal: true });
44
+ const controller = new AbortController();
45
+ const cancel = () => controller.abort();
46
+ terminal.once("SIGINT", cancel);
47
+ terminal.once("close", cancel);
48
+ if (hidden) process.stderr.write(label);
49
+ try {
50
+ return await terminal.question(hidden ? "" : label, { signal: controller.signal });
51
+ } catch (error) {
52
+ if (error.name === "AbortError") throw new Error("Treasury approval cancelled.");
53
+ throw error;
54
+ } finally {
55
+ terminal.close();
56
+ if (hidden) process.stderr.write("\n");
57
+ }
58
+ }
59
+
60
+ async function execute({ state, files, policyPath, policy, market, planId, stderr }) {
61
+ if (!process.stdin.isTTY || !process.stderr.isTTY) {
62
+ throw new Error("Open a personal terminal to approve and execute this testnet swap.");
63
+ }
64
+ if (await readOptionalJson(files.attempt)) {
65
+ throw new Error("This plan already has a submission attempt. Check its status before preparing another swap.");
66
+ }
67
+ const plan = await readJson(files.plan);
68
+ await verifyPrepared(market, policy, plan, planId);
69
+ const { loadSdk, accountPrivateKey, submitSwap } = await import("./hedera-signer.mjs");
70
+ const sdk = await loadSdk();
71
+ stderr.write(`Approve this exact Hedera testnet swap\n${JSON.stringify(plan, null, 2)}\n`);
72
+ const answer = await prompt(`Type approve ${planId} to continue: `);
73
+ if (answer !== `approve ${planId}`) throw new Error("Treasury approval cancelled.");
74
+
75
+ const { key: accountKey } = await market.account(policy.account_id);
76
+ const privateKey = accountPrivateKey(sdk, await prompt("Hedera testnet private key (hidden): ", { hidden: true }), accountKey);
77
+ const lock = join(state, `${policy.account_id}.lock`);
78
+ try {
79
+ await mkdir(lock, { mode: 0o700 });
80
+ } catch (error) {
81
+ if (error.code !== "EEXIST") throw error;
82
+ throw new Error("A treasury execution is already in progress for this account. Check its status before proceeding.");
83
+ }
84
+ try {
85
+ if (await readOptionalJson(files.attempt)) {
86
+ throw new Error("This plan already has a submission attempt. Check its status.");
87
+ }
88
+ const currentPolicy = policyFromJson(await readJson(policyPath));
89
+ await verifyPrepared(market, currentPolicy, plan, planId);
90
+ const result = await submitSwap(sdk, plan, planId, privateKey, proof =>
91
+ writeNewJson(files.attempt, { state: "submission_attempted", plan_id: planId, ...proof }));
92
+ const outcome = { plan_id: planId, ...result };
93
+ await writeNewJson(files.result, outcome);
94
+ return outcome;
95
+ } finally {
96
+ await rmdir(lock);
97
+ }
98
+ }
99
+
100
+ export async function runTreasuryCli(args, { home, market = createMarket(), stdout = process.stdout, stderr = process.stderr }) {
101
+ const print = value => new Promise(resolve => {
102
+ stdout.write(typeof value === "string" ? value + "\n" : JSON.stringify(value, null, 2) + "\n", resolve);
103
+ });
104
+ try {
105
+ if (!args.length || args.includes("--help") || args[0] === "help" || args.includes("-h")) {
106
+ await print(HELP);
107
+ return 0;
108
+ }
109
+ const [command, ...flags] = args;
110
+ const policyCommand = ["preview", "prepare", "execute"].includes(command);
111
+ const requiresId = ["execute", "status"].includes(command);
112
+ if (!policyCommand && !requiresId && command !== "quote") throw new Error("Unknown treasury command. See --help.");
113
+ const options = {};
114
+ if (policyCommand) options.policy = { type: "string" };
115
+ if (["quote", "preview", "prepare"].includes(command)) options["spend-units"] = { type: "string" };
116
+ const { positionals, values } = parseArgs({ args: flags, allowPositionals: requiresId, options });
117
+ if (requiresId && (positionals.length !== 1 || !/^[0-9a-f]{64}$/.test(positionals[0]))) {
118
+ throw new Error("Provide a valid prepared plan ID.");
119
+ }
120
+
121
+ const requested = values["spend-units"];
122
+ if (command === "quote") {
123
+ const spend = integer(requested ?? "1000000", "Requested SAUCE spend", { min: 1n });
124
+ await print({
125
+ network: NETWORK,
126
+ input_token_id: TESTNET_SAUCE,
127
+ output_asset: "HBAR",
128
+ spend_units: spend.toString(),
129
+ quoted_out_tinybars: (await market.quote(spend)).toString(),
130
+ });
131
+ return 0;
132
+ }
133
+
134
+ const state = join(home, "hedera-treasury");
135
+ const plans = join(state, "plans");
136
+ const [planId] = positionals;
137
+ const files = {
138
+ plan: join(plans, `${planId}.json`),
139
+ attempt: join(plans, `${planId}.attempt.json`),
140
+ result: join(plans, `${planId}.result.json`),
141
+ };
142
+ if (command === "status") {
143
+ const record = await readOptionalJson(files.result) ?? await readOptionalJson(files.attempt);
144
+ if (record) await print(record);
145
+ else {
146
+ await readJson(files.plan);
147
+ await print({ state: "prepared", plan_id: planId });
148
+ }
149
+ return 0;
150
+ }
151
+
152
+ const policyPath = values.policy ?? join(state, "policy.json");
153
+ const policy = policyFromJson(await readJson(policyPath));
154
+ if (command === "execute") {
155
+ const outcome = await execute({ state, files, policyPath, policy, market, planId, stderr });
156
+ await print(outcome);
157
+ return outcome.state === "confirmed" ? 0 : 1;
158
+ }
159
+
160
+ const plan = await preview(market, policy, requested);
161
+ if (command === "prepare" && plan.decision === "top_up") {
162
+ const id = digest(plan);
163
+ await mkdir(plans, { recursive: true, mode: 0o700 });
164
+ await writeNewJson(join(plans, `${id}.json`), plan);
165
+ await print({ ...plan, plan_id: id });
166
+ } else {
167
+ await print(plan);
168
+ }
169
+ return 0;
170
+ } catch (error) {
171
+ const message = error.code === "ENOENT"
172
+ ? "Treasury policy or plan file was not found. See hedera-treasury --help."
173
+ : error.message;
174
+ await new Promise(resolve => stderr.write(message + "\n", resolve));
175
+ return 1;
176
+ }
177
+ }
@@ -0,0 +1,155 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ export const NETWORK = "hedera:testnet";
4
+ export const ROUTER = "0.0.19264";
5
+ export const WRAPPED_HBAR = "0.0.15058";
6
+ export const TESTNET_SAUCE = "0.0.1183558";
7
+ const MAX_INT64 = (1n << 63n) - 1n;
8
+ const MAX_FEE_TINYBARS = 500_000_000n;
9
+ const MAX_HCS_FEE_TINYBARS = 10_000_000n;
10
+ const QUOTE_LIFETIME_MS = 180_000;
11
+ const ENTITY_ID = /^0\.0\.[1-9]\d{0,18}$/;
12
+ const EVM_ADDRESS = /^0x[0-9a-f]{40}$/i;
13
+
14
+ export function integer(value, label, { min = 0n, max = MAX_INT64 } = {}) {
15
+ if (typeof value === "number" && Number.isSafeInteger(value)) value = String(value);
16
+ if (typeof value !== "string" || !/^(0|[1-9]\d{0,18})$/.test(value)) {
17
+ throw new Error(`${label} must be a non-negative integer in smallest units.`);
18
+ }
19
+ const amount = BigInt(value);
20
+ if (amount < min || amount > max) throw new Error(`${label} must be between ${min} and ${max}.`);
21
+ return amount;
22
+ }
23
+
24
+ function entityId(value, label) {
25
+ if (typeof value !== "string" || !ENTITY_ID.test(value)) {
26
+ throw new Error(`${label} must be a Hedera 0.0.x ID.`);
27
+ }
28
+ integer(value.split(".")[2], label, { min: 1n });
29
+ return value;
30
+ }
31
+
32
+ export function policyFromJson(input) {
33
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
34
+ throw new Error("Treasury policy must be a JSON object.");
35
+ }
36
+ const supportedKeys = new Set([
37
+ "network", "account_id", "reserve_tinybars", "max_spend_units", "min_receive_tinybars",
38
+ "max_fee_tinybars", "slippage_bps", "audit_topic_id",
39
+ ]);
40
+ for (const key of Object.keys(input)) {
41
+ if (!supportedKeys.has(key)) throw new Error("Unsupported treasury policy field.");
42
+ }
43
+ if (input.network !== NETWORK) throw new Error("Treasury Guard supports only hedera:testnet.");
44
+
45
+ return {
46
+ network: NETWORK,
47
+ account_id: entityId(input.account_id, "Account ID"),
48
+ reserve_tinybars: integer(input.reserve_tinybars, "Reserve", { min: 1n }).toString(),
49
+ max_spend_units: integer(input.max_spend_units, "Maximum SAUCE spend", { min: 1n }).toString(),
50
+ min_receive_tinybars: integer(input.min_receive_tinybars, "Minimum HBAR output", { min: 1n }).toString(),
51
+ max_fee_tinybars: integer(input.max_fee_tinybars, "Maximum swap fee", {
52
+ min: 1n, max: MAX_FEE_TINYBARS,
53
+ }).toString(),
54
+ slippage_bps: Number(integer(input.slippage_bps, "Slippage (bps)", { max: 100n })),
55
+ audit_topic_id: input.audit_topic_id == null ? null : entityId(input.audit_topic_id, "Audit topic ID"),
56
+ max_audit_fee_tinybars: input.audit_topic_id == null ? "0" : MAX_HCS_FEE_TINYBARS.toString(),
57
+ };
58
+ }
59
+
60
+ export function digest(value) {
61
+ return createHash("sha256").update(JSON.stringify(value)).digest("hex");
62
+ }
63
+
64
+ export function approvedSpend(policy, requested = policy.max_spend_units) {
65
+ const spend = integer(requested, "Requested SAUCE spend", { min: 1n });
66
+ if (spend > BigInt(policy.max_spend_units)) {
67
+ throw new Error("Policy rejected: requested SAUCE exceeds the per-swap spending limit.");
68
+ }
69
+ return spend;
70
+ }
71
+
72
+ export async function preview(market, policy, requested, now = Date.now) {
73
+ const spend = approvedSpend(policy, requested);
74
+ const account = await market.account(policy.account_id);
75
+ const balance = integer(account.balance?.balance, "Account HBAR balance");
76
+ const action = {
77
+ network: NETWORK,
78
+ account_id: policy.account_id,
79
+ balance_tinybars: balance.toString(),
80
+ reserve_tinybars: policy.reserve_tinybars,
81
+ };
82
+ if (balance >= BigInt(policy.reserve_tinybars)) {
83
+ return { ...action, decision: "hold", reason: "The HBAR reserve is at or above its target." };
84
+ }
85
+ const maximumFees = BigInt(policy.max_fee_tinybars) + BigInt(policy.max_audit_fee_tinybars);
86
+ if (balance < maximumFees) throw new Error("Policy rejected: account balance is below the approved fee budget.");
87
+ if (!EVM_ADDRESS.test(account.evm_address ?? "") || /^0x0{40}$/i.test(account.evm_address)) {
88
+ throw new Error("Hedera mirror node returned no canonical recipient address.");
89
+ }
90
+
91
+ const quotedAt = now();
92
+ const amountOut = await market.quote(spend);
93
+ const minOut = amountOut * BigInt(10_000 - policy.slippage_bps) / 10_000n;
94
+ if (minOut <= maximumFees || minOut < BigInt(policy.min_receive_tinybars)) {
95
+ throw new Error("Policy rejected: the quote does not meet the minimum HBAR output or fee budget.");
96
+ }
97
+ const available = await market.availableInput(policy.account_id);
98
+ if (available.balance < spend || available.allowance < spend) {
99
+ throw new Error("Insufficient SAUCE balance or SaucerSwap V1 allowance on Hedera testnet.");
100
+ }
101
+
102
+ return {
103
+ ...action,
104
+ decision: "top_up",
105
+ reason: "The HBAR reserve is below target and the live quote meets policy.",
106
+ router_id: ROUTER,
107
+ input_token_id: TESTNET_SAUCE,
108
+ output_asset: "HBAR",
109
+ path: [TESTNET_SAUCE, WRAPPED_HBAR],
110
+ recipient: account.evm_address.toLowerCase(),
111
+ spend_units: spend.toString(),
112
+ quoted_out_tinybars: amountOut.toString(),
113
+ min_out_tinybars: minOut.toString(),
114
+ max_fee_tinybars: policy.max_fee_tinybars,
115
+ audit_topic_id: policy.audit_topic_id,
116
+ max_audit_fee_tinybars: policy.max_audit_fee_tinybars,
117
+ policy_hash: digest(policy),
118
+ quoted_at_ms: quotedAt,
119
+ expires_at_ms: quotedAt + QUOTE_LIFETIME_MS,
120
+ };
121
+ }
122
+
123
+ export async function verifyPrepared(market, policy, plan, id, now = Date.now) {
124
+ if (digest(plan) !== id || plan.decision !== "top_up" || plan.policy_hash !== digest(policy)) {
125
+ throw new Error("Prepared swap or policy has changed. Prepare a new swap.");
126
+ }
127
+ if (plan.network !== NETWORK || plan.router_id !== ROUTER || plan.account_id !== policy.account_id ||
128
+ plan.reserve_tinybars !== policy.reserve_tinybars ||
129
+ plan.input_token_id !== TESTNET_SAUCE || plan.output_asset !== "HBAR" ||
130
+ JSON.stringify(plan.path) !== JSON.stringify([TESTNET_SAUCE, WRAPPED_HBAR]) ||
131
+ plan.max_fee_tinybars !== policy.max_fee_tinybars || plan.audit_topic_id !== policy.audit_topic_id ||
132
+ plan.max_audit_fee_tinybars !== policy.max_audit_fee_tinybars) {
133
+ throw new Error("Invalid prepared Hedera transaction terms.");
134
+ }
135
+ const minOut = integer(plan.min_out_tinybars, "Prepared minimum output", {
136
+ min: BigInt(policy.min_receive_tinybars),
137
+ });
138
+ const maximumFees = BigInt(policy.max_fee_tinybars) + BigInt(policy.max_audit_fee_tinybars);
139
+ const quotedOut = integer(plan.quoted_out_tinybars, "Prepared quoted output");
140
+ if (minOut <= maximumFees || minOut !== quotedOut * BigInt(10_000 - policy.slippage_bps) / 10_000n) {
141
+ throw new Error("Prepared output does not match the policy and quote.");
142
+ }
143
+ if (!Number.isSafeInteger(plan.quoted_at_ms) || !Number.isSafeInteger(plan.expires_at_ms) ||
144
+ plan.expires_at_ms !== plan.quoted_at_ms + QUOTE_LIFETIME_MS ||
145
+ plan.quoted_at_ms > now() || plan.expires_at_ms <= now()) {
146
+ throw new Error("Prepared quote has expired. Prepare a new swap.");
147
+ }
148
+
149
+ const fresh = await preview(market, policy, plan.spend_units, now);
150
+ if (fresh.decision !== "top_up" || fresh.recipient !== plan.recipient ||
151
+ BigInt(fresh.quoted_out_tinybars) < minOut || plan.expires_at_ms <= now()) {
152
+ throw new Error("Treasury state or the quote has changed. Prepare a new swap.");
153
+ }
154
+ return fresh;
155
+ }
package/mcp/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # OneCraft Universal Local MCP
2
+
3
+ This is the framework-neutral OneCraft wallet MCP for any client that
4
+ supports local MCP over `stdio`. It uses the same local wallet runtime and the
5
+ same full tool surface as the Codex and Claude Code bridges.
6
+
7
+ ## Connect a client
8
+
9
+ Install the runtime, then ask the CLI for the exact config for this machine:
10
+
11
+ ```bash
12
+ npx --yes @onecraft/wallet@latest install --yes --runtime-only
13
+ npx --yes @onecraft/wallet@latest mcp config
14
+ ```
15
+
16
+ Paste the resulting `mcpServers` object into the client's MCP settings. The
17
+ command contains an absolute path under
18
+ `~/.openclaw/agent-wallet-runtime/current`, so normal wallet updates keep the
19
+ client connected to the active runtime.
20
+
21
+ For clients that want a command rather than a JSON object:
22
+
23
+ ```bash
24
+ npx --yes @onecraft/wallet@latest mcp serve
25
+ ```
26
+
27
+ For clients that ask for a launcher path:
28
+
29
+ ```bash
30
+ npx --yes @onecraft/wallet@latest mcp path
31
+ ```
32
+
33
+ ## Security and behavior
34
+
35
+ The MCP config contains no wallet secrets. The bridge reuses the existing
36
+ wallet adapter and therefore exposes the same read and write capabilities as
37
+ the Codex and Claude Code integrations. Write operations still preserve the
38
+ wallet's `preview -> prepare -> execute` flow and approval-token validation;
39
+ this universal launcher does not weaken those backend rules.
@@ -0,0 +1,37 @@
1
+ #!/bin/sh
2
+ set -eu
3
+
4
+ # Framework-neutral stdio launcher. It resolves the shared wallet runtime and
5
+ # deliberately keeps secrets out of MCP configuration files.
6
+ SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
7
+ MCP_ROOT=$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd -P)
8
+ OPENCLAW_HOME=${OPENCLAW_HOME:-"$HOME/.openclaw"}
9
+ PACKAGE_ROOT=${AGENT_WALLET_PACKAGE_ROOT:-${OPENCLAW_AGENT_WALLET_PACKAGE_ROOT:-"$MCP_ROOT/../agent-wallet"}}
10
+ export AGENT_WALLET_PACKAGE_ROOT="$PACKAGE_ROOT"
11
+
12
+ if [ -n "${AGENT_WALLET_PYTHON:-}" ]; then
13
+ PYTHON_BIN=$AGENT_WALLET_PYTHON
14
+ elif [ -n "${OPENCLAW_AGENT_WALLET_PYTHON:-}" ]; then
15
+ PYTHON_BIN=$OPENCLAW_AGENT_WALLET_PYTHON
16
+ elif [ -x "$PACKAGE_ROOT/.venv/bin/python" ]; then
17
+ PYTHON_BIN=$PACKAGE_ROOT/.venv/bin/python
18
+ elif [ -x "$PACKAGE_ROOT/.runtime-venv/bin/python" ]; then
19
+ PYTHON_BIN=$PACKAGE_ROOT/.runtime-venv/bin/python
20
+ else
21
+ PYTHON_BIN=python3
22
+ fi
23
+
24
+ if [ ! -f "$MCP_ROOT/server.py" ]; then
25
+ printf '{"error":"OneCraft universal MCP server is missing.","fix":"wallet install --yes"}\n' >&2
26
+ exit 1
27
+ fi
28
+
29
+ if ! "$PYTHON_BIN" -c 'import sys, ast; ast.parse(open(sys.argv[1], encoding="utf-8").read())' "$MCP_ROOT/server.py" 2>/dev/null; then
30
+ printf '{"error":"OneCraft universal MCP server failed to parse.","fix":"wallet install --yes (or: wallet rollback)"}\n' >&2
31
+ exit 1
32
+ fi
33
+
34
+ : "${AGENT_WALLET_HOST:=mcp}"
35
+ export AGENT_WALLET_HOST
36
+
37
+ exec "$PYTHON_BIN" "$MCP_ROOT/server.py"