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/views.mjs CHANGED
@@ -20,12 +20,13 @@ import { createHash } from "node:crypto";
20
20
  import { readFileSync, readdirSync, existsSync } from "node:fs";
21
21
  import { join } from "node:path";
22
22
  import { selectorOf } from "./chain.mjs";
23
- import { units, word, uint, addrWord } from "./read.mjs";
23
+ import { units, word, uint, addrWord, str } from "./read.mjs";
24
24
  import { vouchForGatekeeper } from "./provenance.mjs";
25
25
  import { payCall, swapCall } from "./payloads.mjs";
26
+ import { parseAmount } from "./amount.mjs";
26
27
  import { verifyReceipt } from "./receipt.mjs";
27
- import { explain } from "./reasons.mjs";
28
- import { adapterForNode, describe } from "./manifest.mjs";
28
+ import { explain, reasonName } from "./reasons.mjs";
29
+ import { adapterForNode, describe, readPendingSetup } from "./manifest.mjs";
29
30
  import { fetchChallenge, selectOffer, describeOffer } from "./x402.mjs";
30
31
  import { keccak } from "../src/policy-binding.mjs";
31
32
  import { parsePolicyFile, evalGasInternal } from "../src/policy-file.mjs";
@@ -37,6 +38,8 @@ const PRESENTED_TOPIC = keccak(
37
38
  new TextEncoder().encode("Presented(bytes32,address,uint32,uint256,bytes16,bool,uint8,uint256,bytes32)")
38
39
  ).toLowerCase();
39
40
 
41
+ export { parseAmount };
42
+
40
43
  export class ViewError extends Error {
41
44
  constructor(code, detail) {
42
45
  super(detail ? `${code}: ${detail}` : code);
@@ -51,7 +54,25 @@ const UNCAPPED = 2n ** 128n;
51
54
 
52
55
  // ------------------------------------------------------------------ status
53
56
 
54
- export async function statusView(r) {
57
+ /** How long an unfinished setup is worth mentioning. The record stays; the reminder does not. */
58
+ const PENDING_SAID_FOR = 7 * 24 * 3600;
59
+
60
+ /**
61
+ * Whose vault these answers are about, in a sentence -- for every answer that could be mistaken
62
+ * for being about somebody's own. A person who has set a vault up and is shown the deployment's
63
+ * launch vault instead sees real budgets and a real owner, and nothing in the figures says they
64
+ * are not theirs. So it is said, by the tools, every time it is the case.
65
+ */
66
+ export function whoseVault(m, owner) {
67
+ if (m.wallet) return "";
68
+ if (m.walletOff) return "Reading the deployment's launch vault, because BUOY_WALLET=none asks for it. ";
69
+ return (
70
+ `This is the vault the deployment was launched with${owner ? `, owned by ${owner}` : ""} — ` +
71
+ `not one set up on this machine. `
72
+ );
73
+ }
74
+
75
+ export async function statusView(r, { env = process.env, now = Date.now() } = {}) {
55
76
  const m = r.manifest;
56
77
  const [installed, nodeCount, owner] = await Promise.all([
57
78
  r.installed(),
@@ -93,6 +114,34 @@ export async function statusView(r) {
93
114
  });
94
115
  }
95
116
 
117
+ /* A setup whose link was issued here and whose result was never recorded. See
118
+ writePendingSetup: the vault may exist, be this person's, and be unknown to every tool. */
119
+ let pending = null;
120
+ try {
121
+ const p = readPendingSetup(m, env);
122
+ if (p && Math.floor(now / 1000) - Number(p.createdAt ?? 0) < PENDING_SAID_FOR) {
123
+ pending = {
124
+ name: p.plan?.name ?? null,
125
+ mode: p.plan?.mode ?? null,
126
+ startedAt: new Date(Number(p.createdAt) * 1000).toISOString(),
127
+ file: p.path,
128
+ };
129
+ }
130
+ } catch {
131
+ pending = null; // a manifest with nowhere to keep one has none
132
+ }
133
+ const usdt = m.addresses.usdt ?? null;
134
+ const notes =
135
+ whoseVault(m, owner) +
136
+ (m.walletIgnored
137
+ ? `A wallet file at ${m.walletIgnored.path} was NOT read: ${m.walletIgnored.why}. `
138
+ : "") +
139
+ (pending
140
+ ? `A setup of "${pending.name}" was started here on ${pending.startedAt.slice(0, 10)} and its result was never recorded. ` +
141
+ `If it was approved, finish it with its transaction hash, which the wallet's history shows: ` +
142
+ `buoy_owner_action_result with txHash, or \`buoy owner setup --finish <transaction hash>\`. `
143
+ : "");
144
+
96
145
  return {
97
146
  where: describe(m),
98
147
  target: m.target,
@@ -104,6 +153,16 @@ export async function statusView(r) {
104
153
  /* "setup" when a person made this wallet through the sign-link, "launch" when it is the one
105
154
  the deployment itself built. An agent needs the difference to answer "is this mine?". */
106
155
  createdBy: m.wallet ? "setup" : "launch",
156
+ /* The file that says which vault is read, when one does. */
157
+ walletFile: m.wallet?.path ?? null,
158
+ walletIgnored: m.walletIgnored ?? null,
159
+ pendingSetup: pending,
160
+ /* The one address to send funds to. Named for what it is, because the token's own address
161
+ sits beside it in these answers and has been taken for it. */
162
+ depositAddress: m.addresses.vault,
163
+ token: usdt
164
+ ? { address: usdt, note: "The USDT0 token contract. Never send funds to this address: fund the vault at depositAddress." }
165
+ : null,
107
166
  owner,
108
167
  active: installed,
109
168
  budgetNodes: nodeCount,
@@ -111,13 +170,13 @@ export async function statusView(r) {
111
170
  policies: Object.keys(m.policies),
112
171
  policy,
113
172
  disclosures,
114
- say: installed
173
+ say: notes + (installed
115
174
  ? `The wallet is active on ${m.isFork ? "a local rehearsal" : "X Layer"}, with ${nodeCount} ` +
116
175
  `budget node${nodeCount === 1 ? "" : "s"}${named.length ? " named " + named.map((n) => n.name).join(", ") : ""}.` +
117
176
  (policy.revoked ? " Its policy has been REVOKED, so it can no longer spend; the owner can still withdraw." : "") +
118
177
  (disclosures.length ? " " + disclosures.join(" ") : "")
119
178
  : `The wallet exists but is not enforcing yet: the owner still has to install the policy, ` +
120
- `which only they can sign. Nothing is broken.`,
179
+ `which only they can sign. Nothing is broken.`),
121
180
  };
122
181
  }
123
182
 
@@ -155,13 +214,18 @@ export async function balanceView(r, { token } = {}) {
155
214
  }
156
215
 
157
216
  return {
158
- token: { address: t, symbol, decimals },
217
+ token: { address: t, symbol, decimals, note: `The ${symbol} token contract. Never send funds to this address.` },
218
+ createdBy: m.wallet ? "setup" : "launch",
219
+ depositAddress: m.addresses.vault ?? null,
159
220
  accounts,
160
- say: accounts.length
161
- ? accounts
162
- .map((a) => `${a.name ?? a.via} holds ${a.balance} with ${a.remainingTodayUnits} ${symbol} left to spend today`)
163
- .join("; ") + "."
164
- : "No spending account is recorded in the manifest.",
221
+ say:
222
+ whoseVault(m, null) +
223
+ (accounts.length
224
+ ? accounts
225
+ .map((a) => `${a.name ?? a.via} holds ${a.balance} with ${a.remainingTodayUnits} ${symbol} left to spend today`)
226
+ .join("; ") + "." +
227
+ (m.addresses.vault ? ` To fund it, send ${symbol} to the vault at ${m.addresses.vault} — not to the token's own address.` : "")
228
+ : "No spending account is recorded in the manifest."),
165
229
  };
166
230
  }
167
231
 
@@ -238,17 +302,6 @@ export async function knownNames(r) {
238
302
  return { nodes, builtin: ["vault", m.addresses.safeModule ? "safe" : null].filter(Boolean) };
239
303
  }
240
304
 
241
- // ------------------------------------------------------------------ units
242
-
243
- /**
244
- * How many whole budget units a payment of `amount` base units costs. Rounded UP, exactly as
245
- * `PolicyWord.fields` does on chain, so the advice and the debit cannot disagree.
246
- */
247
- export const unitsCeil = (amount, unit) => {
248
- const a = BigInt(amount);
249
- return a === 0n ? 0n : (a - 1n) / BigInt(unit) + 1n;
250
- };
251
-
252
305
  // ------------------------------------------------------------------ gas
253
306
 
254
307
  /** `FloatGatekeeper.policyGasFloor`, plus the headroom every spend has always been sent with. */
@@ -292,19 +345,226 @@ export async function spendGasLimit(r, { policyDir } = {}) {
292
345
  return limit.toString();
293
346
  }
294
347
 
348
+ // ------------------------------------------------------------------ amounts
349
+
350
+ /** One amount, given once: as a person writes it, or as exact base units. Null when neither. */
351
+ function amountOf(human, base, decimals, symbol, what) {
352
+ const has = (v) => v !== undefined && v !== null && String(v).trim() !== "";
353
+ if (has(human) && has(base)) {
354
+ throw new ViewError("amount-ambiguous", `${what} was given twice, as ${human} and as ${base} base units. Pass one.`);
355
+ }
356
+ if (has(base)) {
357
+ const s = String(base).trim();
358
+ if (!/^[0-9]+$/.test(s)) throw new ViewError("bad-amount", `${what}: base units are a whole number, got "${s}"`);
359
+ return BigInt(s);
360
+ }
361
+ return has(human) ? parseAmount(human, decimals, symbol) : null;
362
+ }
363
+
364
+ // ------------------------------------------------------------------ asking the contract first
365
+
366
+ /** Errors the vault, the gatekeeper and the token raise, by selector. */
367
+ const KNOWN_ERRORS = [
368
+ "NotAgent(address)", "NotOwner()", "TokenNotAllowed(address)", "RouterNotAllowed(address)", "SameToken(address)",
369
+ "ZeroMinimumOut()", "NoSwapOutput(address)", "SwapOutputTooLow(address,uint256,uint256)",
370
+ "OutflowExceeded(address,uint256,uint256)", "CollateralOutflow(address,uint256)", "NoOutflow(address,uint256)",
371
+ "LingeringAllowance(address,address,uint256)", "NotInstalled()", "BindingIsRevoked()", "BindingNotYet()",
372
+ "BindingExpired()", "AccountNotBound(address)", "NotTheBoundAdapter(address,address)",
373
+ "AgentNodeOutsideAccount(uint32,uint32)", "NoPolicyOnPath()", "InsufficientGasForPolicy(uint256,uint256)",
374
+ "ERC20InsufficientBalance(address,uint256,uint256)",
375
+ ];
376
+ const ERROR_BY_SELECTOR = new Map(KNOWN_ERRORS.map((sig) => [selectorOf(sig).toLowerCase(), sig.slice(0, sig.indexOf("("))]));
377
+ const ERROR_STRING = "0x08c379a0"; // Error(string), what `require` and older tokens revert with
378
+
379
+ /** Name a revert from the bytes the node returned. An unrecognised one is said to be unknown. */
380
+ export function decodeRevert(rev) {
381
+ const data = String(rev?.data ?? "0x").toLowerCase();
382
+ const message = String(rev?.message ?? "");
383
+ if (data.startsWith(ERROR_STRING)) {
384
+ let text = "";
385
+ try {
386
+ text = str("0x" + data.slice(10));
387
+ } catch {
388
+ text = "";
389
+ }
390
+ return { name: "Error", text };
391
+ }
392
+ const name = data.length >= 10 ? ERROR_BY_SELECTOR.get(data.slice(0, 10)) : undefined;
393
+ if (name) return { name, text: "" };
394
+ // Some nodes give only a sentence. It is the token's or the router's own, so it is kept.
395
+ const tail = /execution reverted:\s*(.+)$/i.exec(message);
396
+ if (data.length < 10 && tail) return { name: "Error", text: tail[1] };
397
+ return { name: "unknown", selector: data.length >= 10 ? data.slice(0, 10) : null, text: message };
398
+ }
399
+
400
+ const short = (a) => `${String(a).slice(0, 6)}…${String(a).slice(-4)}`;
401
+
402
+ /** Why the policy said no, in words, with the figures the contract itself returned. */
403
+ function whyRefused(reason, { left, wantUnits, symbol }) {
404
+ switch (reason) {
405
+ case 1:
406
+ return "it is more than this budget allows in one request";
407
+ case 2:
408
+ return wantUnits !== null
409
+ ? `it is over today's budget: ${left} ${symbol} left, and this asks for ${wantUnits}`
410
+ : `it is over today's budget: ${left} ${symbol} left`;
411
+ case 3:
412
+ return "that recipient is not on this budget's approved list";
413
+ case 4:
414
+ return "that token is not one this budget may spend";
415
+ case 5:
416
+ return "this budget is outside its allowed hours right now";
417
+ case 6:
418
+ return "that token is not in the signed tables, so the amount cannot be counted";
419
+ case 7:
420
+ return "this budget does not allow that kind of request";
421
+ default:
422
+ return `the policy gave ${reasonName(reason)} as its reason`;
423
+ }
424
+ }
425
+
426
+ /** Why the call would revert, in words. A revert is not a refusal, and the sentence says so. */
427
+ function whyReverts(err, c) {
428
+ const funds =
429
+ err.name === "ERC20InsufficientBalance" || (err.name === "Error" && /exceeds balance|insufficient balance/i.test(err.text));
430
+ if (funds || (c.balance !== null && c.need !== null && c.balance < c.need && err.name !== "NotAgent")) {
431
+ return {
432
+ underfunded: true,
433
+ text:
434
+ `${c.policyAllows ? "The policy allows this, but the" : "The"} vault holds ${units(c.balance ?? 0n, c.decimals, c.symbol)} ` +
435
+ `and this needs ${c.needHuman}, so the transfer would revert. Send ${c.symbol} to the vault at ${c.holder} first.`,
436
+ };
437
+ }
438
+ const map = {
439
+ NotAgent: `${c.agent} is not an agent of this vault. Check the address your agent signs with against buoy_agents`,
440
+ TokenNotAllowed: "that token is not on this vault's allowlist",
441
+ RouterNotAllowed: "that router is not one the owner allowed",
442
+ SameToken: "it swaps a token for itself",
443
+ ZeroMinimumOut: "it has no minimum to receive",
444
+ NoSwapOutput: "the swap would return nothing",
445
+ SwapOutputTooLow: "the swap would return less than the minimum asked for",
446
+ NotInstalled: "this vault's policy has not been switched on yet",
447
+ BindingIsRevoked: "this vault's policy has been revoked, so it can no longer spend; its owner can still withdraw",
448
+ BindingNotYet: "this vault's policy is not in force yet",
449
+ BindingExpired: "this vault's policy has expired, so it can no longer spend; its owner can still withdraw",
450
+ AccountNotBound: "this vault is not bound to a budget",
451
+ InsufficientGasForPolicy: "the gas limit is too low for the policy to run",
452
+ };
453
+ const known = map[err.name];
454
+ return {
455
+ underfunded: false,
456
+ text: `The call would revert: ${known ?? (err.text ? err.text : `the contract gave an error this version does not name (${err.selector ?? "no data"})`)}.`,
457
+ };
458
+ }
459
+
460
+ /**
461
+ * Ask the contract what it WOULD answer to this exact call, and say it in a sentence.
462
+ *
463
+ * Two questions, because they are different contracts' answers:
464
+ * the adapter's `preview`, a view: does the policy and the budget allow it, and how many budget
465
+ * units does the contract count it as. It does not look at the sender or the balance.
466
+ * the call itself, by `eth_call` as the agent: everything -- that the sender is an agent, the
467
+ * verdict from that agent's own budget, and whether the money can actually move.
468
+ *
469
+ * THIS IS NOT A GATE. The plan still carries the call, and a refusal seen here is still worth
470
+ * sending: only a broadcast leaves a verdict on chain with a receipt anyone can replay. What this
471
+ * replaces is arithmetic done on this side, which could say "within budget" about a payment the
472
+ * contract was going to refuse, with nothing anywhere to contradict it.
473
+ */
474
+ async function askContract(r, q) {
475
+ let pv = null;
476
+ try {
477
+ pv = await q.preview();
478
+ } catch {
479
+ pv = null; // a vault that cannot judge yet reverts here; the call below says why
480
+ }
481
+ let sim = null;
482
+ let unasked = null;
483
+ if (!q.agent) unasked = "no agent address is known for this vault";
484
+ else if (!r.simulate) unasked = "this client cannot simulate a call";
485
+ else {
486
+ try {
487
+ sim = await r.simulate({ from: q.agent, to: q.adapter, data: q.data, gas: q.gasLimit });
488
+ if (!sim) unasked = "the node gave no answer";
489
+ } catch (e) {
490
+ unasked = `the node could not be asked (${e.code ?? e.message})`;
491
+ }
492
+ }
493
+
494
+ const wantUnits = pv ? pv.amountUnits.toString() : null;
495
+ const base = { sender: q.agent ?? null, budgetUnits: wantUnits };
496
+ const c = { ...q.context, agent: q.agent, policyAllows: pv ? pv.allow : null };
497
+ const receipt = "Sending it anyway records that refusal on chain, with a receipt buoy_verify can replay.";
498
+ const refusal = (reason, how) => ({
499
+ ...base,
500
+ how,
501
+ outcome: "refused",
502
+ reason,
503
+ reasonName: reasonName(reason),
504
+ say: `Asked the contract just now: it would REFUSE this — ${whyRefused(reason, { left: q.context.left, wantUnits, symbol: q.context.budgetSymbol })}. Nothing has been sent. ${receipt}`,
505
+ });
506
+ const uses = wantUnits !== null ? ` It uses ${wantUnits} of the ${q.context.left} ${q.context.budgetSymbol} of budget left today.` : "";
507
+
508
+ if (sim && !sim.reverted) {
509
+ const s = String(sim.result ?? "").replace(/^0x/, "");
510
+ if (s.length < 128) {
511
+ return { ...base, how: "call", outcome: "unavailable", say: "The contract answered with nothing readable, so nothing here says whether it would allow this." };
512
+ }
513
+ if (BigInt("0x" + s.slice(0, 64)) !== 0n) {
514
+ return { ...base, how: "call", outcome: "allowed", say: `Asked the contract just now, as the agent ${short(q.agent)}: it allows this.${uses}` };
515
+ }
516
+ return refusal(Number(BigInt("0x" + s.slice(64, 128))), "call");
517
+ }
518
+ if (sim && sim.reverted) {
519
+ const err = decodeRevert(sim);
520
+ const why = whyReverts(err, c);
521
+ return {
522
+ ...base,
523
+ how: "call",
524
+ outcome: "reverts",
525
+ error: err.name,
526
+ errorText: err.text || null,
527
+ underfunded: why.underfunded,
528
+ policyAllows: c.policyAllows,
529
+ ...(pv && !pv.allow ? { reason: pv.reason, reasonName: reasonName(pv.reason) } : {}),
530
+ say: `Asked the contract just now. ${why.text} Nothing has been sent. A revert is not a refusal: it leaves no verdict and no receipt.`,
531
+ };
532
+ }
533
+ if (pv) {
534
+ // The policy alone. True as far as it goes, and it says how far that is.
535
+ if (!pv.allow) return refusal(pv.reason, "preview");
536
+ return {
537
+ ...base,
538
+ how: "preview",
539
+ outcome: "allowed",
540
+ say:
541
+ `Asked the contract's policy just now: it allows this.${uses} That was the policy alone — ${unasked} — ` +
542
+ `so who sends it and what the vault holds were not checked.`,
543
+ };
544
+ }
545
+ return {
546
+ ...base,
547
+ how: null,
548
+ outcome: "unavailable",
549
+ say: `The contract could not be asked just now (${unasked}), so nothing here says whether it would allow this. Send it and check the result with buoy_verify.`,
550
+ };
551
+ }
552
+
295
553
  // ------------------------------------------------------------------ payment
296
554
 
297
555
  /**
298
- * Build the unsigned payment and say what to expect. Nothing is withheld: see the header.
556
+ * Build the unsigned payment and say what the contract would answer. Nothing is withheld: see the
557
+ * header, and `askContract`.
558
+ *
559
+ * @param amount as a person writes it, in the token's own units: "150", "0.10"
560
+ * @param amountBaseUnits the same thing as an exact whole number of base units. One or the other.
561
+ * @param agent who will send it. Defaults to the vault's recorded agent.
299
562
  */
300
- export async function planPayment(r, { to, amount, token, from } = {}) {
563
+ export async function planPayment(r, { to, amount, amountBaseUnits, token, from, agent } = {}) {
301
564
  const m = r.manifest;
302
565
  const t = token ?? m.addresses.usdt;
303
566
  if (!t) throw new ViewError("no-token", "pass a token address; the manifest records none");
304
567
  if (!/^0x[0-9a-fA-F]{40}$/.test(String(to))) throw new ViewError("bad-recipient", String(to));
305
- if (amount === undefined || amount === null || String(amount) === "") {
306
- throw new ViewError("no-amount", "pass the amount in the token's base units");
307
- }
308
568
 
309
569
  const acct = await resolveAccount(r, from);
310
570
  if (!acct || !acct.address) {
@@ -316,40 +576,52 @@ export async function planPayment(r, { to, amount, token, from } = {}) {
316
576
  );
317
577
  }
318
578
 
319
- const [symbol, decimals, left, gasLimit] = await Promise.all([
320
- r.symbol(t),
321
- r.decimals(t),
579
+ const [symbol, decimals] = await Promise.all([r.symbol(t), r.decimals(t)]);
580
+ const base = amountOf(amount, amountBaseUnits, decimals, symbol, "the amount");
581
+ if (base === null) {
582
+ throw new ViewError("no-amount", `pass the amount in ${symbol}, as you would write it: "150", or "0.10" for ten cents`);
583
+ }
584
+
585
+ const [left, gasLimit, holder] = await Promise.all([
322
586
  r.remainingOnPath(acct.address),
323
587
  spendGasLimit(r),
588
+ r.holder(acct.address),
324
589
  ]);
325
- const call = payCall(acct.address, t, to, String(amount), undefined);
326
-
327
- /* Advice, never a gate. `remainingOnPath` is in table units and `amount` is in base units, so
328
- they are compared only after scaling -- and if the manifest has no unit for this token the
329
- comparison is SKIPPED rather than guessed, because a wrong scale here would predict a
330
- refusal that never happens and talk the agent out of a valid payment. */
331
- const unit = unitForToken(m, t);
332
- let expectation = "The contract decides. Submit it either way.";
333
- if (unit) {
334
- /* Rounded UP, because the contract does: PolicyWord counts `(amount - 1) / unit + 1`, so a
335
- 0.10 payment costs one whole unit of budget, not zero. Flooring here told people a payment
336
- "asks for about 0" when the chain was about to debit 1 -- seen on mainnet, 2026-11-21. */
337
- const wantUnits = unitsCeil(amount, unit);
338
- expectation =
339
- wantUnits > left
340
- ? `This looks over today's budget -- ${left} ${symbol} left, this asks for about ${wantUnits}. ` +
341
- `Submitting anyway, because only the contract may refuse, and its refusal comes with a receipt.`
342
- : `This should be within today's budget: ${left} ${symbol} left, this asks for about ${wantUnits}.`;
343
- }
590
+ const balance = await r.balanceOf(t, holder);
591
+ const call = payCall(acct.address, t, to, base.toString(), undefined);
592
+ const amountHuman = units(base, decimals, symbol);
593
+ const sender = agent ?? m.addresses.agent ?? null;
594
+
595
+ const simulation = await askContract(r, {
596
+ adapter: acct.address,
597
+ data: (call.submit ?? call).data,
598
+ gasLimit,
599
+ agent: sender,
600
+ preview: () => r.preview(acct.address, t, to, base),
601
+ context: { left: left.toString(), budgetSymbol: symbol, symbol, decimals, balance, need: base, needHuman: amountHuman, holder },
602
+ });
603
+
604
+ /* The old habit, caught where it can be: a whole number with no decimal point that is a
605
+ million or more is much likelier base units from before this argument changed meaning. It is
606
+ still sent as written -- the figure above is in the sentence, and the contract rules on it. */
607
+ const legacy =
608
+ amount !== undefined && amount !== null && /^\s*[0-9]+\s*$/.test(String(amount)) && BigInt(String(amount).trim()) >= 10n ** BigInt(decimals)
609
+ ? `"${String(amount).trim()}" was read as ${amountHuman}. If you meant base units (${units(BigInt(String(amount).trim()), decimals, symbol)}), pass amountBaseUnits instead.`
610
+ : null;
344
611
 
345
612
  return {
346
613
  from: { ...acct, name: acct.nodeId ? await r.nodeName(acct.nodeId) : null },
347
614
  to,
348
615
  token: { address: t, symbol, decimals },
349
- amountBaseUnits: String(amount),
350
- amountHuman: units(amount, decimals, symbol),
616
+ amount: units(base, decimals),
617
+ amountBaseUnits: base.toString(),
618
+ amountHuman,
351
619
  remainingTodayUnits: left.toString(),
352
- expectation,
620
+ vaultHolds: units(balance, decimals, symbol),
621
+ simulation,
622
+ /* What to expect, which is now the contract's own answer rather than arithmetic done here. */
623
+ expectation: simulation.say,
624
+ ...(legacy ? { note: legacy } : {}),
353
625
  /* `gasLimit` travels WITH the call, because it is a property of this wallet's policies and
354
626
  not a constant: see spendGasLimit. */
355
627
  submit: { ...(call.submit ?? call), gasLimit },
@@ -357,47 +629,74 @@ export async function planPayment(r, { to, amount, token, from } = {}) {
357
629
  "Send this with the AGENT key via `onchainos wallet contract-call --gas-limit " + gasLimit + "` " +
358
630
  "(keys stay in OKX Agentic Wallet's TEE; Buoy holds none). Do not lower the gas limit. " +
359
631
  "Then pass the transaction hash to buoy_verify.",
360
- say:
361
- `Paying ${units(amount, decimals, symbol)} to ${to} from ${acct.via}. ${expectation}`,
632
+ say: `${whoseVault(m, null)}Paying ${amountHuman} to ${to} from ${acct.via}. ${simulation.say}`,
362
633
  };
363
634
  }
364
635
 
365
- /** The signed tables record 1 unit = N base units per asset. Absent means "do not guess". */
366
- export function unitForToken(m, token) {
367
- try {
368
- const tables = typeof m.canonicalTables === "string" ? JSON.parse(m.canonicalTables) : m.canonicalTables;
369
- const a = tables?.assets?.[String(token).toLowerCase()];
370
- return a?.unit ?? null;
371
- } catch {
372
- return null;
373
- }
374
- }
375
-
376
636
  // ------------------------------------------------------------------ swap
377
637
 
638
+ /**
639
+ * Build the unsigned swap and say what the contract would answer.
640
+ *
641
+ * `amountIn` and `minAmountOut` are whole tokens, each in its OWN token's decimals -- USDT0 has 6
642
+ * and WOKB has 18, so one scale for both was never right. `amountInBaseUnits` and
643
+ * `minAmountOutBaseUnits` are the exact forms.
644
+ */
378
645
  export async function planSwap(r, args = {}) {
379
- const { amountIn, minAmountOut, from } = args;
646
+ const { from, agent } = args;
647
+ const m = r.manifest;
380
648
  /* The pair a setup allows, so "swap 10 USDT0" works without the agent hunting for a router
381
649
  address. Anything passed explicitly still wins -- including a token the vault never allowed,
382
650
  which is how the allowlist's refusal gets demonstrated. */
383
651
  const router = args.router ?? SWAP_ROUTER02;
384
- const tokenIn = args.tokenIn ?? r.manifest.addresses.usdt;
652
+ const tokenIn = args.tokenIn ?? m.addresses.usdt;
385
653
  const tokenOut = args.tokenOut ?? WOKB;
386
654
  const fee = args.fee ?? 500;
387
655
  const acct = await resolveAccount(r, from);
388
656
  if (!acct || !acct.address) throw new ViewError("unknown-account", String(from));
389
- if (minAmountOut === undefined || BigInt(minAmountOut ?? 0) === 0n) {
390
- throw new ViewError("no-floor", "minAmountOut must not be 0: a swap with no floor is a donation");
657
+
658
+ const [symIn, decIn, symOut, decOut] = await Promise.all([
659
+ r.symbol(tokenIn), r.decimals(tokenIn), r.symbol(tokenOut), r.decimals(tokenOut),
660
+ ]);
661
+ const amountIn = amountOf(args.amountIn, args.amountInBaseUnits, decIn, symIn, "the amount to swap");
662
+ if (amountIn === null) throw new ViewError("no-amount", `pass amountIn in ${symIn}, as you would write it: "10", or "0.10"`);
663
+ const minOut = amountOf(args.minAmountOut, args.minAmountOutBaseUnits, decOut, symOut, "the minimum to receive");
664
+ if (minOut === null || minOut === 0n) {
665
+ throw new ViewError("no-floor", `minAmountOut must be more than 0 ${symOut}: a swap with no floor is a donation`);
391
666
  }
392
- const call = swapCall(acct.address, { router, tokenIn, tokenOut, fee, amountIn, minAmountOut });
393
- const gasLimit = await spendGasLimit(r);
667
+
668
+ const call = swapCall(acct.address, { router, tokenIn, tokenOut, fee, amountIn: amountIn.toString(), minAmountOut: minOut.toString() });
669
+ const [left, gasLimit, holder] = await Promise.all([r.remainingOnPath(acct.address), spendGasLimit(r), r.holder(acct.address)]);
670
+ const balance = await r.balanceOf(tokenIn, holder);
671
+ const inHuman = units(amountIn, decIn, symIn);
672
+ const outHuman = units(minOut, decOut, symOut);
673
+ const sender = agent ?? m.addresses.agent ?? null;
674
+
675
+ const simulation = await askContract(r, {
676
+ adapter: acct.address,
677
+ data: (call.submit ?? call).data,
678
+ gasLimit,
679
+ agent: sender,
680
+ preview: () => r.previewSwap(acct.address, router, tokenIn, amountIn),
681
+ context: { left: left.toString(), budgetSymbol: symIn, symbol: symIn, decimals: decIn, balance, need: amountIn, needHuman: inHuman, holder },
682
+ });
683
+
394
684
  return {
395
685
  from: acct,
686
+ tokenIn: { address: tokenIn, symbol: symIn, decimals: decIn },
687
+ tokenOut: { address: tokenOut, symbol: symOut, decimals: decOut },
688
+ amountInBaseUnits: amountIn.toString(),
689
+ amountInHuman: inHuman,
690
+ minAmountOutBaseUnits: minOut.toString(),
691
+ minAmountOutHuman: outHuman,
692
+ remainingTodayUnits: left.toString(),
693
+ simulation,
694
+ expectation: simulation.say,
396
695
  submit: { ...(call.submit ?? call), gasLimit },
397
696
  say:
398
- `Swapping ${amountIn} of ${tokenIn} for at least ${minAmountOut} of ${tokenOut} from ${acct.via}. ` +
399
- `A swap presents kind 0, so it is refused unless this node's circuit admits kind 0 -- and that ` +
400
- `refusal is recorded on chain. The output is forced back to the vault, so it cannot leave custody.`,
697
+ whoseVault(m, null) +
698
+ `Swapping ${inHuman} for at least ${outHuman} from ${acct.via}; the proceeds are forced back to the vault, so they cannot leave custody. ` +
699
+ simulation.say,
401
700
  howToSend: "Send with the AGENT key via `onchainos wallet contract-call --gas-limit " + gasLimit + "`. Do not lower the gas limit.",
402
701
  };
403
702
  }
@@ -444,7 +743,9 @@ export async function planFetch(r, { url, from, agentWallet, maxAmountBaseUnits,
444
743
  const wallet = agentWallet ?? m.addresses.agent;
445
744
  if (!wallet) throw new ViewError("no-agent-wallet", "pass agentWallet: the manifest records none");
446
745
 
447
- const draw = await planPayment(r, { to: wallet, amount: offer.amountBaseUnits, token, from });
746
+ /* The seller prices in base units, and the agent that will sign the payment header is the one
747
+ that draws: both are passed as what they are, so nothing is re-read as a different scale. */
748
+ const draw = await planPayment(r, { to: wallet, amountBaseUnits: offer.amountBaseUnits, token, from, agent: wallet });
448
749
  const symbol = draw.token.symbol;
449
750
 
450
751
  return {
@@ -0,0 +1,45 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Where is `onchainos`, and is it there at all?
3
+ //
4
+ // OKX's installer puts the binary in `~/.local/bin` (measured 2026-11-22 on Windows:
5
+ // `%USERPROFILE%\.local\bin\onchainos.exe`, version 4.6.11). That folder is on PATH in a new
6
+ // terminal and often NOT in the one the installer was just run from, nor in the environment an
7
+ // editor hands an agent. "onchainos is not installed" was therefore being said about machines that
8
+ // had it. So this looks in both places and says which it found.
9
+ //
10
+ // It runs nothing but `--version`, holds no key, and is imported by the installer and by the two
11
+ // signing lanes -- never by ts/mcp/.
12
+
13
+ import { spawnSync } from "node:child_process";
14
+ import { existsSync } from "node:fs";
15
+ import { homedir } from "node:os";
16
+ import { join } from "node:path";
17
+
18
+ /** The one install command, from OKX's own README (github.com/okx/onchainos-skills, 2026-11-20). */
19
+ export const ONCHAINOS_INSTALL = "npx -y @okxweb3/onchainos-installer install";
20
+
21
+ /** Where OKX's installer puts the binary. */
22
+ export function onchainosHome({ env = process.env, platform = process.platform } = {}) {
23
+ const home = env.HOME || env.USERPROFILE || homedir();
24
+ return join(home, ".local", "bin", platform === "win32" ? "onchainos.exe" : "onchainos");
25
+ }
26
+
27
+ /**
28
+ * @returns {{ bin: string|null, onPath: boolean, version: string|null }}
29
+ * `bin` is what to spawn: the bare name when PATH has it, the full path when only the
30
+ * installer's folder does, and null when it is in neither.
31
+ */
32
+ export function locateOnchainos({ env = process.env, platform = process.platform, spawn = spawnSync, exists = existsSync } = {}) {
33
+ const probe = (bin) => {
34
+ const r = spawn(bin, ["--version"], { encoding: "utf8", shell: false, env });
35
+ return r.error || r.status !== 0 ? null : (r.stdout ?? "").trim() || "onchainos";
36
+ };
37
+ const onPath = probe("onchainos");
38
+ if (onPath) return { bin: "onchainos", onPath: true, version: onPath };
39
+ const there = onchainosHome({ env, platform });
40
+ if (exists(there)) {
41
+ const v = probe(there);
42
+ if (v) return { bin: there, onPath: false, version: v };
43
+ }
44
+ return { bin: null, onPath: false, version: null };
45
+ }
package/ts/okx/signer.mjs CHANGED
@@ -16,6 +16,7 @@
16
16
  // read 2026-11-20 -- not from a docs page or a third-party skill summary.
17
17
 
18
18
  import { spawnSync } from "node:child_process";
19
+ import { locateOnchainos, ONCHAINOS_INSTALL } from "./locate.mjs";
19
20
 
20
21
  /// `FloatGatekeeper.policyGasFloor` (src/FloatGatekeeper.sol:147). The gatekeeper requires this
21
22
  /// much gas still available when it runs the policy circuit.
@@ -126,13 +127,16 @@ export function buildContractCallArgs({
126
127
  }
127
128
 
128
129
  /// Default runner. Injectable so the translation above can be tested without the CLI installed.
129
- export function cliRunner(bin = "onchainos") {
130
+ export function cliRunner(bin) {
131
+ /* PATH first, then the folder OKX's installer uses: a machine that has just installed it
132
+ usually has the binary and not yet the PATH entry, and that is not "not installed". */
133
+ const exe = bin ?? locateOnchainos().bin ?? "onchainos";
130
134
  return (args) => {
131
- const r = spawnSync(bin, args, { encoding: "utf8", shell: false });
135
+ const r = spawnSync(exe, args, { encoding: "utf8", shell: false });
132
136
  if (r.error && r.error.code === "ENOENT") {
133
137
  throw new OkxSignerError(
134
138
  "cli-not-installed",
135
- `${bin} is not on PATH. Install with: npx -y @okxweb3/onchainos-installer install`
139
+ `onchainos was not found on PATH or in ~/.local/bin. Install it with: ${ONCHAINOS_INSTALL}`
136
140
  );
137
141
  }
138
142
  return { code: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };