buoy-wallet 0.0.1 → 0.0.2

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.
@@ -5,6 +5,32 @@ description: Set up and use Buoy Wallet on X Layer — an AI agent's spending ac
5
5
 
6
6
  # Buoy Wallet
7
7
 
8
+ ## First-time setup, in three steps
9
+
10
+ Read these before anything else. They are the whole of what you do on a first run.
11
+
12
+ 1. **You are not creating an account, generating a key, or signing anything.** You install a
13
+ local MCP server — `npx -y buoy-wallet@latest install -y` — and you start an approval link
14
+ on `127.0.0.1` that the user opens in their own browser, with their own OKX Wallet. That is
15
+ all. Every signature in a setup is made by the user, in their wallet.
16
+ 2. **Buoy never generates keys, so the agent's address has to exist already.** Ask `onchainos`
17
+ for it first: `onchainos wallet addresses --chain 196`. If `onchainos` is not installed and
18
+ the user does not want it, ask them for an existing X Layer `0x` address to be the agent —
19
+ and it must be a **different address from their owner wallet**. An agent that holds the
20
+ owner's key is not limited by the vault at all. Never invent an address, and never reuse the
21
+ owner's.
22
+ 3. **Keep the approval server running until the user confirms or the link times out.** The
23
+ page reports back to the process that made the link. Do not restart the agent, the MCP, or
24
+ the terminal in between, and do not run the link from a shell command that will be cut off
25
+ after a minute or two. If it is lost anyway, the vault is still made and still theirs:
26
+ see "If the result never came back", below.
27
+
28
+ Steps 1–5 under Onboarding are these three in detail.
29
+
30
+ ---
31
+
32
+ ## What Buoy is
33
+
8
34
  An AI agent's spending account on X Layer, where the limit is enforced by a smart contract rather
9
35
  than by the agent's good intentions. The agent can ask to pay. It cannot move tokens directly, it
10
36
  cannot raise its own limit, and it cannot reach the owner's functions.
@@ -32,7 +58,9 @@ npx -y buoy-wallet@latest install -y
32
58
  It needs Node 22+, no addresses and no keys. It wires the `buoy` MCP server into Claude Code and
33
59
  Cursor — as `npx -y buoy-wallet@latest mcp`, so the agent always starts the current release — and
34
60
  tells you which deployment it found (X Layer mainnet) and whether `onchainos` — your signing
35
- lane — is installed (`npx -y @okxweb3/onchainos-installer install` if not).
61
+ lane — is installed. For Claude Code it registers the server at **user scope**, so it is there
62
+ in every folder, and it prints `not installed` rather than `Done` if it could not: believe what
63
+ it prints. (`--scope project` writes a `.mcp.json` in the current folder instead.)
36
64
 
37
65
  Any other MCP host takes the same server by hand: command `npx`, arguments
38
66
  `-y buoy-wallet@latest mcp` (on Windows, command `cmd` with `/c npx -y buoy-wallet@latest mcp`).
@@ -68,7 +96,9 @@ change cannot be read at all. Do not ask them to confirm what they just told you
68
96
 
69
97
  ### 5. One link
70
98
 
71
- Find your own address — you are the agent — with `onchainos wallet addresses --chain 196`. Then:
99
+ Find your own address — you are the agent — with `onchainos wallet addresses --chain 196`; it is
100
+ `data.xlayer[0].address` in what that prints. If `onchainos` is missing, see "The agent's wallet"
101
+ below, or ask the user for an existing X Layer address **other than their owner wallet**. Then:
72
102
 
73
103
  ```
74
104
  buoy_request_owner_action { action: "setup", agent: "<your address>",
@@ -111,7 +141,26 @@ both of those are true on chain.
111
141
 
112
142
  Then call `buoy_owner_action_result` with the `handle` and `waitSeconds: 120`, again while it
113
143
  says `pending`. **Do not say it is live until it does** — that tool re-reads the chain rather
114
- than trusting the browser.
144
+ than trusting the browser. Keep the MCP server running the whole time: the page reports to it.
145
+
146
+ **If the wallet that approves is also the agent**, the card stops once and says so before it
147
+ sends anything: that wallet could withdraw everything, so the limit would bind nothing. Tell
148
+ the user what it said and get a different agent address. Do not tell them to press through it.
149
+
150
+ ### If the result never came back
151
+
152
+ The user approved, the transaction is mined, and you have no result — the handle is unknown
153
+ because the server restarted, or the link was started from a shell that was cut off. The vault
154
+ exists and is theirs. Do **not** set up again, which makes a second vault. Instead:
155
+
156
+ 1. Ask the user for the **transaction hash** of the setup, from their OKX Wallet's history.
157
+ 2. Call `buoy_owner_action_result` with `txHash` (no handle), or run
158
+ `npx -y buoy-wallet@latest owner setup --finish <hash>`.
159
+ 3. Relay its `say` whole. It names the vault's **owner**: ask the user to confirm that is their
160
+ own wallet address before they fund anything.
161
+
162
+ `buoy_status` tells you when this applies: it reports a `pendingSetup`, and its `say` says a
163
+ setup was started here and never recorded. Never guess the hash, and never look one up yourself.
115
164
 
116
165
  ### What to say afterwards
117
166
 
@@ -125,7 +174,9 @@ than trusting the browser.
125
174
  | `fast-start-no-pay-only` | "On Fast Start an agent can pay-and-swap or swap-only. Pay-only needs a policy of your own, which only this deployment's owner can sign today." |
126
175
  | `published-policy-expired`, `-revoked`, `-unusable`, `-mismatch` | its `say`, verbatim. The shared policy was re-read from the chain and is not safe to build on. Nothing was sent, and trying again will not help. |
127
176
  | `bad-amount` | "The daily ceiling must be a whole number of USDT0, 1 or more — like 50, 100 or 200." |
128
- | `missing-agent-address` | Get your address with `onchainos wallet addresses --chain 196` and call it again. |
177
+ | `missing-agent-address` | Get your address with `onchainos wallet addresses --chain 196` and call it again. No `onchainos`: ask the user for an existing X Layer address that is **not** their owner wallet. |
178
+ | `unknown-handle` after a setup they say they approved | Ask for the setup's transaction hash from their wallet's history, and call `buoy_owner_action_result` with `txHash`. Do not start a second setup. |
179
+ | the card says the wallet is also the agent | Stop. Get a different agent address and make a new link. |
129
180
  | `agent-key-is-public` | You passed the rehearsal's sample agent. Use your own address; never that one on mainnet. |
130
181
  | still `pending`, and they say the page found no wallet | "I can't reach your OKX Wallet. Unlock the extension and reload that same link — it stays good for 20 minutes." |
131
182
 
@@ -184,9 +235,26 @@ narrower permission has to be chosen here, at setup.
184
235
  | "was that really refused?" | `buoy_verify` |
185
236
  | "set up Buoy" / first run | Onboarding, above: `buoy_request_owner_action` with `action: "setup"` |
186
237
  | add/remove/rename an agent, change a budget | `buoy_request_owner_action` |
238
+ | "take my money out" / "withdraw" | `buoy_request_owner_action` with `action: "withdraw"`, `amount` (or `"all"`) and `to` — the owner's card, never an agent's call |
187
239
 
188
240
  Start with `buoy_status`. It takes no arguments and tells you whether anything else will work.
189
241
 
242
+ **Say whose vault it is.** `buoy_status` returns `createdBy`: `setup` is a vault made on this
243
+ machine, `launch` is the one the deployment itself was launched with, which belongs to somebody
244
+ else. Its `say` opens by saying so whenever it is the launch vault, and so do `buoy_balance`,
245
+ `buoy_pay` and `buoy_swap`. Relay that. Never present the launch vault's budgets as the user's.
246
+
247
+ **The only address to fund is `depositAddress`** — the vault. `token.address` is the USDT0
248
+ token contract itself; it appears in these answers and funds sent to it are gone. Never give a
249
+ user the token's address as somewhere to send money.
250
+
251
+ **Amounts are whole tokens, written the way a person writes them.** `amount: "150"` is 150
252
+ USDT0; `amount: "0.10"` is ten cents. They are **not** base units: `"150"` used to mean
253
+ 0.00015 USDT0, and that is exactly how a 150 USDT0 request once looked the same as a 0.10 one.
254
+ If you really have base units, pass `amountBaseUnits` instead — never both. The same goes for
255
+ `buoy_swap`'s `amountIn` and `minAmountOut`, each in its own token, and for the CLI's `--amount`.
256
+ A daily ceiling (`ceiling`, `limit`) is whole USDT0 too.
257
+
190
258
  **Addresses are not your problem.** Every tool finds the deployment itself. Never ask the user for
191
259
  a contract address, and never offer to accept one.
192
260
 
@@ -198,7 +266,22 @@ another name.
198
266
 
199
267
  ## Paying: three steps, and the middle one is not yours
200
268
 
201
- `buoy_pay` **builds** the call. It cannot send it — the Buoy MCP holds no key and has no
269
+ `buoy_pay` **builds** the call, and first **asks the contract what it would answer**: it runs the
270
+ exact call as a read-only simulation on chain, as the agent. `simulation.outcome` is one of:
271
+
272
+ - **`allowed`** — the contract would let it through.
273
+ - **`refused`** — the contract would refuse it, with `reason` and `reasonName` (over today's
274
+ budget is `period-limit-reached`). The figures are the contract's own.
275
+ - **`reverts`** — the call would fail before any verdict: the vault does not hold enough
276
+ (`underfunded: true`, and the `say` gives the address to fund), or the sender is not an agent
277
+ of this vault. A revert is not a refusal and leaves no receipt.
278
+ - **`unavailable`** — it could not be asked. Say that; do not guess.
279
+
280
+ Relay its `say`. This needs no key and no `onchainos`, so it is the answer you have even on a
281
+ machine that cannot broadcast — in which case say what it said, and that nothing was sent. Never
282
+ tell a user a payment "would pass" from arithmetic of your own.
283
+
284
+ It cannot send the call — the Buoy MCP holds no key and has no
202
285
  `sendRawTransaction` anywhere in it. You broadcast it with your own `onchainos` tool, whose key
203
286
  lives in OKX's TEE:
204
287
 
@@ -221,6 +304,44 @@ flow around this.
221
304
 
222
305
  ---
223
306
 
307
+ ## The agent's wallet: `onchainos`
308
+
309
+ The agent signs with OKX Agentic Wallet, through OKX's own `onchainos` CLI. Buoy does not ship
310
+ it, does not hold its key, and works without it for everything except broadcasting: status,
311
+ balances, simulations, verification and every owner card need no `onchainos` at all.
312
+
313
+ **There is one install command, and it is OKX's own** (from the README of
314
+ `github.com/okx/onchainos-skills`; the npm package is published by OKX). It needs Git and Node:
315
+
316
+ ```bash
317
+ npx -y @okxweb3/onchainos-installer install
318
+ ```
319
+
320
+ Do not substitute any other package name for it, and do not guess one. If that command fails,
321
+ say so and stop — do not go looking for an alternative installer.
322
+
323
+ It puts the binary in `~/.local/bin` (on Windows, `%USERPROFILE%\.local\bin\onchainos.exe`).
324
+ Then, in this order:
325
+
326
+ ```bash
327
+ onchainos --version # prints e.g. "onchainos 4.6.11"
328
+ onchainos wallet status # "loggedIn": true once the user has signed in
329
+ onchainos wallet login # only if not logged in: prints a login URL
330
+ onchainos wallet addresses --chain 196 # the agent's X Layer address: data.xlayer[0].address
331
+ ```
332
+
333
+ - **"command not found" straight after installing** almost always means the folder is not on
334
+ PATH in this terminal yet. Open a new terminal, or run it by its full path. `buoy install`
335
+ says which it is: `installed, but not on PATH`, with the path, or `onchainos missing`.
336
+ - **Login is the user's.** `onchainos wallet login` returns a URL; the user opens it and signs in
337
+ with Google, Apple or email in their browser, and `onchainos wallet login --phase poll` then
338
+ completes it. You never see a password, and you never ask for one. If the `okx-agentic-wallet`
339
+ skill is installed, follow its login steps rather than these.
340
+ - **The address it gives is the agent's**, and that is the one to pass as `agent` in a setup. It
341
+ is not the user's owner wallet, and the two must stay different.
342
+
343
+ ---
344
+
224
345
  ## Paid APIs: `buoy_fetch`, and the order that matters
225
346
 
226
347
  When a URL answers HTTP 402, call `buoy_fetch`. It reads the seller's price and builds the
@@ -249,9 +370,9 @@ The agent never holds a buoy. It is funded for one invoice and returns to zero.
249
370
  If the user asks you to pay, call `buoy_pay` and **broadcast it — even when you have just read
250
371
  the budget and are confident it will be refused.**
251
372
 
252
- `buoy_pay` returns an `expectation` field that may say the payment looks over budget. That is
253
- advice for the user, not a decision for you. Say it out loud if you like — "this looks over
254
- today's limit, sending it so the account can rule" — and then send it.
373
+ `buoy_pay` returns a `simulation` that may say the contract would refuse. That is the contract's
374
+ answer to a question, not a receipt, and not a decision for you. Say it out loud — "the vault says
375
+ this is over today's limit; sending it so that refusal is on record" — and then send it.
255
376
 
256
377
  A refusal you calculated is a refusal nobody can check. When the **contract** refuses, the
257
378
  decision is recorded on chain, the agent provably could not have done otherwise, and the user
@@ -312,8 +433,16 @@ that the receipt did not verify — that is a serious discrepancy, not a detail.
312
433
 
313
434
  ## Owner actions: one card, one click
314
435
 
315
- Letting an agent spend, revoking one, renaming something, changing a budget — these are the
316
- human's, not yours. (Making the vault in the first place is `action: "setup"`: see Onboarding.)
436
+ Letting an agent spend, revoking one, renaming something, changing a budget, **taking money out**
437
+ — these are the human's, not yours. (Making the vault in the first place is `action: "setup"`:
438
+ see Onboarding.)
439
+
440
+ **Withdrawing** is `action: "withdraw"` with `amount` — whole tokens, or `"all"` — and `to`, the
441
+ address the funds go to (the vault's owner if left out). The card shows the amount and the full
442
+ destination, and stops a wallet that does not own the vault before sending anything. It never
443
+ goes through the budget or the policy, so it works on a vault whose policy has expired or been
444
+ revoked — and no agent can do it. Read the destination back to the user before giving them the
445
+ link: a transfer cannot be undone.
317
446
 
318
447
  1. Call `buoy_request_owner_action` with the action and its arguments.
319
448
  2. Give the user the `url` it returns, with the one-sentence `summary`. The link works **once** and
@@ -10,7 +10,7 @@
10
10
  // not, and an approval card that shows the second one is a card that gets approved blindly.
11
11
 
12
12
  import { selectorOf } from "../mcp/chain.mjs";
13
- import { word, addrWord, strTail } from "../mcp/read.mjs";
13
+ import { word, addrWord, strTail, units } from "../mcp/read.mjs";
14
14
  import { assertUnsigned, planBinding } from "../mcp/payloads.mjs";
15
15
  import { keccak } from "../src/policy-binding.mjs";
16
16
  import { encodeInstallBinding, tablesFromCanonicalJson } from "./abi.mjs";
@@ -109,6 +109,13 @@ export const ACTIONS = {
109
109
  },
110
110
  },
111
111
 
112
+ // ---------------------------------------------------------------- the owner's money back out
113
+ /* `FloatVault.withdraw` is the owner's alone and never asks the gatekeeper: it works with the
114
+ policy expired, revoked, or never installed. That is the promise every Fast Start card makes
115
+ ("it cannot touch your funds"), and until this action existed there was no card to keep it
116
+ with -- the owner had to hand-build the call. */
117
+ withdraw: { plan: (m, a) => planWithdraw(m, a) },
118
+
112
119
  // ---------------------------------------------------------------- agents
113
120
  "add-agent": {
114
121
  summary: (a) =>
@@ -119,6 +126,8 @@ export const ACTIONS = {
119
126
  "It never holds your money, and it cannot raise its own limit.",
120
127
  a.name ? `The name "${a.name}" is a label for you to read; it grants nothing.` : null,
121
128
  ].filter(Boolean),
129
+ /* Compared, in the page, with the wallet that connects. See the same field in setup.mjs. */
130
+ agents: (a) => (ADDR.test(String(a.agent ?? "")) ? [String(a.agent)] : []),
122
131
  build: (m, a) => {
123
132
  const agent = needAddr(a.agent, "--agent");
124
133
  const acct = adapterOf(m, a.via);
@@ -264,6 +273,78 @@ export const ACTIONS = {
264
273
  },
265
274
  };
266
275
 
276
+ /**
277
+ * The owner taking money out of the vault.
278
+ *
279
+ * THE LABEL IS MADE FROM THE CALLDATA'S OWN NUMBER, here and nowhere else. `amountBaseUnits` is
280
+ * what goes into the transaction, and the sentence and the rows on the card are that same figure
281
+ * formatted -- there is no separate "amount to display" a caller could set to something smaller.
282
+ * `resolved` (the token's decimals and symbol, and what the vault holds) is read from the chain by
283
+ * createSignLink and dropped from anything a tool passed in; without it the figure is shown in
284
+ * base units, which is ugly and true.
285
+ *
286
+ * The destination is shown in full, in the rows a person reads before pressing the button. A
287
+ * shortened address is how a look-alike gets approved.
288
+ */
289
+ function planWithdraw(m, a = {}) {
290
+ if (a.via !== undefined && String(a.via).toLowerCase() !== "vault") {
291
+ throw new ActionError(
292
+ "withdraw-vault-only",
293
+ "a withdrawal is from the vault. Funds behind the Safe leg are held by the Safe itself: move them from there."
294
+ );
295
+ }
296
+ const vault = needAddr(m.addresses.vault, "vault");
297
+ const token = needAddr(a.token ?? m.addresses.usdt, "--token");
298
+ const to = needAddr(a.to ?? m.addresses.owner, "--to (where the funds go)");
299
+ if (/^0x0{40}$/.test(to)) throw new ActionError("bad-address", "--to is the zero address: that would burn the funds");
300
+ const raw = String(need(a.amountBaseUnits, "--amount")).trim();
301
+ if (!/^[0-9]+$/.test(raw) || BigInt(raw) === 0n) {
302
+ throw new ActionError("bad-amount", `the amount to withdraw must be more than 0, got "${raw}"`);
303
+ }
304
+ const base = BigInt(raw);
305
+ const r = a.resolved && Number.isInteger(a.resolved.decimals) ? a.resolved : null;
306
+ const label = r ? units(base, r.decimals, r.symbol) : `${base} base units of ${token}`;
307
+ const holds = r && r.holds !== undefined ? units(BigInt(r.holds), r.decimals, r.symbol) : null;
308
+ const toOwner = m.addresses.owner && to.toLowerCase() === String(m.addresses.owner).toLowerCase();
309
+
310
+ return {
311
+ summary: `Withdraw ${label} from your vault to ${to}.`,
312
+ detail: [
313
+ "Only the vault's owner can do this. No agent can: it is not a payment, and it never goes through the budget or the policy.",
314
+ "It works even if the vault's policy has expired or been revoked.",
315
+ "The funds go straight to the address shown. Check every character of it: a transfer cannot be undone.",
316
+ ],
317
+ card: {
318
+ title: `Withdraw ${label}`,
319
+ rows: [
320
+ ["From", `your vault ${vault}`],
321
+ ["To", toOwner ? `${to} — the vault's owner` : to],
322
+ ["Amount", label],
323
+ ["Cost", "1 transaction · gas only"],
324
+ ],
325
+ disclosure: null,
326
+ more: [
327
+ ["Token", r ? `${r.symbol} ${token}` : token],
328
+ ...(holds ? [["Vault holds", holds]] : []),
329
+ ["Exactly", `${base} base units`],
330
+ ],
331
+ },
332
+ /* Asked in the page before anything is sent: a wallet that does not own the vault is told so
333
+ instead of being shown a transaction that can only revert. */
334
+ preflight: [
335
+ {
336
+ check: "connected-account-is",
337
+ to: vault,
338
+ data: selectorOf("owner()"),
339
+ failure: "This wallet does not own that vault, so it cannot withdraw from it. Nothing was sent.",
340
+ },
341
+ ],
342
+ txs: [
343
+ tx(vault, selectorOf("withdraw(address,address,uint256)") + addrWord(token) + addrWord(to) + word(base), `Withdraw ${label} to ${to}`),
344
+ ],
345
+ };
346
+ }
347
+
267
348
  /**
268
349
  * Prepare one owner action.
269
350
  *
@@ -283,6 +364,7 @@ export function prepare(m, name, args) {
283
364
  action: name,
284
365
  summary: spec.summary(args),
285
366
  detail: spec.detail(args),
367
+ ...(spec.agents ? { agentAddresses: spec.agents(args) } : {}),
286
368
  chainId: m.chainId,
287
369
  target: m.target,
288
370
  isRehearsal: m.isFork,
@@ -24,12 +24,15 @@
24
24
  import { createServer } from "node:http";
25
25
  import { readFileSync } from "node:fs";
26
26
  import { randomBytes } from "node:crypto";
27
- import { prepare, ACTION_NAMES } from "./actions.mjs";
27
+ import { prepare, ACTION_NAMES, ActionError } from "./actions.mjs";
28
28
  import { fillStep, refsFromReceipt } from "./steps.mjs";
29
- import { SETUP_TTL_MS, finishSetup, modeOf } from "./setup.mjs";
29
+ import { SETUP_TTL_MS, finishSetup, finishPendingSetup, modeOf } from "./setup.mjs";
30
30
  import { loadPublishedPolicy, sharedPolicyDisclosures } from "./faststart.mjs";
31
31
  import { verifyOneStepFactory } from "./v2.mjs";
32
32
  import { makeClient } from "../mcp/chain.mjs";
33
+ import { makeReader, units } from "../mcp/read.mjs";
34
+ import { parseAmount } from "../mcp/amount.mjs";
35
+ import { writePendingSetup, clearPendingSetup } from "../mcp/manifest.mjs";
33
36
 
34
37
  export class SignLinkError extends Error {
35
38
  constructor(code, detail) {
@@ -97,7 +100,44 @@ async function chainTime(rpc) {
97
100
  }
98
101
  }
99
102
 
100
- export async function createSignLink({ manifest, action, args = {}, ttlMs, published, v2 } = {}) {
103
+ /**
104
+ * What a withdrawal's amount IS, asked of the chain before a card exists.
105
+ *
106
+ * A person says "0.10" or "all". The transaction needs base units, the card needs the token's
107
+ * own figure, and both have to be the same number -- so the token's decimals and what the vault
108
+ * holds are read here, and a request for more than is there is a sentence now rather than a
109
+ * reverted transaction the owner has already approved.
110
+ */
111
+ async function resolveWithdrawal(chain, manifest, a) {
112
+ const token = a.token ?? manifest.addresses.usdt;
113
+ const vault = manifest.addresses.vault;
114
+ if (!token || !vault) throw new ActionError("missing-address", "there is no vault, or no token, to withdraw");
115
+ const r = makeReader(chain, manifest);
116
+ const [symbol, decimals, holds] = await Promise.all([r.symbol(token), r.decimals(token), r.balanceOf(token, vault)]);
117
+ const said = String(a.amount ?? "").trim();
118
+ const exact = a.amountBaseUnits !== undefined && a.amountBaseUnits !== null && String(a.amountBaseUnits).trim() !== "";
119
+ if (said !== "" && exact) {
120
+ throw new ActionError("amount-ambiguous", `the amount was given twice, as ${said} and as ${a.amountBaseUnits} base units. Pass one.`);
121
+ }
122
+ let base;
123
+ if (said.toLowerCase() === "all") base = holds;
124
+ else if (exact) {
125
+ if (!/^[0-9]+$/.test(String(a.amountBaseUnits).trim())) throw new ActionError("bad-amount", "base units are a whole number");
126
+ base = BigInt(String(a.amountBaseUnits).trim());
127
+ } else if (said !== "") base = parseAmount(said, decimals, symbol);
128
+ else throw new ActionError("missing-argument", `how much to withdraw: a figure in ${symbol} like 0.10, or "all"`);
129
+ if (holds === 0n) throw new ActionError("nothing-to-withdraw", `the vault holds no ${symbol}`);
130
+ if (base === 0n) throw new ActionError("bad-amount", "the amount to withdraw must be more than 0");
131
+ if (base > holds) {
132
+ throw new ActionError(
133
+ "more-than-held",
134
+ `the vault holds ${units(holds, decimals, symbol)}, and ${units(base, decimals, symbol)} is more than that`
135
+ );
136
+ }
137
+ return { amountBaseUnits: base.toString(), resolved: { decimals, symbol, holds: holds.toString() } };
138
+ }
139
+
140
+ export async function createSignLink({ manifest, action, args = {}, ttlMs, published, v2, chain } = {}) {
101
141
  /* The EARLIER of the two clocks: never later than the chain, so the binding is already valid
102
142
  when it lands, and never later than this machine, so a node reporting a time in the future
103
143
  cannot push the window forward either. Unreachable node: the wall clock, as before. */
@@ -110,6 +150,11 @@ export async function createSignLink({ manifest, action, args = {}, ttlMs, publi
110
150
  carried under this name is dropped first: a verified policy comes from this function (or, in
111
151
  a test, from its caller), never from a tool argument. */
112
152
  const { published: _dropped, v2: _droppedToo, ...clean } = args;
153
+ /* A withdrawal's figures come from the chain, by the same rule. They are spread into the
154
+ action's arguments LAST, below, so whatever a tool passed as `resolved` or as an amount in
155
+ base units is overwritten: the amount the card shows is the one in the transaction. */
156
+ const withdrawal =
157
+ action === "withdraw" ? await resolveWithdrawal(chain ?? makeClient({ url: manifest.rpc }), manifest, clean) : null;
113
158
  const mode = action === "setup" ? modeOf(manifest, clean) : null;
114
159
  let policy = published;
115
160
  if (action === "setup" && policy === undefined && mode === "fast-start") {
@@ -128,6 +173,7 @@ export async function createSignLink({ manifest, action, args = {}, ttlMs, publi
128
173
  now,
129
174
  ...(policy ? { published: policy } : {}),
130
175
  ...(oneStep ? { v2: oneStep } : {}),
176
+ ...(withdrawal ?? {}),
131
177
  });
132
178
  const nonce = randomBytes(32).toString("hex");
133
179
  /* A sequence that waits for each step to be mined cannot fit in the window a single
@@ -590,6 +636,13 @@ const txHashes = [];
590
636
  let refs = {};
591
637
  let next = 0;
592
638
 
639
+ // Said once, before anything is sent, when the wallet that connects is one of the agents this
640
+ // card lets spend. Nothing on chain forbids it, and it defeats the vault: an agent holding the
641
+ // owner's key can withdraw, which no limit covers. It is a notice and not a refusal -- pressing
642
+ // the button again goes ahead, and it is not asked twice.
643
+ const SAME_WALLET = "This wallet is also the agent you are about to let spend. An agent that holds the owner's key is not limited by the vault at all: it could withdraw everything. Use a different address for the agent, or press the button again to continue anyway.";
644
+ let sameWalletSaid = false;
645
+
593
646
  async function mined(p, hash) {
594
647
  for (let n = 0; n < 240; n++) {
595
648
  const r = await p.request({ method: "eth_getTransactionReceipt", params: [hash] });
@@ -613,6 +666,16 @@ async function run() {
613
666
  const from = accounts[0];
614
667
  if (!from) throw new Error("no account");
615
668
 
669
+ const agents = (P.agentAddresses || []).map((a) => String(a).toLowerCase());
670
+ if (!sameWalletSaid && agents.indexOf(String(from).toLowerCase()) >= 0) {
671
+ sameWalletSaid = true;
672
+ go.disabled = false;
673
+ go.textContent = "Continue anyway";
674
+ show("plan");
675
+ msg(SAME_WALLET, "warn");
676
+ return;
677
+ }
678
+
616
679
  const chainId = await p.request({ method: "eth_chainId" });
617
680
  if (chainId.toLowerCase() !== NET.chainId.toLowerCase()) {
618
681
  msg("Switching network…");
@@ -751,12 +814,24 @@ export async function startSignLink({ argv, connect, print = console.log }) {
751
814
  print(`\nbuoy owner <action> — prepare an owner action and open a sign-link\n`);
752
815
  print(` actions: ${ACTION_NAMES.join(", ")}\n`);
753
816
  print(` e.g. buoy owner add-agent --agent 0x… --name assistant --via vault`);
817
+ print(` buoy owner withdraw --amount 0.10 take USDT0 out of your vault (or --amount all)`);
818
+ print(` buoy owner setup --finish 0x<tx hash> record a setup whose result never came back`);
754
819
  print(` buoy owner setup --agent 0x… --ceiling 100 --agent-name Primary --can both
755
820
  buoy owner setup --template --agent 0x… publish the shared Fast Start policy (owner, once)\n`);
756
821
  return;
757
822
  }
758
823
 
759
824
  const { m, chain } = connect();
825
+
826
+ /* A setup whose result never reached the process that issued its link: finish it from the
827
+ transaction hash in the owner's own wallet history. See finishPendingSetup. */
828
+ if (action === "setup" && argv.includes("--finish")) {
829
+ const done = await finishPendingSetup(chain, m, flag("finish"));
830
+ print(`\n ${done.say.split("\n").join("\n ")}\n`);
831
+ if (!done.live) process.exitCode = 1;
832
+ return;
833
+ }
834
+
760
835
  const args = {
761
836
  name: flag("name"),
762
837
  agent: flag("agent"),
@@ -766,13 +841,21 @@ export async function startSignLink({ argv, connect, print = console.log }) {
766
841
  ceiling: flag("ceiling"),
767
842
  agentName: flag("agent-name"),
768
843
  can: flag("can"),
844
+ // withdraw: how much (a figure in whole tokens, or "all"), of what, and where to.
845
+ amount: flag("amount"),
846
+ amountBaseUnits: flag("amount-base-units"),
847
+ token: flag("token"),
848
+ to: flag("to"),
769
849
  /* Bare switches. --template PUBLISHES the shared Fast Start policy (the circuit holder only);
770
850
  --independent asks for a policy of your own even where a shared one exists. */
771
851
  template: argv.includes("--template") || undefined,
772
852
  independent: argv.includes("--independent") || undefined,
773
853
  };
774
854
 
775
- const link = await createSignLink({ manifest: m, action, args });
855
+ const link = await createSignLink({ manifest: m, action, args, chain });
856
+ /* Written down before the link is shown: if this command is closed or times out before the
857
+ approval comes back, the setup can still be finished from its transaction hash. */
858
+ if (action === "setup") writePendingSetup(m, link.payload, { ttlMs: link.ttlMs });
776
859
  print(`\n${link.payload.summary}\n`);
777
860
  for (const [k, v] of link.payload.card?.rows ?? []) print(` ${k.padEnd(14)} ${v}`);
778
861
  if (link.payload.card?.disclosure) print(`\n ${link.payload.card.disclosure}`);
@@ -782,10 +865,18 @@ export async function startSignLink({ argv, connect, print = console.log }) {
782
865
  for (const d of link.payload.detail) print(` · ${d}`);
783
866
  print(`\n Approve it here (this link works once, and expires in ${Math.round(link.ttlMs / 60000)} minutes):\n`);
784
867
  print(` ${link.url}\n`);
868
+ print(` Leave this command running until you have approved: it is what the page reports back to.`);
869
+ if (action === "setup") {
870
+ print(` If it is closed first, the vault is still made and still yours — record it afterwards with`);
871
+ print(` buoy owner setup --finish <the transaction hash from your wallet's history>`);
872
+ }
873
+ print("");
785
874
 
786
875
  const res = await link.result;
787
876
  if (res.rejected) {
788
877
  const got = res.completed?.length ?? 0;
878
+ // Declined or expired with nothing sent: there is no setup left to finish.
879
+ if (action === "setup" && got === 0) clearPendingSetup(m);
789
880
  print(` Not done: ${res.reason}`);
790
881
  if (got) print(` ${got} of ${link.payload.txs.length} steps had already gone through; the vault they made is unfinished and holds nothing.`);
791
882
  print("");
@@ -31,7 +31,7 @@ import { keccak } from "../src/policy-binding.mjs";
31
31
  import { SWAP_ROUTER02, WOKB } from "../src/xlayer.mjs";
32
32
  import { encodeInstallBinding, encodeCreateWalletV2, tablesFromCanonicalJson } from "./abi.mjs";
33
33
  import { ActionError } from "./errors.mjs";
34
- import { writeWalletFile, writeFastStartFile } from "../mcp/manifest.mjs";
34
+ import { writeWalletFile, writeFastStartFile, readPendingSetup, clearPendingSetup } from "../mcp/manifest.mjs";
35
35
  import {
36
36
  assetEntry, genericTablesJson, buildFastStartRecord, sharedPolicyDisclosures, sharedPolicyLine, FAST_START_SECONDS,
37
37
  } from "./faststart.mjs";
@@ -599,6 +599,9 @@ export function planSetup(m, a = {}) {
599
599
  summary,
600
600
  detail,
601
601
  card: { title, rows: glance, disclosure, more: rows },
602
+ /* Every address this card lets spend. The page compares them with the wallet that connects:
603
+ an agent that is also the owner is not limited by the vault at all. */
604
+ agentAddresses: plan.agents.map((g) => g.address),
602
605
  /* Run in the page, against the connected account, before step 1. A Fast Start has none: it
603
606
  needs no signature, so there is no wallet that cannot finish it. */
604
607
  preflight:
@@ -839,5 +842,68 @@ export async function finishSetup(chain, m, payload, txHashes, env = process.env
839
842
  },
840
843
  env
841
844
  );
845
+ // Recorded. Whatever was written down when the link was issued has done its job.
846
+ clearPendingSetup(m, env);
842
847
  return { live: true, published: p.mode === "template" ? true : undefined, seen, walletFile, fastStartFile, say: liveMessage(m, payload, seen), policy: published };
843
848
  }
849
+
850
+ /**
851
+ * Finish a setup whose result never came back, from its transaction hash.
852
+ *
853
+ * The card reports to the process that issued the link. If that process is gone when the person
854
+ * approves -- a shell command that timed out, an MCP server that restarted -- the transaction is
855
+ * mined, the vault is theirs, and no file here says so. The plan was written down when the link
856
+ * was issued (see `writePendingSetup`), so the same confirmation can be run later against the
857
+ * hash from the person's own wallet history.
858
+ *
859
+ * TWO THINGS THIS WILL NOT DO. It will not adopt a vault from a hash alone, with no setup
860
+ * outstanding: the checks below are only as good as the plan they are checked against. And it
861
+ * will not look the transaction up by itself. A scan for "a vault matching this plan" would
862
+ * adopt whichever was mined first, and anyone watching the mempool can make one that matches --
863
+ * same name, same limit, same agent -- owned by them; the tools would then tell the person to
864
+ * fund it. The hash must come from the person, and the result names the owner and asks them to
865
+ * check it is theirs before they send anything.
866
+ */
867
+ export async function finishPendingSetup(chain, m, txHash, env = process.env) {
868
+ if (!/^0x[0-9a-fA-F]{64}$/.test(String(txHash ?? ""))) {
869
+ return {
870
+ live: false,
871
+ problem: "bad-tx-hash",
872
+ say: "That is not a transaction hash. It is 0x followed by 64 characters; your wallet's history shows it for the setup you approved.",
873
+ };
874
+ }
875
+ const pending = readPendingSetup(m, env);
876
+ if (!pending) {
877
+ return {
878
+ live: false,
879
+ problem: "no-pending-setup",
880
+ say:
881
+ "No setup is outstanding on this machine, so there is nothing to finish. A transaction hash on its own " +
882
+ "is not enough to adopt a vault: the setup has to have been started here.",
883
+ };
884
+ }
885
+ if (pending.plan.mode === "template") {
886
+ return {
887
+ live: false,
888
+ problem: "template-needs-its-own-run",
889
+ say: "Publishing the shared policy cannot be finished from one hash: its record is built from the second of nine transactions. Run it again from the terminal that started it.",
890
+ };
891
+ }
892
+ const done = await finishSetup(chain, m, { action: "setup", plan: pending.plan }, [txHash], env);
893
+ if (!done.live) {
894
+ return {
895
+ ...done,
896
+ problem: done.seen?.problem ?? "does-not-match",
897
+ say:
898
+ `That transaction is not the setup that was started here: ${done.seen?.say ?? "it is missing — " + (done.seen?.failed ?? []).join("; ")}. ` +
899
+ `Nothing was recorded, and the setup is still outstanding. Check the hash in your wallet's history.`,
900
+ };
901
+ }
902
+ return {
903
+ ...done,
904
+ recovered: true,
905
+ say:
906
+ `${done.say}\nThis vault is owned by ${done.seen.owner}. That hash came from you, so check it is your own ` +
907
+ `OKX Wallet address before you send the vault anything.`,
908
+ };
909
+ }
@@ -0,0 +1,54 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // What an amount means, in one place.
3
+ //
4
+ // Imported by the read engine (ts/mcp/views.mjs) for `buoy pay` and `buoy swap`, and by the owner's
5
+ // approval card (ts/approve/) for a withdrawal, so a figure a person writes is read the same way
6
+ // wherever they write it. Nothing here touches the chain or a key.
7
+
8
+ export class AmountError extends Error {
9
+ constructor(code, detail) {
10
+ super(detail ? `${code}: ${detail}` : code);
11
+ this.code = code;
12
+ }
13
+ }
14
+
15
+ /**
16
+ * What a person writes, in the token's own units, as base units.
17
+ *
18
+ * `amount` used to MEAN base units, and nothing said so where it mattered: asked to pay "150
19
+ * USDT0" an agent passed 150, which is 0.00015 USDT0, which rounds up to one unit of budget --
20
+ * the same as a real 0.10. Two different requests became one, and both looked fine. So a bare
21
+ * figure is now read the way it is written, and base units have their own argument and name.
22
+ *
23
+ * It refuses rather than guesses. A comma is a decimal point in half the world and a thousands
24
+ * mark in the other half, and a figure finer than the token can hold would have to be rounded
25
+ * one way or the other; both would pay an amount nobody asked for.
26
+ */
27
+ const normSymbol = (s) => String(s ?? "").toUpperCase().replace(/₮/g, "T");
28
+
29
+ export function parseAmount(text, decimals, symbol) {
30
+ const raw = String(text ?? "").trim();
31
+ const bad = () =>
32
+ new AmountError(
33
+ "bad-amount",
34
+ `"${raw}" is not an amount. Write a plain figure in the token's own units, like 150 or 0.10 — no commas, no exponent.`
35
+ );
36
+ const hit = /^\$?\s*([0-9]+)(?:\.([0-9]+))?\s*([^\s0-9.,$-]\S*)?$/.exec(raw);
37
+ if (!hit) throw bad();
38
+ const [, whole, frac = "", named] = hit;
39
+ if (named !== undefined) {
40
+ // "1e6" reaches here with "e6" in the token's place: not a name, so not a mismatch either.
41
+ if (!/^[A-Za-z₮]{2}/.test(named)) throw bad();
42
+ if (normSymbol(named) !== normSymbol(symbol)) {
43
+ throw new AmountError(
44
+ "amount-symbol-mismatch",
45
+ `the amount says ${named}, but this is in ${symbol}. Pass the bare figure, or name the token you mean.`
46
+ );
47
+ }
48
+ }
49
+ const d = Number(decimals);
50
+ if (frac.length > d) {
51
+ throw new AmountError("amount-too-precise", `${raw} has ${frac.length} decimal places and ${symbol} has ${d}`);
52
+ }
53
+ return BigInt(whole) * 10n ** BigInt(d) + BigInt((frac + "0".repeat(d)).slice(0, d) || "0");
54
+ }