@needmoretruth/nmts-cli 0.47.0 → 0.49.0

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/CHANGELOG.md CHANGED
@@ -3,6 +3,31 @@
3
3
  Each version's entry is what changed for the person or the program using `nmts`. The product's own
4
4
  update history, which covers the site and the server too, is at https://nmts.me/updates.
5
5
 
6
+ ## 0.49.0 — 2026-09-28
7
+
8
+ - `nmts wallet swap` now trades SUI, WAL and USDC in all six directions:
9
+ `nmts wallet swap <SUI|WAL|USDC> <amount|max> --to <SUI|WAL|USDC> --venue deepbook|bluefin`.
10
+ USDC means Circle's native USDC on Sui, matched by its full coin type. A coin that only shares the
11
+ name is refused.
12
+ - On DeepBook, WAL↔SUI is quoted both directly and through USDC in one transaction. The route that
13
+ pays more is the one that gets signed.
14
+ - An agent grant with a spending cap refuses swaps that spend USDC, because the cap counts only SUI
15
+ and WAL.
16
+
17
+ ## 0.48.1 — 2026-09-28
18
+
19
+ - 0.48.0 was tagged but never reached npm: one test named the public code file by hand and failed
20
+ whenever a random code held a character a file name drops. The test now builds the name the way
21
+ the command does. 0.48.1 carries 0.48.0's changes below.
22
+
23
+ ## 0.48.0 — 2026-09-28
24
+
25
+ - **Every public link in one list.** `nmts links` prints every link of yours that still opens a
26
+ file, newest first, with the file's path, download count and end date (`--json` for programs).
27
+ `nmts links revoke <id>` cuts one and `nmts links revoke-all` cuts them all in one request;
28
+ copies already downloaded stay with whoever has them. The SDK has `allLinks()` and
29
+ `revokeAllLinks()`.
30
+
6
31
  ## 0.47.0 — 2026-09-27
7
32
 
8
33
  - **Public links.** `nmts link make <path>` makes a link to one file that anyone can open without
package/README.ko.md CHANGED
@@ -50,7 +50,7 @@ nmts --help
50
50
 
51
51
  ```sh
52
52
  npm install -g github:needmoretruth/nmts-cli # 기본 브랜치
53
- npm install -g github:needmoretruth/nmts-cli#v0.47.0 # 버전을 고정할 때
53
+ npm install -g github:needmoretruth/nmts-cli#v0.49.0 # 버전을 고정할 때
54
54
  npm install -g https://github.com/needmoretruth/nmts-cli/releases/latest/download/nmts.tgz
55
55
  ```
56
56
 
package/README.md CHANGED
@@ -51,7 +51,7 @@ default branch, from a pinned version, or from the tarball attached to the
51
51
 
52
52
  ```sh
53
53
  npm install -g github:needmoretruth/nmts-cli # the default branch
54
- npm install -g github:needmoretruth/nmts-cli#v0.47.0 # a pinned version
54
+ npm install -g github:needmoretruth/nmts-cli#v0.49.0 # a pinned version
55
55
  npm install -g https://github.com/needmoretruth/nmts-cli/releases/latest/download/nmts.tgz
56
56
  ```
57
57
 
@@ -11,7 +11,7 @@ export declare const CRYPTO_SPEC_URL = "https://github.com/needmoretruth/nmts-re
11
11
  * is the field's own contract — what the writer says about itself — and a person holding two
12
12
  * copies of one account's artefacts can then tell which program made each.
13
13
  */
14
- export declare const WRITTEN_BY = "nmts-cli 0.47.0";
14
+ export declare const WRITTEN_BY = "nmts-cli 0.49.0";
15
15
  /** Which of the three artefacts a wrapper is. A reader holding several can sort them. */
16
16
  export type ArtifactKind = "recovery-list" | "file-list" | "recovery-kit";
17
17
  /**
@@ -0,0 +1,7 @@
1
+ export interface LinksOptions {
2
+ server?: string | undefined;
3
+ network?: string | undefined;
4
+ json?: boolean;
5
+ write?: (line: string) => void;
6
+ }
7
+ export declare function links(sub: string | undefined, operand: string | undefined, options?: LinksOptions): Promise<number>;
@@ -0,0 +1,71 @@
1
+ // `nmts links` · `nmts links revoke <id>` · `nmts links revoke-all` — every live public link this
2
+ // account holds, across all its files, and the two ways to cut them (NCF-3 §5.8), so a person who
3
+ // handed out many links can take them all back without going file by file.
4
+ //
5
+ // ⛔ THE SERVER NAMES FILES BY ID. The path beside each link comes from this account's own sealed
6
+ // file list, opened here; a link whose file is not in that list prints `(not in the file list)`.
7
+ //
8
+ // ⛔ `revoke-all` IS ONE REQUEST, ALL OR NONE. It sits beside `link revoke` in the gate's `low` tier:
9
+ // it only takes something back, and no copy already downloaded is reached.
10
+ import { buildIndex, fullPathOf } from "../drive-paths.js";
11
+ import { NmtsError } from "../errors.js";
12
+ import { listLiveLinks, revokeAllLinks, revokeLink } from "../links.js";
13
+ import { readFileList } from "../manifest.js";
14
+ import { BINARY_NAME } from "../product.js";
15
+ import { openSession } from "../session.js";
16
+ const USAGE = `\`${BINARY_NAME} links\` · \`${BINARY_NAME} links revoke <id>\` · \`${BINARY_NAME} links revoke-all\``;
17
+ export async function links(sub, operand, options = {}) {
18
+ const say = options.write ?? ((line) => process.stdout.write(`${line}\n`));
19
+ if (sub !== undefined && sub !== "revoke" && sub !== "revoke-all") {
20
+ throw new NmtsError("Say nothing to list, or `revoke <id>`, or `revoke-all`.", { exitCode: 2, nextStep: USAGE });
21
+ }
22
+ if (sub === "revoke" && (operand === undefined || operand === "")) {
23
+ throw new NmtsError("Say which link id.", { exitCode: 2, nextStep: USAGE });
24
+ }
25
+ const session = await openSession({ server: options.server, network: options.network });
26
+ const account = { server: session.server, bearer: session.apiKey, code: session.code };
27
+ if (sub === "revoke" && operand !== undefined) {
28
+ await revokeLink(account, operand);
29
+ say(options.json === true ? JSON.stringify({ id: operand, cut: true }) : `${operand} cut`);
30
+ return 0;
31
+ }
32
+ if (sub === "revoke-all") {
33
+ const cut = await revokeAllLinks(account);
34
+ say(options.json === true ? JSON.stringify({ cut }) : `${cut} ${cut === 1 ? "link" : "links"} cut`);
35
+ return 0;
36
+ }
37
+ const rows = await listLiveLinks(account);
38
+ const paths = await pathsOf(session, rows);
39
+ if (options.json === true) {
40
+ say(JSON.stringify({ links: rows.map((row) => ({ ...row, path: paths.get(row.itemId) ?? null })) }));
41
+ return 0;
42
+ }
43
+ if (rows.length === 0) {
44
+ say("No live public links.");
45
+ return 0;
46
+ }
47
+ for (const row of rows) {
48
+ const path = paths.get(row.itemId) ?? "(not in the file list)";
49
+ const ends = row.expiresAt === null ? "" : ` expires ${row.expiresAt}`;
50
+ say(`${row.id} ${path} made ${row.createdAt} downloads ${row.downloads}${ends}`);
51
+ if (row.link !== null)
52
+ say(` ${row.link}`);
53
+ }
54
+ return 0;
55
+ }
56
+ /** Each linked file's path, from the account's own sealed list. Nothing to look up, nothing read. */
57
+ async function pathsOf(session, rows) {
58
+ const found = new Map();
59
+ if (rows.length === 0)
60
+ return found;
61
+ const list = await readFileList(session.server, session.apiKey, session.code, session.accountId);
62
+ if (list.manifest === null)
63
+ return found;
64
+ const index = buildIndex(list.manifest.entries);
65
+ for (const row of rows) {
66
+ const entry = index.byId.get(row.itemId);
67
+ if (entry !== undefined)
68
+ found.set(row.itemId, fullPathOf(index, entry));
69
+ }
70
+ return found;
71
+ }
@@ -1,4 +1,4 @@
1
- // The share verbs (share · shares · unshare · receive · link), dispatched here rather than in `main.ts`.
1
+ // The share verbs (share · shares · unshare · receive · link · links), dispatched here rather than in `main.ts`.
2
2
  //
3
3
  // ⛔ WHY A SECOND SWITCH. `main.ts` is measured (`check:size`) and had no room for `nmts support`;
4
4
  // this block shares a file and an option shape, so it moved as one piece with its comments.
@@ -53,6 +53,10 @@ export async function runShare(command, args) {
53
53
  json: args.json,
54
54
  });
55
55
  }
56
+ case "links": {
57
+ const { links } = await import("./links.js");
58
+ return await links(args.operands[0], args.operands[1], { server: args.server, network: args.network, json: args.json });
59
+ }
56
60
  default:
57
61
  throw new Error(`not a share verb: ${command}`);
58
62
  }
@@ -1,11 +1,8 @@
1
1
  import { type Network } from "../network.ts";
2
2
  import { type SwapReads } from "../wallet-swap-chain.ts";
3
+ import { type MarketPrices } from "../wallet-swap-words.ts";
3
4
  import type { SignSwap } from "../wallet-sign.ts";
4
- /** What the site's price route says, when it says anything. Null = no reference price just now. */
5
- export interface MarketPrices {
6
- suiUsd: number | null;
7
- walUsd: number | null;
8
- }
5
+ export { asMarketPrices, type MarketPrices } from "../wallet-swap-words.ts";
9
6
  export interface WalletSwapOptions {
10
7
  server?: string | undefined;
11
8
  network?: string | undefined;
@@ -14,7 +11,7 @@ export interface WalletSwapOptions {
14
11
  yes?: boolean;
15
12
  dryRun?: boolean;
16
13
  feeCap?: string | undefined;
17
- /** `--to`: the coin to receive. Only ever the other coin; said so a typo cannot flip the trade. */
14
+ /** `--to`: the coin to receive — SUI, WAL or USDC. Without it SUI→WAL and WAL→SUI; USDC must say. */
18
15
  to?: string | undefined;
19
16
  /** `--venue`: deepbook or bluefin. Without it, both are quoted and the run stops. */
20
17
  venue?: string | undefined;
@@ -31,5 +28,4 @@ export interface WalletSwapOptions {
31
28
  readPrices?: (server: string) => Promise<MarketPrices | null>;
32
29
  sign?: SignSwap;
33
30
  }
34
- export declare function asMarketPrices(value: unknown): MarketPrices | null;
35
31
  export declare function walletSwap(operands: readonly string[], options?: WalletSwapOptions): Promise<number>;
@@ -1,15 +1,21 @@
1
- // `nmts wallet swap <SUI|WAL> <amount|max>` — turn one coin into the other, from the wallet this
2
- // NMTS key derives, on the venue the person names. ⛔ SIGNS AND SPENDS.
1
+ // `nmts wallet swap <SUI|WAL|USDC> <amount|max> [--to <coin>]` — turn one coin into another, from the
2
+ // wallet this NMTS key derives, on the venue the person names. ⛔ SIGNS AND SPENDS.
3
3
  //
4
- // ⛔ THE ORDER IS THE SAFETY. ① both balances are READ, and an unread one stops the run ② the
5
- // amount and the slippage are judged by the browser's own rules (`shared/lib/wallet/swap-rules.ts`,
6
- // copied byte-for-byte) ③ the venue's quote is read from the chain — on mainnet BOTH venues when
7
- // none was named, printed side by side, and the run stops there: neither is a default and nobody
8
- // recommends one ④ the exact swap is dry-run for its fee ⑤ the quote is compared with the site's
9
- // reference price when one can be read, and said to be uncompared when none can ⑥ the review is
10
- // printed ⑦ anything outside the ordinary bands — slippage, fee cap, market distance — is refused;
11
- // only a person, in mode off, may say `--accept-extremes` ⑧ without `--yes` that is the end ⑨ the
12
- // wallet agreement is held against the amount and the fee, scope `all` ⑩ only then the signature.
4
+ // ⛔ THREE COINS, SIX DIRECTIONS. SUI, WAL and Circle's native USDC, any into either of the other two.
5
+ // Without --to, SUI goes to WAL and WAL to SUI (the two-coin behaviour, kept); USDC must say --to.
6
+ // A coin may also be named by its full coin type, and then only the EXACT type counts — a coin
7
+ // whose symbol is "USDC" from another package is refused, never swapped.
8
+ //
9
+ // ⛔ THE ORDER IS THE SAFETY. ① the balances the trade touches are READ, and an unread one stops the
10
+ // run ② the amount and the slippage are judged by the browser's own rules (`shared/lib/wallet/
11
+ // swap-rules.ts`, copied byte-for-byte) ③ the venue's quote is read from the chain — on mainnet
12
+ // BOTH venues when none was named, printed side by side, and the run stops there: neither is a
13
+ // default and nobody recommends one ④ the exact swap is dry-run for its fee ⑤ the quote is compared
14
+ // with the site's reference price when one can be read, and said to be uncompared when none can
15
+ // ⑥ the review is printed ⑦ anything outside the ordinary bands — slippage, fee cap, market
16
+ // distance — is refused; only a person, in mode off, may say `--accept-extremes` ⑧ without `--yes`
17
+ // that is the end ⑨ the wallet agreement is held against the amount and the fee, scope `all`
18
+ // ⑩ only then the signature.
13
19
  //
14
20
  // ⛔ NOT ON THE MCP SURFACE. A model can ask a person to run this; it cannot run it through a tool call.
15
21
  import { request } from "../api.js";
@@ -17,61 +23,25 @@ import { currentMode } from "../autonomy.js";
17
23
  import { requireAccountCode } from "../code-access.js";
18
24
  import { readCredentialsFile } from "../credentials.js";
19
25
  import { NmtsError } from "../errors.js";
20
- import { isRecord } from "../guards.js";
21
26
  import { resolveNetwork } from "../network.js";
22
27
  import { BINARY_NAME } from "../product.js";
23
28
  import { resolveServer } from "../server.js";
24
29
  import { explorerTxUrl } from "../shared/lib/wallet/activity.js";
25
30
  import { clampGasBudgetMist, parseTokenAmountToBaseUnits, SUI_GAS_RESERVE_MIST } from "../shared/lib/wallet/send-rules.js";
26
- import { clampSlippageBps, impliedRate, marketRate, maxSwappableSuiMist, minOutFromQuote, priceDeviationBps, SLIPPAGE_BPS_DEFAULT, SLIPPAGE_BPS_MAX, SLIPPAGE_BPS_MIN, swapExtremes, } from "../shared/lib/wallet/swap-rules.js";
31
+ import { clampSlippageBps, COIN_DECIMALS, directionOf, impliedRate, marketRate, maxSwappableSuiMist, minOutFromQuote, priceDeviationBps, SLIPPAGE_BPS_DEFAULT, SLIPPAGE_BPS_MAX, SLIPPAGE_BPS_MIN, swapExtremes, } from "../shared/lib/wallet/swap-rules.js";
27
32
  import { coinAmount, walletAddress } from "../wallet.js";
28
33
  import { payingWalletIndex } from "../wallet-pay-index.js";
29
34
  import { recordWalletSpend, requireWalletGrant } from "../wallet-grant.js";
30
35
  import { railsFor } from "../wallet-swap-chain.js";
31
- const EXTREME_WORDS = {
32
- lowSlippage: "the slippage is below 10 bps: the smallest price movement fails the swap, and the chain fee is spent for nothing",
33
- highSlippage: "the slippage is above 200 bps: a thin order book may keep that much of what goes in",
34
- lowFee: "the fee cap is under 1.2 times the measured fee: the swap may fail for want of gas, and that gas is gone",
35
- highFee: "the fee cap is over ten times the measured fee and over 0.05 SUI",
36
- deviation: "the quote is more than 3% from the site's reference price: the book may be thin or moved",
37
- };
38
- function coinOf(raw, what) {
39
- const up = (raw ?? "").toUpperCase();
40
- if (up === "SUI" || up === "WAL")
41
- return up;
42
- throw new NmtsError(`Say which coin ${what}: SUI or WAL.`, {
43
- exitCode: 2,
44
- nextStep: `\`${BINARY_NAME} wallet swap <SUI|WAL> <amount|max> --venue deepbook|bluefin\``,
45
- });
46
- }
47
- function pct(bps) {
48
- return `${(bps / 100).toFixed(2).replace(/0+$/, "").replace(/\.$/, "")}%`;
49
- }
50
- export function asMarketPrices(value) {
51
- if (!isRecord(value) || value["unavailable"] === true)
52
- return null;
53
- const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : null);
54
- return { suiUsd: num(value["suiUsd"]), walUsd: num(value["walUsd"]) };
55
- }
56
- function venueName(venue) {
57
- return venue === "deepbook" ? "DeepBook" : venue === "bluefin" ? "Bluefin" : "the official Walrus testnet exchange";
58
- }
59
- function quoteLine(q, outCoin, inCoin) {
60
- const fee = q.feeRateBps === null ? "venue fee could not be measured" : `venue fee about ${pct(q.feeRateBps)}`;
61
- const left = q.leftoverInUnits > 0n ? ` (${coinAmount(q.leftoverInUnits)} ${inCoin} would come back unused)` : "";
62
- return `${q.venue.padEnd(9)} ${coinAmount(q.outUnits)} ${outCoin} — ${fee}${left}`;
63
- }
36
+ import { amountOf, asMarketPrices, coinWordOf, EXTREME_WORDS, pct, quoteLine, resolveCoin, USAGE, venueName, } from "../wallet-swap-words.js";
37
+ export { asMarketPrices } from "../wallet-swap-words.js";
64
38
  export async function walletSwap(operands, options = {}) {
65
39
  const say = options.write ?? ((line) => process.stdout.write(`${line}\n`));
66
40
  const [coinRaw, amountRaw] = operands;
67
- const coinIn = coinOf(coinRaw, "goes in");
68
- const coinOut = coinIn === "SUI" ? "WAL" : "SUI";
69
- if (options.to !== undefined && coinOf(options.to, "comes out") !== coinOut) {
70
- throw new NmtsError(`${coinIn} can only be swapped for ${coinOut}.`, { exitCode: 2, nextStep: `Drop --to, or say --to ${coinOut}.` });
71
- }
72
- const direction = coinIn === "SUI" ? "SUI_TO_WAL" : "WAL_TO_SUI";
41
+ const inWord = coinWordOf(coinRaw, "goes in");
42
+ const toWord = options.to === undefined ? null : coinWordOf(options.to, "comes out");
73
43
  if (amountRaw === undefined) {
74
- throw new NmtsError("Say how much.", { exitCode: 2, nextStep: `\`${BINARY_NAME} wallet swap ${coinIn} <amount|max>\` — "max" swaps everything that can be swapped.` });
44
+ throw new NmtsError("Say how much.", { exitCode: 2, nextStep: `${USAGE} — "max" swaps everything that can be swapped.` });
75
45
  }
76
46
  const resolved = await requireAccountCode();
77
47
  // ⛔ WHICH WALLET SWAPS, FIRST — the coins that are read, the quote that is priced, the address
@@ -81,34 +51,62 @@ export async function walletSwap(operands, options = {}) {
81
51
  const stored = resolved.source === "file" || resolved.source === "file-locked" ? readCredentialsFile() : null;
82
52
  const server = resolveServer(options.server ?? stored?.server);
83
53
  const network = resolveNetwork(server, options.network ?? stored?.network);
54
+ // The direction: the coin named, into --to; without --to, SUI↔WAL as before, and USDC must say.
55
+ const coinIn = resolveCoin(inWord, network);
56
+ let coinOut;
57
+ if (toWord !== null) {
58
+ coinOut = resolveCoin(toWord, network);
59
+ }
60
+ else if (coinIn === "USDC") {
61
+ throw new NmtsError("Say which coin USDC becomes: --to SUI or --to WAL.", { exitCode: 2, nextStep: USAGE });
62
+ }
63
+ else {
64
+ coinOut = coinIn === "SUI" ? "WAL" : "SUI";
65
+ }
66
+ const direction = directionOf(coinIn, coinOut);
67
+ if (direction === null) {
68
+ throw new NmtsError(`${coinIn} cannot be swapped for itself.`, { exitCode: 2, nextStep: `Say --to one of the other two coins.` });
69
+ }
84
70
  const rails = railsFor(network);
85
71
  const reads = await (options.readChain ?? (async (net) => (await import("../wallet-swap-chain.js")).swapReads(net)))(network);
86
- // ① The balances — read, and refused as unread rather than treated as zero.
72
+ // ① The balances — read, and refused as unread rather than treated as zero. USDC is read only when
73
+ // the trade touches it, so an unreadable USDC never stops a SUI↔WAL swap.
87
74
  const purse = await reads.readWallet(address);
88
- if (!purse.sui.read || !purse.wal.read) {
89
- const which = [!purse.sui.read ? `SUI: ${purse.sui.why}` : null, !purse.wal.read ? `WAL: ${purse.wal.why}` : null].filter((w) => w !== null);
75
+ const usdcRead = coinIn === "USDC" || coinOut === "USDC" ? await reads.readUsdc(address) : null;
76
+ if (!purse.sui.read || !purse.wal.read || (usdcRead !== null && !usdcRead.read)) {
77
+ const which = [
78
+ !purse.sui.read ? `SUI: ${purse.sui.why}` : null,
79
+ !purse.wal.read ? `WAL: ${purse.wal.why}` : null,
80
+ usdcRead !== null && !usdcRead.read ? `USDC: ${usdcRead.why}` : null,
81
+ ].filter((w) => w !== null);
90
82
  throw new NmtsError("A balance could not be read, so this tool cannot tell what can be swapped.", {
91
83
  exitCode: 1,
92
84
  nextStep: `Nothing was signed. That is not an empty wallet — ${which.join("; ")}.`,
93
85
  });
94
86
  }
95
- const sui = purse.sui.baseUnits;
96
- const wal = purse.wal.baseUnits;
87
+ const held = {
88
+ SUI: purse.sui.baseUnits,
89
+ WAL: purse.wal.baseUnits,
90
+ USDC: usdcRead !== null && usdcRead.read ? usdcRead.baseUnits : 0n,
91
+ };
92
+ const sui = held.SUI;
97
93
  // ② The numbers — the browser's rules, unchanged. The gas kept back is the cap the person set,
98
94
  // or the same reserve `wallet send` keeps when none was set.
99
95
  const gasBudgetMist = options.feeCap === undefined ? undefined : clampGasBudgetMist(parseTokenAmountToBaseUnits(options.feeCap) ?? 0n);
100
96
  const keptForGas = gasBudgetMist ?? SUI_GAS_RESERVE_MIST;
101
- const maxIn = direction === "SUI_TO_WAL" ? maxSwappableSuiMist(sui, keptForGas) : wal;
102
- const amountInUnits = amountRaw.toLowerCase() === "max" ? maxIn : parseTokenAmountToBaseUnits(amountRaw);
97
+ const maxIn = coinIn === "SUI" ? maxSwappableSuiMist(sui, keptForGas) : held[coinIn];
98
+ const amountInUnits = amountRaw.toLowerCase() === "max" ? maxIn : parseTokenAmountToBaseUnits(amountRaw, COIN_DECIMALS[coinIn]);
103
99
  if (amountInUnits === null || amountInUnits <= 0n) {
104
- throw new NmtsError("The amount must be a number above zero, with at most nine decimals.", { exitCode: 2 });
100
+ throw new NmtsError(`The amount must be a number above zero, with at most ${COIN_DECIMALS[coinIn]} decimals for ${coinIn}.`, { exitCode: 2 });
105
101
  }
106
- if (amountInUnits > maxIn || (direction === "WAL_TO_SUI" && sui < keptForGas)) {
107
- throw new NmtsError(direction === "WAL_TO_SUI" && sui < keptForGas
108
- ? "A WAL swap pays its fee in SUI, and the wallet holds less SUI than is kept back for that."
102
+ const shortOfGas = coinIn !== "SUI" && sui < keptForGas;
103
+ if (amountInUnits > maxIn || shortOfGas) {
104
+ const holds = [`${coinAmount(sui)} SUI`, `${coinAmount(held.WAL)} WAL`, ...(usdcRead !== null ? [`${amountOf("USDC", held.USDC)} USDC`] : [])];
105
+ throw new NmtsError(shortOfGas
106
+ ? `A ${coinIn} swap pays its fee in SUI, and the wallet holds less SUI than is kept back for that.`
109
107
  : "The wallet does not hold that much.", {
110
108
  exitCode: 4,
111
- nextStep: `Nothing was signed. The wallet holds ${coinAmount(sui)} SUI and ${coinAmount(wal)} WAL; the most that can go in is ${coinAmount(maxIn)} ${coinIn} (SUI keeps ${coinAmount(keptForGas)} back for the fee).`,
109
+ nextStep: `Nothing was signed. The wallet holds ${holds.join(", ")}; the most that can go in is ${amountOf(coinIn, maxIn)} ${coinIn} (SUI keeps ${coinAmount(keptForGas)} back for the fee).`,
112
110
  });
113
111
  }
114
112
  let slippageBps = SLIPPAGE_BPS_DEFAULT;
@@ -126,7 +124,7 @@ export async function walletSwap(operands, options = {}) {
126
124
  if (rails[0] === "exchange") {
127
125
  if (options.venue !== undefined)
128
126
  throw new NmtsError(`On testnet the only rail is ${venueName("exchange")}; --venue does not apply.`, { exitCode: 2 });
129
- if (direction === "WAL_TO_SUI")
127
+ if (direction !== "SUI_TO_WAL")
130
128
  throw new NmtsError(`${venueName("exchange")} only turns SUI into WAL.`, { exitCode: 2 });
131
129
  if (options.slippageBps !== undefined)
132
130
  throw new NmtsError("The testnet facility takes no minimum; --slippage-bps does not apply.", { exitCode: 2 });
@@ -135,7 +133,7 @@ export async function walletSwap(operands, options = {}) {
135
133
  throw new NmtsError("The testnet exchange could not be read, so what it would give is unknown.", { exitCode: 1, nextStep: `Nothing was signed. ${error instanceof Error ? error.message : String(error)}` });
136
134
  });
137
135
  // The facility's rate is a fraction read off its object; there is no fee to measure and no lot to leave over.
138
- quote = { outUnits: (amountInUnits * exchange.rateWal) / exchange.rateSui, feeRateBps: null, leftoverInUnits: 0n };
136
+ quote = { outUnits: (amountInUnits * exchange.rateWal) / exchange.rateSui, feeRateBps: null, leftoverInUnits: 0n, route: "direct", leftoverMidUnits: 0n };
139
137
  }
140
138
  else {
141
139
  if (options.venue !== undefined && options.venue !== "deepbook" && options.venue !== "bluefin") {
@@ -154,10 +152,10 @@ export async function walletSwap(operands, options = {}) {
154
152
  if (options.venue === undefined) {
155
153
  const lines = answers.map((a) => (a.quote === null ? `${a.venue.padEnd(9)} did not answer — ${a.why}` : quoteLine(a.quote, coinOut, coinIn)));
156
154
  if (options.json) {
157
- say(JSON.stringify({ direction, amountInUnits: amountInUnits.toString(), network, quotes: answers.map((a) => (a.quote === null ? { venue: a.venue, answered: false, why: a.why } : { venue: a.venue, answered: true, outUnits: a.quote.outUnits.toString(), feeRateBps: a.quote.feeRateBps, leftoverInUnits: a.quote.leftoverInUnits.toString() })), signed: false }));
155
+ say(JSON.stringify({ direction, amountInUnits: amountInUnits.toString(), network, quotes: answers.map((a) => (a.quote === null ? { venue: a.venue, answered: false, why: a.why } : { venue: a.venue, answered: true, outUnits: a.quote.outUnits.toString(), feeRateBps: a.quote.feeRateBps, leftoverInUnits: a.quote.leftoverInUnits.toString(), route: a.quote.route, leftoverMidUnits: a.quote.leftoverMidUnits.toString() })), signed: false }));
158
156
  return 4;
159
157
  }
160
- say(`Quotes for ${coinAmount(amountInUnits)} ${coinIn} → ${coinOut}, read from the ${network} chain just now`);
158
+ say(`Quotes for ${amountOf(coinIn, amountInUnits)} ${coinIn} → ${coinOut}, read from the ${network} chain just now`);
161
159
  for (const line of lines)
162
160
  say(` ${line}`);
163
161
  say(``);
@@ -175,48 +173,66 @@ export async function walletSwap(operands, options = {}) {
175
173
  bluefin = only.binding ?? undefined;
176
174
  }
177
175
  if (quote.outUnits <= 0n) {
178
- throw new NmtsError(`${venueName(venue)} would give nothing for ${coinAmount(amountInUnits)} ${coinIn}: the amount is below one lot, or the book is empty.`, { exitCode: 4, nextStep: "Nothing was signed." });
176
+ throw new NmtsError(`${venueName(venue)} would give nothing for ${amountOf(coinIn, amountInUnits)} ${coinIn}: the amount is below one lot, or the book is empty.`, { exitCode: 4, nextStep: "Nothing was signed." });
179
177
  }
180
178
  const minOutUnits = venue === "exchange" ? 0n : minOutFromQuote(quote.outUnits, slippageBps);
181
- const shape = { venue, direction, amountInUnits, minOutUnits, gasBudgetMist, bluefin, exchange };
179
+ const shape = { venue, direction, amountInUnits, minOutUnits, gasBudgetMist, bluefin, exchange, route: quote.route };
182
180
  // ④ The fee of this exact swap. ⑤ The market check, said as unknown when it is.
183
181
  const feeMist = await reads.estimateFee(shape, address);
184
182
  const prices = await (options.readPrices ?? (async (base) => asMarketPrices(await request(base, "/api/prices").catch(() => null))))(server).catch(() => null);
185
- const market = marketRate(direction, prices?.suiUsd, prices?.walUsd);
186
- const implied = impliedRate(quote.outUnits, amountInUnits);
183
+ const market = marketRate(direction, prices?.suiUsd, prices?.walUsd, prices?.usdcUsd);
184
+ const implied = impliedRate(quote.outUnits, amountInUnits, COIN_DECIMALS[coinOut], COIN_DECIMALS[coinIn]);
187
185
  const deviationBps = market !== null && implied !== null ? priceDeviationBps(implied, market) : null;
188
186
  const extremes = venue === "exchange" ? [] : swapExtremes({ slippageBps, budgetMist: gasBudgetMist ?? null, estimateMist: feeMist, deviationBps });
189
- const suiAfter = sui - (direction === "SUI_TO_WAL" ? amountInUnits - quote.leftoverInUnits : -quote.outUnits) - (feeMist ?? 0n);
190
- const walAfter = wal - (direction === "WAL_TO_SUI" ? amountInUnits - quote.leftoverInUnits : -quote.outUnits);
187
+ // What each coin would be afterwards if the chain gives exactly the quote. USDC handed back by the
188
+ // middle of a through-USDC route counts as USDC.
189
+ const after = (coin) => {
190
+ let v = held[coin];
191
+ if (coin === coinIn)
192
+ v -= amountInUnits - quote.leftoverInUnits;
193
+ if (coin === coinOut)
194
+ v += quote.outUnits;
195
+ if (coin === "USDC")
196
+ v += quote.leftoverMidUnits;
197
+ if (coin === "SUI")
198
+ v -= feeMist ?? 0n;
199
+ return v < 0n ? 0n : v;
200
+ };
201
+ const showsUsdc = usdcRead !== null || quote.leftoverMidUnits > 0n;
191
202
  const facts = {
192
203
  from: address,
193
204
  venue,
194
205
  direction,
206
+ route: quote.route,
195
207
  amountInUnits: amountInUnits.toString(),
196
- amountIn: coinAmount(amountInUnits),
208
+ amountIn: amountOf(coinIn, amountInUnits),
197
209
  coinIn,
198
210
  coinOut,
199
211
  quotedOutUnits: quote.outUnits.toString(),
200
- quotedOut: coinAmount(quote.outUnits),
212
+ quotedOut: amountOf(coinOut, quote.outUnits),
201
213
  minOutUnits: minOutUnits.toString(),
202
- minOut: coinAmount(minOutUnits),
214
+ minOut: amountOf(coinOut, minOutUnits),
203
215
  slippageBps: venue === "exchange" ? null : slippageBps,
204
216
  venueFeeBps: quote.feeRateBps,
205
217
  leftoverInUnits: quote.leftoverInUnits.toString(),
218
+ leftoverMidUsdcUnits: quote.leftoverMidUnits.toString(),
206
219
  feeMist: feeMist === null ? null : feeMist.toString(),
207
220
  feeSui: feeMist === null ? null : coinAmount(feeMist),
208
221
  feeCapMist: gasBudgetMist === undefined ? null : gasBudgetMist.toString(),
209
222
  deviationBps: deviationBps === null ? null : Math.round(deviationBps * 100) / 100,
210
223
  extremes,
211
224
  network,
212
- suiAfter: coinAmount(suiAfter < 0n ? 0n : suiAfter),
213
- walAfter: coinAmount(walAfter < 0n ? 0n : walAfter),
225
+ suiAfter: coinAmount(after("SUI")),
226
+ walAfter: coinAmount(after("WAL")),
227
+ usdcAfter: showsUsdc ? amountOf("USDC", after("USDC")) : null,
214
228
  };
215
229
  // ⑥ The review, every time.
216
230
  if (!options.json) {
217
231
  say(`Swapping ${facts.amountIn} ${coinIn} for ${coinOut} on ${venueName(venue)}`);
218
232
  say(` from ${address} (wallet ${wallet})`);
219
- say(` Quoted ${facts.quotedOut} ${coinOut} — the chain's answer just now, not a promise${quote.leftoverInUnits > 0n ? `; ${coinAmount(quote.leftoverInUnits)} ${coinIn} would come back unused` : ""}`);
233
+ if (quote.route === "viaUsdc")
234
+ say(` Route ${coinIn} → USDC → ${coinOut}, two pools in one transaction; the minimum covers the whole trade`);
235
+ say(` Quoted ${facts.quotedOut} ${coinOut} — the chain's answer just now, not a promise${quote.leftoverInUnits > 0n ? `; ${amountOf(coinIn, quote.leftoverInUnits)} ${coinIn} would come back unused` : ""}${quote.leftoverMidUnits > 0n ? `; ${amountOf("USDC", quote.leftoverMidUnits)} USDC would come back unused` : ""}`);
220
236
  if (venue === "exchange")
221
237
  say(` Rate ${exchange?.rateWal} WAL per ${exchange?.rateSui} SUI, read off the facility; it takes no minimum`);
222
238
  else
@@ -226,7 +242,7 @@ export async function walletSwap(operands, options = {}) {
226
242
  if (gasBudgetMist !== undefined)
227
243
  say(` Fee cap ${coinAmount(gasBudgetMist)} SUI — only up to this is used; the rest stays`);
228
244
  say(deviationBps === null ? ` Market no reference price could be read just now, so the quote was not compared with the market` : ` Market ${pct(deviationBps)} from the site's reference price (1 ${coinIn} ≈ ${market?.toFixed(4)} ${coinOut})`);
229
- say(` Afterwards, if the chain gives exactly the quote: about ${facts.suiAfter} SUI and ${facts.walAfter} WAL`);
245
+ say(` Afterwards, if the chain gives exactly the quote: about ${facts.suiAfter} SUI and ${facts.walAfter} WAL${facts.usdcAfter === null ? "" : ` and ${facts.usdcAfter} USDC`}`);
230
246
  say(``);
231
247
  say(` NMTS is not a party to this trade and takes nothing from it. Any other exchange may be used instead.`);
232
248
  if (extremes.length > 0) {
@@ -271,10 +287,18 @@ export async function walletSwap(operands, options = {}) {
271
287
  }
272
288
  // ⑨ The agreement — scope `all`, the amount and the fee held against its ceiling.
273
289
  const spend = {
274
- walFrost: direction === "WAL_TO_SUI" ? amountInUnits : 0n,
275
- suiMist: (direction === "SUI_TO_WAL" ? amountInUnits : 0n) + (feeMist ?? 0n),
290
+ walFrost: coinIn === "WAL" ? amountInUnits : 0n,
291
+ suiMist: (coinIn === "SUI" ? amountInUnits : 0n) + (feeMist ?? 0n),
276
292
  };
277
- requireWalletGrant("exchange", spend, new Date(options.now ?? Date.now()));
293
+ const grant = requireWalletGrant("exchange", spend, new Date(options.now ?? Date.now()));
294
+ // ⛔ The agreement's ceilings count SUI and WAL. A USDC spend cannot be held against them, so under
295
+ // an agreement that HAS a ceiling it is refused rather than signed uncounted.
296
+ if (coinIn === "USDC" && (grant.capWalFrost !== null || grant.capSuiMist !== null)) {
297
+ throw new NmtsError("The wallet agreement on this machine has a spending ceiling, and its ceilings count SUI and WAL only.", {
298
+ exitCode: 5,
299
+ nextStep: `Nothing was signed. A USDC swap under a ceiling would go uncounted, so it is refused. To swap USDC, agree again without --cap-wal and --cap-sui: ${BINARY_NAME} unlock wallet --days 7 --scope all`,
300
+ });
301
+ }
278
302
  // ⑩ The signature.
279
303
  const sign = options.sign ?? (await import("../wallet-sign.js")).signSwap;
280
304
  const digest = await sign({ network, code: resolved.code, wallet, shape });
@@ -286,6 +310,6 @@ export async function walletSwap(operands, options = {}) {
286
310
  say(``);
287
311
  say(` Swapped. Transaction ${digest}`);
288
312
  say(` ${explorerTxUrl(digest, network)}`);
289
- say(` What arrived is what the chain gave — at least the minimum above. \`${BINARY_NAME} wallet\` shows both balances now.`);
313
+ say(` What arrived is what the chain gave — at least the minimum above. \`${BINARY_NAME} wallet\` shows the SUI and WAL balances now.`);
290
314
  return 0;
291
315
  }
@@ -80,7 +80,8 @@ export function optionLines() {
80
80
  ` be listed under in the gift hall of fame (wallet hall)`,
81
81
  ` --to <folder> Destination folder, as \`${BINARY_NAME} ls\` prints it (put, push).`,
82
82
  ` For \`credits transfer\` it is the account identifier that receives;`,
83
- ` for \`handover make\`, a public code or a public code file`,
83
+ ` for \`handover make\`, a public code or a public code file;`,
84
+ ` for \`wallet swap\`, the coin to receive (SUI, WAL or USDC)`,
84
85
  ` --dry-run Say what it would cost, and stop (put, push, extend), or what it`,
85
86
  ` would install, and stop (update). With \`extend\` and \`--pay`,
86
87
  ` wallet\` nothing is signed and the wallet key is never touched`,
package/dist/help.js CHANGED
@@ -78,9 +78,10 @@ export function helpText(version) {
78
78
  ` wallet send <SUI|WAL> <amount|max> <address>`,
79
79
  ` Send coins to an address — **signs and spends from the wallet**.`,
80
80
  ` Prints the review; sends only with --yes`,
81
- ` wallet swap <SUI|WAL> <amount|max>`,
82
- ` Swap one coin for the other on DeepBook or Bluefin (mainnet) —`,
83
- ` **signs and spends**. Without --venue, quotes both and stops`,
81
+ ` wallet swap <SUI|WAL|USDC> <amount|max> [--to <SUI|WAL|USDC>]`,
82
+ ` Swap SUI, WAL and USDC, any direction, on DeepBook or Bluefin`,
83
+ ` (mainnet) — **signs and spends**. Without --venue, quotes both`,
84
+ ` and stops. Without --to, SUI→WAL and WAL→SUI; USDC needs --to`,
84
85
  ` wallet donate <SUI|WAL> <amount>`,
85
86
  ` A voluntary gift to the developer — **signs and spends**. A person's`,
86
87
  ` act: refused in mode auto, and needs --yes every time`,
@@ -131,6 +132,8 @@ export function helpText(version) {
131
132
  ` link make <path> Make a public link to a file`,
132
133
  ` link list <path> List a file's public links`,
133
134
  ` link revoke <id> Cut a public link`,
135
+ ` links List every live public link this account holds, with each file's path`,
136
+ ` links revoke-all Cut every live public link at once`,
134
137
  ` link open <link> Download and decrypt a file from a public link, without logging in`,
135
138
  ` env What this machine is, and what it means for the NMTS key`,
136
139
  ` unlock [name] What this machine has unlocked; \`unlock <name>\` opens one — a person,`,
package/dist/links.d.ts CHANGED
@@ -18,6 +18,8 @@ export interface MadeLink {
18
18
  }
19
19
  export interface ListedLink {
20
20
  id: string;
21
+ /** The server's id for the file the link opens. */
22
+ itemId: string;
21
23
  /** The whole link again, or null when it is cut (or its sealed secret did not open). */
22
24
  link: string | null;
23
25
  showsName: boolean;
@@ -36,6 +38,13 @@ export declare function makeLink(account: LinkAccount, entry: ManifestEntry, opt
36
38
  }): Promise<MadeLink>;
37
39
  /** Every link the account made to one file, newest first, cut ones included. */
38
40
  export declare function listLinks(account: LinkAccount, itemId: string): Promise<ListedLink[]>;
41
+ /**
42
+ * Every LIVE link the account holds, across all its files, newest first. Each names its file by
43
+ * `itemId`; the file's name is in the account's own sealed list, which the server cannot read.
44
+ */
45
+ export declare function listLiveLinks(account: LinkAccount): Promise<ListedLink[]>;
46
+ /** Cut every live link the account holds, in one request: all or none. Returns how many were cut. */
47
+ export declare function revokeAllLinks(account: LinkAccount): Promise<number>;
39
48
  /** Cut one of the account's links. Cutting one that is already cut is not an error. */
40
49
  export declare function revokeLink(account: LinkAccount, id: string): Promise<void>;
41
50
  export interface OpenedLinkFile {
package/dist/links.js CHANGED
@@ -89,6 +89,25 @@ export async function listLinks(account, itemId) {
89
89
  const answer = await request(account.server, `/v1/share-links?item_id=${encodeURIComponent(itemId)}`, {
90
90
  token: account.bearer,
91
91
  });
92
+ return listedFrom(account, answer);
93
+ }
94
+ /**
95
+ * Every LIVE link the account holds, across all its files, newest first. Each names its file by
96
+ * `itemId`; the file's name is in the account's own sealed list, which the server cannot read.
97
+ */
98
+ export async function listLiveLinks(account) {
99
+ return listedFrom(account, await request(account.server, "/v1/share-links/live", { token: account.bearer }));
100
+ }
101
+ /** Cut every live link the account holds, in one request: all or none. Returns how many were cut. */
102
+ export async function revokeAllLinks(account) {
103
+ const answer = await request(account.server, "/v1/share-links", { method: "DELETE", token: account.bearer });
104
+ const cut = isRecord(answer) ? answer["cut"] : null;
105
+ if (typeof cut !== "number")
106
+ throw new NmtsError("The server's answer did not say how many links were cut.");
107
+ return cut;
108
+ }
109
+ /** A list answer's rows, each with its whole link rebuilt from the owner's sealed copy of `S`. */
110
+ async function listedFrom(account, answer) {
92
111
  const rows = isRecord(answer) ? answer["links"] : null;
93
112
  if (!Array.isArray(rows))
94
113
  throw new NmtsError("The server listed the links in a shape this version cannot read.");
@@ -113,6 +132,7 @@ export async function listLinks(account, itemId) {
113
132
  }
114
133
  return {
115
134
  id,
135
+ itemId: text(row["item_id"]) ?? "",
116
136
  link,
117
137
  showsName: row["disclosed_name"] === true,
118
138
  createdAt: text(row["created_at"]) ?? "",