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.
package/ts/mcp/chain.mjs CHANGED
@@ -45,6 +45,31 @@ export function makeClient({ url = RPC, chainId = CHAIN_ID } = {}) {
45
45
  return r.result;
46
46
  }
47
47
 
48
+ /**
49
+ * Ask the chain what a call WOULD do, as a named sender. Still `eth_call`: nothing is signed,
50
+ * nothing is sent, and nothing changes.
51
+ *
52
+ * Unlike `call`, a revert here is an ANSWER and not a failure. "The vault would revert because
53
+ * the sender is not its agent" is exactly what a caller is asking, so it comes back as
54
+ * `{ reverted: true, data, message }` and only a node that could not be asked at all throws.
55
+ * Measured on X Layer 2026-11-22: a revert arrives as error code 3 with the revert bytes in
56
+ * `error.data`, both for a custom error and for the token's own `Error(string)`.
57
+ */
58
+ async function simulate({ from, to, data, gas }, block = "latest") {
59
+ const tx = { to, data };
60
+ if (from) tx.from = from;
61
+ if (gas !== undefined && gas !== null) tx.gas = "0x" + BigInt(gas).toString(16);
62
+ const r = await post(url, { jsonrpc: "2.0", id: 1, method: "eth_call", params: [tx, block] });
63
+ if (r.error) {
64
+ const bytes = typeof r.error.data === "string" ? r.error.data : null;
65
+ if (r.error.code === 3 || bytes !== null || /revert/i.test(String(r.error.message ?? ""))) {
66
+ return { reverted: true, data: bytes ?? "0x", message: String(r.error.message ?? "") };
67
+ }
68
+ throw new RpcError("eth_call-failed", r.error.message);
69
+ }
70
+ return { reverted: false, result: r.result };
71
+ }
72
+
48
73
  /**
49
74
  * Batched eth_call, never above the measured cap, and a non-array response is treated as a
50
75
  * FAILED batch rather than an empty one.
@@ -153,6 +178,7 @@ export function makeClient({ url = RPC, chainId = CHAIN_ID } = {}) {
153
178
  url,
154
179
  chainId,
155
180
  call,
181
+ simulate,
156
182
  callMany,
157
183
  blockNumber,
158
184
  blockTimestamp,
@@ -18,7 +18,13 @@ THREE LANES, and the difference is the whole design.
18
18
  READ buoy_status, buoy_balance, buoy_agents, buoy_accounts, buoy_verify. No key, no
19
19
  risk. Start with buoy_status: it needs no arguments and says whether the wallet is
20
20
  set up at all.
21
- SPEND buoy_pay, buoy_swap. These return the EXACT UNSIGNED CALL and nothing else. You
21
+ SPEND buoy_pay, buoy_swap. AMOUNTS ARE WHOLE TOKENS, as a person writes them: "150" is
22
+ 150 USDT0 and "0.10" is ten cents. They are not base units; if you have base
23
+ units, pass them as amountBaseUnits. Each tool first asks the contract, by a
24
+ read-only simulation as the agent, what it would answer: 'simulation.outcome' is
25
+ allowed, refused (with its reason) or reverts. Relay 'say'. It needs no key and
26
+ no onchainos, so it is also the answer you have when nothing can be broadcast.
27
+ These return the EXACT UNSIGNED CALL and sign nothing. You
22
28
  broadcast it yourself with 'onchainos wallet contract-call', whose key lives in OKX
23
29
  Agentic Wallet's TEE. THIS SERVER HOLDS NO KEY AND CANNOT BROADCAST ANYTHING -- its
24
30
  chain client exposes reads only. Then pass the hash to buoy_verify.
@@ -35,9 +41,11 @@ ADDRESSES ARE NOT YOUR PROBLEM. Every tool resolves the deployment itself from d
35
41
  question about addresses.
36
42
 
37
43
  ONLY THE CONTRACT MAY REFUSE A PAYMENT. NEVER REFUSE ONE YOURSELF.
38
- If the user asks for a payment, call buoy_pay. Submit it even when you have just read the
39
- caps and are confident it will be refused. Your confidence is not the answer, and it can be
40
- wrong: caps change, a day rolls over, a sibling account's spend is released.
44
+ If the user asks for a payment, call buoy_pay. Submit it even when the simulation says it
45
+ would be refused. The simulation is the contract's answer to a question; it is not a
46
+ receipt, and it can go stale: caps change, a day rolls over, a sibling account's spend is
47
+ released. Never tell a user a payment "would pass" on arithmetic of your own -- say what the
48
+ simulation said, and if it could not be run, say that.
41
49
 
42
50
  This is not a formality. A refusal you computed is a refusal nobody can check. When the
43
51
  CONTRACT refuses, the verdict is on chain, the trace advances, the agent provably could not
@@ -50,9 +58,9 @@ ONLY THE CONTRACT MAY REFUSE A PAYMENT. NEVER REFUSE ONE YOURSELF.
50
58
  contract can rule"). What you may not do is stop there.
51
59
 
52
60
  A refusal does not revert. The call succeeds, the verdict is recorded as refused, and not one
53
- unit moves -- so there is no cost to letting the contract decide beyond gas. You see the
54
- verdict by passing the transaction hash to buoy_verify, not from buoy_pay, which only
55
- builds the call.
61
+ unit moves -- so there is no cost to letting the contract decide beyond gas. The RECORDED
62
+ verdict comes from passing the transaction hash to buoy_verify. What buoy_pay returns is a
63
+ simulation: true when it was asked, recorded nowhere.
56
64
 
57
65
  SPEAK LIKE A PERSON. NEVER SHOW A REASON CODE TO THE USER.
58
66
  Every tool returns "say" -- a plain-English sentence with the real numbers in it. RELAY "say".
@@ -12,7 +12,7 @@
12
12
  // wallet is not set up yet" rather than "you are pointed at the wrong chain". The `target`
13
13
  // field is therefore load-bearing, and it picks the RPC.
14
14
 
15
- import { readFileSync, existsSync, writeFileSync, mkdirSync } from "node:fs";
15
+ import { readFileSync, existsSync, writeFileSync, mkdirSync, rmSync } from "node:fs";
16
16
  import { homedir } from "node:os";
17
17
  import { dirname, join, resolve } from "node:path";
18
18
  import { fileURLToPath } from "node:url";
@@ -242,9 +242,16 @@ function walletReadPath(dir, declared, env) {
242
242
  return existsSync(beside) ? beside : path;
243
243
  }
244
244
 
245
+ /**
246
+ * @returns {{ wallet: object|null, ignored: {path, why}|null }}
247
+ * `ignored` is the case that used to be silent: a wallet file is THERE, and the tools go on
248
+ * reading the launch wallet anyway because it belongs to another deployment. The person who
249
+ * made that vault then sees somebody else's, with nothing said. It is still not believed --
250
+ * a different factory is a different set of contracts -- but it is reported.
251
+ */
245
252
  function readWallet(dir, declared, raw, env) {
246
253
  const path = walletReadPath(dir, declared, env);
247
- if (!path || !existsSync(path)) return null;
254
+ if (!path || !existsSync(path)) return { wallet: null, ignored: null };
248
255
  let w;
249
256
  try {
250
257
  w = JSON.parse(readFileSync(path, "utf8"));
@@ -252,11 +259,16 @@ function readWallet(dir, declared, raw, env) {
252
259
  throw new ManifestError("wallet-file-unreadable", `${path}: ${e.message}`);
253
260
  }
254
261
  const same = (a, b) => String(a ?? "").toLowerCase() === String(b ?? "").toLowerCase();
255
- if (w.target !== declared || !same(w.factory, raw.factory)) return null;
262
+ if (w.target !== declared) {
263
+ return { wallet: null, ignored: { path, why: `it is a ${w.target ?? "(unnamed)"} wallet and these tools are reading ${declared}` } };
264
+ }
265
+ if (!same(w.factory, raw.factory)) {
266
+ return { wallet: null, ignored: { path, why: `it was made by factory ${w.factory ?? "(none)"}, and this deployment's is ${raw.factory}` } };
267
+ }
256
268
  if (!ADDR.test(String(w.gatekeeper ?? "")) || !ADDR.test(String(w.vault ?? ""))) {
257
269
  throw new ManifestError("wallet-file-malformed", `${path} names no gatekeeper and vault`);
258
270
  }
259
- return { ...w, path };
271
+ return { wallet: { ...w, path }, ignored: null };
260
272
  }
261
273
 
262
274
  /**
@@ -297,6 +309,71 @@ export function writeWalletFile(m, w, env = process.env) {
297
309
  return path;
298
310
  }
299
311
 
312
+ // ---------------------------------------------------------------------------------------
313
+ // A setup that was started, and whose result has not been recorded yet
314
+ // ---------------------------------------------------------------------------------------
315
+ //
316
+ // The wallet file above is written when a setup's RESULT comes back: the card posts its
317
+ // transaction hash to the process that made the link, and that process reads the chain and
318
+ // records the vault. If that process is gone by then -- an agent's shell command that timed out,
319
+ // an MCP server that was restarted, a terminal that was closed -- the transaction is mined, the
320
+ // vault exists and is the person's, and nothing here knows. Every tool then goes on reading the
321
+ // launch wallet, and the only remedy was a second setup and a second vault.
322
+ //
323
+ // So the PLAN is written down when the link is made, beside where the wallet file will go. It
324
+ // holds what was asked for -- names, limits, addresses -- and never a key. With it, a setup can be
325
+ // finished later from its transaction hash alone, and `status` can say that one is outstanding.
326
+
327
+ const PENDINGS = {
328
+ mainnet: `pending-setup.xlayer-${CHAIN_ID}.json`,
329
+ fork: "pending-setup.fork.json",
330
+ };
331
+
332
+ /** Beside the wallet file, wherever that is. Null when BUOY_WALLET=none: nothing is recorded then. */
333
+ export function pendingSetupPath(m, env = process.env) {
334
+ const wallet = walletFilePath(join(m.root, "deployments"), m.target, env);
335
+ return wallet ? join(dirname(wallet), PENDINGS[m.target]) : null;
336
+ }
337
+
338
+ /** Record that a setup link was issued. Returns the path, or null where nothing is recorded. */
339
+ export function writePendingSetup(m, payload, { ttlMs = 0, now = Date.now() } = {}, env = process.env) {
340
+ const path = pendingSetupPath(m, env);
341
+ if (!path) return null;
342
+ const body = {
343
+ note:
344
+ "written when a buoy setup link was issued: what was asked for, so the setup can be finished from its " +
345
+ "transaction hash if the result never came back. No key is in here. Removed once the result is recorded.",
346
+ target: m.target,
347
+ factory: m.addresses.factory,
348
+ createdAt: Math.floor(now / 1000),
349
+ expiresAt: Math.floor((now + ttlMs) / 1000),
350
+ steps: payload.txs?.length ?? null,
351
+ plan: payload.plan,
352
+ };
353
+ mkdirSync(dirname(path), { recursive: true });
354
+ writeFileSync(path, JSON.stringify(body, null, 2) + "\n");
355
+ return path;
356
+ }
357
+
358
+ /** The outstanding setup for THIS deployment, or null. One from another deployment is not it. */
359
+ export function readPendingSetup(m, env = process.env) {
360
+ const path = pendingSetupPath(m, env);
361
+ if (!path || !existsSync(path)) return null;
362
+ try {
363
+ const p = JSON.parse(readFileSync(path, "utf8"));
364
+ const same = String(p.factory ?? "").toLowerCase() === String(m.addresses.factory ?? "").toLowerCase();
365
+ if (p.target !== m.target || !same || !p.plan) return null;
366
+ return { ...p, path };
367
+ } catch {
368
+ return null; // a record that cannot be read is a record of nothing
369
+ }
370
+ }
371
+
372
+ export function clearPendingSetup(m, env = process.env) {
373
+ const path = pendingSetupPath(m, env);
374
+ if (path && existsSync(path)) rmSync(path, { force: true });
375
+ }
376
+
300
377
  /** Is this URL a loopback address? Only these may serve a fork manifest. */
301
378
  export function isLoopback(url) {
302
379
  try {
@@ -362,7 +439,10 @@ export function resolveManifest({ root, target, rpc, env = process.env } = {}) {
362
439
  the stack, not to whichever vault the tools happen to be reading. */
363
440
  const fastStart = readFastStart(dir, declared, raw, env);
364
441
  const v2 = readV2(dir, declared, raw, env);
365
- const wallet = readWallet(dir, declared, raw, env);
442
+ const { wallet, ignored: walletIgnored } = readWallet(dir, declared, raw, env);
443
+ /* Whether a wallet COULD be selected at all: BUOY_WALLET=none is somebody choosing the launch
444
+ wallet out loud, which is not the same thing as never having set one up. */
445
+ const walletOff = env.BUOY_WALLET === "none";
366
446
  /* Kept before a setup wallet replaces it: the launch wallet is still one of this deployment's,
367
447
  and a receipt it issued is still one `buoy verify` can vouch for, whichever wallet the tools
368
448
  happen to be reading. */
@@ -422,6 +502,10 @@ export function resolveManifest({ root, target, rpc, env = process.env } = {}) {
422
502
  wallet: wallet
423
503
  ? { name: wallet.name ?? null, path: wallet.path, createdTx: wallet.createdTx ?? null, mode: wallet.mode ?? null }
424
504
  : null,
505
+ /* A wallet file that exists and was NOT believed, and why. Never silent: see readWallet. */
506
+ walletIgnored,
507
+ /* True when BUOY_WALLET=none chose the launch wallet on purpose. */
508
+ walletOff,
425
509
  /* Non-null when the owner has published a shared policy. Unverified as read: see faststart.mjs. */
426
510
  fastStart,
427
511
  /* Non-null when a one-transaction factory is recorded. Unverified as read: see ts/approve/v2.mjs. */
package/ts/mcp/read.mjs CHANGED
@@ -64,6 +64,18 @@ export const str = (h) => {
64
64
  return new TextDecoder().decode(Uint8Array.from(body.match(/../g).map((x) => parseInt(x, 16))));
65
65
  };
66
66
 
67
+ /** `(bool allow, uint8 reason, bytes16 word, uint256 amountUnits)`, as `preview` and `verdict` return it. */
68
+ export const verdictOf = (h) => {
69
+ const s = strip(h);
70
+ if (s.length < 256) throw new ReadError("empty-return", "the call returned no verdict; wrong address or no code");
71
+ return {
72
+ allow: BigInt("0x" + s.slice(0, 64)) !== 0n,
73
+ reason: Number(BigInt("0x" + s.slice(64, 128))),
74
+ word: "0x" + s.slice(128, 160),
75
+ amountUnits: BigInt("0x" + s.slice(192, 256)),
76
+ };
77
+ };
78
+
67
79
  /** A dynamic array of 32-byte-encoded scalars, mapped through `f`. */
68
80
  const arrayOf = (h, f) => {
69
81
  const s = strip(h);
@@ -156,6 +168,22 @@ export function makeReader(chain, m) {
156
168
  return out;
157
169
  },
158
170
 
171
+ // ---- what a spend WOULD do, asked without sending anything ------
172
+ /**
173
+ * The adapter's own read-only verdict on a payment: whether the policy and the budget allow
174
+ * it, and how many budget units the contract counts it as. It judges the ACCOUNT's budget and
175
+ * does not look at who is calling or at what the vault holds -- `simulate` does that.
176
+ */
177
+ preview: async (adapter, token, to, amount) =>
178
+ verdictOf(await call(adapter, "preview(address,address,uint256)", addrWord(token) + addrWord(to) + word(amount))),
179
+ previewSwap: async (adapter, router, tokenIn, amountIn) =>
180
+ verdictOf(await call(adapter, "previewSwap(address,address,uint256)", addrWord(router) + addrWord(tokenIn) + word(amountIn))),
181
+ /**
182
+ * The whole call, as the named sender, by `eth_call`. Absent when the client cannot do it,
183
+ * so a caller can tell "not asked" from "asked, and it said no".
184
+ */
185
+ simulate: typeof chain.simulate === "function" ? (tx) => chain.simulate(tx) : null,
186
+
159
187
  // ---- tokens -----------------------------------------------------
160
188
  balanceOf: async (token, who) => uint(await call(token, "balanceOf(address)", addrWord(who))),
161
189
  decimals: async (token) => num(await call(token, "decimals()")),
package/ts/mcp/server.mjs CHANGED
@@ -42,12 +42,12 @@ import { explain } from "./reasons.mjs";
42
42
  import { planBinding, planRevocation } from "./payloads.mjs";
43
43
  import { makeClient } from "./chain.mjs";
44
44
  import { makeReader } from "./read.mjs";
45
- import { resolveManifest, describe, ManifestError, isCheckout } from "./manifest.mjs";
45
+ import { resolveManifest, describe, ManifestError, isCheckout, writePendingSetup, clearPendingSetup } from "./manifest.mjs";
46
46
  import {
47
47
  statusView, balanceView, agentsView, planPayment, planSwap, planFetch, verifyTransaction, knownNames,
48
48
  } from "./views.mjs";
49
49
  import { ACTION_NAMES } from "../approve/actions.mjs";
50
- import { finishSetup } from "../approve/setup.mjs";
50
+ import { finishSetup, finishPendingSetup } from "../approve/setup.mjs";
51
51
  import { describeLink } from "../approve/server.mjs";
52
52
  import { CHAIN_ID } from "../src/xlayer.mjs";
53
53
 
@@ -173,18 +173,35 @@ server.tool(
173
173
 
174
174
  server.tool(
175
175
  "buoy_pay",
176
- "Build a payment from the wallet. Returns the exact call to broadcast with `onchainos wallet " +
176
+ "Build a payment from the wallet, and ask the contract what it would answer. `amount` is in " +
177
+ "WHOLE TOKENS as a person writes them: \"150\" is 150 USDT0 and \"0.10\" is ten cents. It is " +
178
+ "NOT base units. The call is simulated on chain as the agent before anything is sent, and " +
179
+ "`simulation` carries the contract's own answer: `allowed`, `refused` with its reason, or " +
180
+ "`reverts` with the error -- relay `say`, which has the real figures in it. It needs no " +
181
+ "`onchainos` and no key. Returns the exact call to broadcast with `onchainos wallet " +
177
182
  "contract-call` using the AGENT's key -- this server holds no key and cannot send it. " +
178
- "SUBMIT IT EVEN IF `expectation` SAYS IT LOOKS OVER BUDGET: only the contract may refuse, " +
179
- "and its refusal comes with a receipt buoy_verify can replay. Then verify the hash.",
183
+ "SUBMIT IT EVEN IF THE SIMULATION SAYS REFUSED: only a broadcast leaves the refusal on " +
184
+ "chain with a receipt buoy_verify can replay. Then verify the hash. If there is no way to " +
185
+ "broadcast on this machine, say what the simulation said and that nothing was sent.",
180
186
  {
181
187
  to: z.string().describe("who is being paid"),
182
- amount: z.string().describe("in the token's base units, e.g. 5000000 for 5 USDT0"),
188
+ amount: z
189
+ .string()
190
+ .optional()
191
+ .describe('in whole tokens, as written: "150" for 150 USDT0, "0.10" for ten cents. Not base units'),
192
+ amountBaseUnits: z
193
+ .string()
194
+ .optional()
195
+ .describe('instead of amount: the exact figure in base units, e.g. "5000000" for 5 USDT0. Never both'),
183
196
  token: z.string().optional().describe("defaults to the settlement token"),
184
197
  from: z
185
198
  .string()
186
199
  .optional()
187
200
  .describe('which account, by name: "vault", "safe", or a name from buoy_agents/buoy_status'),
201
+ agent: z
202
+ .string()
203
+ .optional()
204
+ .describe("the address that will send it, for the simulation. Defaults to the agent this vault was set up with"),
188
205
  },
189
206
  async (a) =>
190
207
  guard(async () => {
@@ -197,7 +214,9 @@ server.tool(
197
214
  "buoy_swap",
198
215
  "Build a swap through an owner-allowlisted router. A swap presents kind 0, which most policies " +
199
216
  "refuse -- that refusal is the point and it is recorded on chain. The output is forced back " +
200
- "to the vault, so it cannot leave custody. Broadcast it the same way as buoy_pay.",
217
+ "to the vault, so it cannot leave custody. `amountIn` and `minAmountOut` are WHOLE TOKENS, " +
218
+ "each in its own token: \"10\" USDT0 in, \"0.1\" WOKB out. Like buoy_pay it is simulated on " +
219
+ "chain first and `simulation` carries the contract's answer. Broadcast it the same way.",
201
220
  {
202
221
  router: z.string().optional().describe("defaults to Uniswap V3 SwapRouter02, the one a setup allows"),
203
222
  tokenIn: z.string().optional().describe("defaults to the settlement token, USDT0"),
@@ -206,9 +225,15 @@ server.tool(
206
225
  .optional()
207
226
  .describe("defaults to WOKB. Must be on the vault's allowlist, or the call reverts"),
208
227
  fee: z.number().int().optional().describe("the V3 pool fee tier; defaults to 500"),
209
- amountIn: z.string(),
210
- minAmountOut: z.string().describe("never 0: a swap with no floor is a donation"),
228
+ amountIn: z.string().optional().describe('how much to give, in whole tokens of tokenIn: "10" for 10 USDT0'),
229
+ amountInBaseUnits: z.string().optional().describe("instead of amountIn: the exact figure in base units"),
230
+ minAmountOut: z
231
+ .string()
232
+ .optional()
233
+ .describe('the least to accept, in whole tokens of tokenOut: "0.1" for 0.1 WOKB. Never 0: a swap with no floor is a donation'),
234
+ minAmountOutBaseUnits: z.string().optional().describe("instead of minAmountOut: the exact figure in base units"),
211
235
  from: z.string().optional(),
236
+ agent: z.string().optional().describe("the address that will send it, for the simulation"),
212
237
  },
213
238
  async (a) =>
214
239
  guard(async () => {
@@ -272,10 +297,15 @@ server.tool(
272
297
  "Ask the human to approve an owner action. FIRST-TIME SETUP IS `action: \"setup\"`: one link " +
273
298
  "that creates the vault, switches its policy on, sets the daily ceiling and lets the first " +
274
299
  "agent spend -- pass `agent` (your own wallet address) plus any of name, ceiling, agentName, " +
275
- "can. The other actions change a wallet that already exists: letting an agent spend, " +
276
- "revoking one, renaming something, changing a budget. NEVER ask the user for a private key " +
300
+ "can. The agent address must NOT be the owner's own wallet: an agent holding the owner's key " +
301
+ "is not limited by the vault. The other actions change a wallet that already exists: letting " +
302
+ "an agent spend, revoking one, renaming something, changing a budget -- and `withdraw`, the " +
303
+ "owner taking funds out of the vault (pass `amount` in whole tokens or \"all\", and `to`; no " +
304
+ "agent can do this and it does not go through the budget). NEVER ask the user for a private key " +
277
305
  "or seed phrase, and never accept one: this returns a short-lived link they open and approve " +
278
- "once in their own OKX Wallet. Give them the link, then call buoy_owner_action_result.",
306
+ "once in their own OKX Wallet. Give them the link, then call buoy_owner_action_result. THIS " +
307
+ "SERVER MUST STAY RUNNING until they have approved: the page reports back to it. Do not " +
308
+ "restart the agent or the MCP between giving the link and reading the result.",
279
309
  {
280
310
  action: z.enum(ACTION_NAMES),
281
311
  name: z.string().optional().describe("a label, 32 bytes at most"),
@@ -283,6 +313,12 @@ server.tool(
283
313
  via: z.enum(["vault", "safe"]).optional().describe("which account it applies to"),
284
314
  node: z.number().int().optional().describe("a budget node id"),
285
315
  units: z.string().optional().describe("a daily cap, in the policy's units"),
316
+ amount: z
317
+ .string()
318
+ .optional()
319
+ .describe('withdraw: how much, in whole tokens as written ("0.10", "25"), or "all" for everything the vault holds'),
320
+ to: z.string().optional().describe("withdraw: the address the funds go to. Default: the vault's owner"),
321
+ token: z.string().optional().describe("withdraw: which token. Default: the settlement token, USDT0"),
286
322
  ceiling: z
287
323
  .string()
288
324
  .optional()
@@ -319,9 +355,13 @@ server.tool(
319
355
  },
320
356
  async ({ action, ...args }) =>
321
357
  guard(async () => {
322
- const { m } = connect();
358
+ const { m, chain } = connect();
323
359
  const { createSignLink } = await import("../approve/server.mjs");
324
- const link = await createSignLink({ manifest: m, action, args });
360
+ const link = await createSignLink({ manifest: m, action, args, chain });
361
+ /* Written down before the link is handed over. If this process is restarted before the
362
+ approval comes back, the vault is still made and is still theirs; this is what lets it
363
+ be recorded afterwards, from the transaction hash, instead of read past for ever. */
364
+ if (action === "setup") writePendingSetup(m, link.payload, { ttlMs: link.ttlMs });
325
365
  const handle = randomBytes(6).toString("hex");
326
366
  pending.set(handle, link);
327
367
  link.result.then(() => setTimeout(() => pending.delete(handle), 60_000));
@@ -329,7 +369,13 @@ server.tool(
329
369
  handle,
330
370
  url: link.url,
331
371
  ...describeLink(link),
332
- next: `Call buoy_owner_action_result with handle "${handle}" once they have clicked.`,
372
+ next:
373
+ `Call buoy_owner_action_result with handle "${handle}" once they have clicked. Keep this server running ` +
374
+ `until then.` +
375
+ (action === "setup"
376
+ ? ` If the handle is ever unknown -- the server was restarted -- ask the user for the setup's transaction hash ` +
377
+ `from their wallet's history and call buoy_owner_action_result with txHash instead.`
378
+ : ""),
333
379
  });
334
380
  })
335
381
  );
@@ -338,19 +384,48 @@ server.tool(
338
384
  "buoy_owner_action_result",
339
385
  "Wait for the human to finish with a sign-link from buoy_request_owner_action. Returns " +
340
386
  "`pending` if they have not clicked yet -- call it again rather than assuming either outcome, " +
341
- "and never tell the user something was done before this says so.",
387
+ "and never tell the user something was done before this says so. If a SETUP's handle is no " +
388
+ "longer known (the server restarted, or the link was made from the command line), pass " +
389
+ "`txHash` instead: the hash of the setup transaction from the user's own wallet history. " +
390
+ "That records the vault they made, after checking it against what was asked for. Relay its " +
391
+ "`say`, which names the vault's owner so they can confirm it is theirs.",
342
392
  {
343
- handle: z.string(),
393
+ handle: z.string().optional().describe("from buoy_request_owner_action"),
394
+ txHash: z
395
+ .string()
396
+ .optional()
397
+ .describe("setup only, when the handle is gone: the setup transaction's hash, from the user's wallet history"),
344
398
  waitSeconds: z.number().int().min(1).max(120).optional().describe("how long to wait, default 60"),
345
399
  },
346
- async ({ handle, waitSeconds }) =>
400
+ async ({ handle, txHash, waitSeconds }) =>
347
401
  guard(async () => {
348
- const link = pending.get(handle);
402
+ const link = handle ? pending.get(handle) : undefined;
403
+ if (!link && txHash) {
404
+ const { m, chain } = connect();
405
+ const done = await finishPendingSetup(chain, m, txHash);
406
+ if (!done.live) return text({ ok: false, status: "not-recorded", problem: done.problem, say: done.say });
407
+ return text({
408
+ status: "approved",
409
+ live: true,
410
+ recovered: true,
411
+ vault: done.seen.vault,
412
+ depositAddress: done.seen.vault,
413
+ gatekeeper: done.seen.gatekeeper,
414
+ owner: done.seen.owner,
415
+ checks: done.seen.checks,
416
+ txHashes: [txHash],
417
+ walletFile: done.walletFile,
418
+ say: done.say,
419
+ });
420
+ }
349
421
  if (!link) {
350
422
  return text({
351
423
  ok: false,
352
424
  problem: "unknown-handle",
353
- say: "That approval link is finished or expired. Ask for a new one if it still needs doing.",
425
+ say:
426
+ "That approval link is finished or expired, or this server was restarted since it was made. " +
427
+ "If it was a setup and the user approved it, ask them for the transaction hash from their wallet's " +
428
+ "history and call this again with txHash. Otherwise ask for a new link.",
354
429
  });
355
430
  }
356
431
  const timeout = new Promise((res) => setTimeout(() => res("pending"), (waitSeconds ?? 60) * 1000));
@@ -368,6 +443,8 @@ server.tool(
368
443
  /* "Nothing was done" is only true if nothing was. A setup declined at step 6 has already
369
444
  created a vault, and telling the user otherwise would be the one false sentence here. */
370
445
  const got = res.completed?.length ?? 0;
446
+ // Declined or expired with nothing sent: there is no setup left to finish.
447
+ if (link.payload.action === "setup" && got === 0) clearPendingSetup(connect().m);
371
448
  return text({
372
449
  status: "rejected",
373
450
  reason: res.reason,