@needmoretruth/nmts-cli 0.41.0 → 0.43.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.43.0 — 2026-09-20
7
+
8
+ - Nothing changes for the `nmts` command: it signs with the wallet this NMTS key derives, as it
9
+ always has, and a terminal has no browser extension to offer instead.
10
+ - The library surface has a new entry, `@needmoretruth/nmts-cli/wallet-sign-external`: a program can
11
+ pay for an upload, an extension or a change to a storage resource with a wallet it holds no key to
12
+ — a browser extension, a hardware wallet, a remote signer — by handing over the payer's address and
13
+ a function that signs transaction bytes. The transactions are the same builders the key's own
14
+ signers use, this package submits them and reads the effects rather than trusting a digest, and a
15
+ wallet that declines is `WALLET_REFUSED`.
16
+ - A wallet-paid upload and an extension take that payer before they read a balance
17
+ (`WalletPutContext.payer`, `ExtendPlanSeams.payer`), so the quote, both balances, the measured
18
+ chain fee, the review and the sentence saying where to send coins all name the wallet that will
19
+ sign. Without a payer every one of them is the wallet this key derives, unchanged.
20
+ - An unfinished wallet-paid upload records which wallet paid, and a later run that would pay from a
21
+ different one is refused before it signs: what a registration creates belongs to the address that
22
+ signed for it.
23
+
24
+ ## 0.42.0 — 2026-09-20
25
+
26
+ - Nothing changes for the `nmts` command. The library surface gains one seam for programs built on
27
+ it: a caller can name the upload relay, the Sui nodes and the aggregators, and hand over the
28
+ `fetch` function every request goes through (`@needmoretruth/nmts-cli/portable`: `useReach`). The
29
+ command reads its addresses from the environment as before and sets none of it.
30
+
6
31
  ## 0.41.0 — 2026-09-20
7
32
 
8
33
  - **Wallet login.** `nmts login --wallet --sui-key-file <file>` signs in with a Sui wallet, and
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.41.0 # 버전을 고정할 때
53
+ npm install -g github:needmoretruth/nmts-cli#v0.43.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.41.0 # a pinned version
54
+ npm install -g github:needmoretruth/nmts-cli#v0.43.0 # a pinned version
55
55
  npm install -g https://github.com/needmoretruth/nmts-cli/releases/latest/download/nmts.tgz
56
56
  ```
57
57
 
package/dist/api.js CHANGED
@@ -13,6 +13,7 @@
13
13
  import { adviseFor } from "./api-advice.js";
14
14
  import { NmtsError } from "./errors.js";
15
15
  import { isTransient, keepTrying } from "./net-retry.js";
16
+ import { reachFetch } from "./reach.js";
16
17
  import { noteRequest } from "./run-log.js";
17
18
  /** Default deadline for a request that is not moving file bytes. */
18
19
  export const DEFAULT_TIMEOUT_MS = 30_000;
@@ -109,7 +110,7 @@ async function once(base, path, options) {
109
110
  const init = { method, headers, signal: controller.signal };
110
111
  if (body !== undefined)
111
112
  init.body = JSON.stringify(body);
112
- response = await fetch(`${base}${path}`, init);
113
+ response = await reachFetch(`${base}${path}`, init);
113
114
  }
114
115
  catch (error) {
115
116
  // ⛔ The cause is named, not swallowed: "fetch failed" alone sends an agent looking at its own
@@ -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.41.0";
14
+ export declare const WRITTEN_BY = "nmts-cli 0.43.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
  /**
@@ -21,6 +21,7 @@ import { NmtsError } from "./errors.js";
21
21
  import { epochClock } from "./expiry.js";
22
22
  import { isRecord } from "./guards.js";
23
23
  import { epochStartedMs } from "./walrus-write.js";
24
+ import { storageNodesThrough } from "./walrus.js";
24
25
  import { suiRpcTransport } from "./sui-rpc.js";
25
26
  import { readBalances, walCoinType } from "./wallet.js";
26
27
  import { chainReader } from "./wallet-chain.js";
@@ -41,7 +42,7 @@ function build(network) {
41
42
  return new SuiJsonRpcClient({
42
43
  network: network === "mainnet" ? "mainnet" : "testnet",
43
44
  transport: suiRpcTransport(network),
44
- }).$extend(walrus({}));
45
+ }).$extend(walrus(storageNodesThrough()));
45
46
  }
46
47
  /** A number off the wire, whether it arrived as a number or as one of Sui's 64-bit strings. */
47
48
  function numberOf(value) {
@@ -1,6 +1,8 @@
1
1
  export { forgetHost, host, hostIsRegistered, registerHost } from "./host.ts";
2
2
  export type { EngineHost, Host, HostName, StateHost, ZstdHost } from "./host.ts";
3
3
  export { hostContract } from "./host-contract.ts";
4
+ export { forgetReach, reach, reachFetch, useReach } from "./reach.ts";
5
+ export type { Reach } from "./reach.ts";
4
6
  export { concat, fromBase64Url, fromUtf8, toBase64Url, utf8 } from "./bytes.ts";
5
7
  export { setZstdCodec, zstdCodec, zstdContentSize } from "./shared/lib/drive/zstd.ts";
6
8
  export type { ZstdCodec } from "./shared/lib/drive/zstd.ts";
@@ -46,6 +48,7 @@ export { fetchFile, fetchWithKey } from "./download.ts";
46
48
  export type { FetchedFile, FetchInput } from "./download.ts";
47
49
  export type { PlaintextSink } from "./download-sink.ts";
48
50
  export { AGGREGATOR_ENV_VAR, readBlob, RELAY_ENV_VAR, SUI_RPC_ENV_VAR } from "./walrus.ts";
51
+ export { relayHost, storageNodesThrough, suiRpcHosts } from "./walrus.ts";
49
52
  export type { ReadOptions } from "./walrus.ts";
50
53
  export { coinAmount, readBalances, walCoinType, walletAddress } from "./wallet.ts";
51
54
  export type { ChainReader, CoinBalance, WalletBalances } from "./wallet.ts";
package/dist/portable.js CHANGED
@@ -19,6 +19,10 @@
19
19
  // The host every module below reaches for. A program that imported this entry point registers one.
20
20
  export { forgetHost, host, hostIsRegistered, registerHost } from "./host.js";
21
21
  export { hostContract } from "./host-contract.js";
22
+ // Where a caller says this client talks, and what it talks through — the addresses the
23
+ // command-line tool takes from its environment, and the one `fetch` every request here goes
24
+ // through. A library's caller has no environment to write, so this is how it says the same things.
25
+ export { forgetReach, reach, reachFetch, useReach } from "./reach.js";
22
26
  // Bytes to text and back, in the two spellings the format uses.
23
27
  export { concat, fromBase64Url, fromUtf8, toBase64Url, utf8 } from "./bytes.js";
24
28
  // The file-list codec's zstd register (NCF-3 §6.3.4). A host fills it with the encoder its runtime
@@ -66,6 +70,10 @@ export { DEFAULT_UPLOAD_EPOCHS } from "./upload-wallet-plan.js";
66
70
  // Downloading: fetching sealed parts from the storage network and opening them here.
67
71
  export { fetchFile, fetchWithKey } from "./download.js";
68
72
  export { AGGREGATOR_ENV_VAR, readBlob, RELAY_ENV_VAR, SUI_RPC_ENV_VAR } from "./walrus.js";
73
+ // ⛔ THE THREE ADDRESS ANSWERS, so that a caller — and a test — can ask what this client WILL talk
74
+ // to rather than finding out from a request that went somewhere else. Each reads what the
75
+ // caller said first, then the environment, then the network's own.
76
+ export { relayHost, storageNodesThrough, suiRpcHosts } from "./walrus.js";
69
77
  // The wallet the NMTS key derives: reading it, and signing with it.
70
78
  export { coinAmount, readBalances, walCoinType, walletAddress } from "./wallet.js";
71
79
  export { chainReader } from "./wallet-chain.js";
package/dist/product.d.ts CHANGED
@@ -9,7 +9,7 @@ export declare const BINARY_NAME = "nmts";
9
9
  * beside it. Here rather than in `main.ts` because the MCP server has to say it too, and a
10
10
  * command importing the entry point is a cycle waiting to bite.
11
11
  */
12
- export declare const VERSION = "0.41.0";
12
+ export declare const VERSION = "0.43.0";
13
13
  /** Where the product lives, for messages that need to send somebody somewhere real. */
14
14
  export declare const HOME_URL = "https://nmts.me";
15
15
  /** The source, so a person holding only the built program can find what it was built from. */
package/dist/product.js CHANGED
@@ -18,7 +18,7 @@ export const BINARY_NAME = "nmts";
18
18
  * beside it. Here rather than in `main.ts` because the MCP server has to say it too, and a
19
19
  * command importing the entry point is a cycle waiting to bite.
20
20
  */
21
- export const VERSION = "0.41.0";
21
+ export const VERSION = "0.43.0";
22
22
  /** Where the product lives, for messages that need to send somebody somewhere real. */
23
23
  export const HOME_URL = "https://nmts.me";
24
24
  /** The source, so a person holding only the built program can find what it was built from. */
@@ -32,5 +32,9 @@ export declare class Progress {
32
32
  *
33
33
  * ⚠ `duplex: "half"` is required by the fetch specification for a streaming body and Node enforces
34
34
  * it. Without it the request throws before a single byte is sent.
35
+ *
36
+ * ⛔ IT WRAPS `reachFetch`, NOT THE GLOBAL. Counting the bytes must not be a way around the
37
+ * function a caller asked every request to go through — this is the one request in an upload
38
+ * that carries the file.
35
39
  */
36
40
  export declare function countingFetch(onSent: (sent: number, total: number) => void, chunkBytes?: number): (url: RequestInfo, init?: RequestInit) => Promise<Response>;
package/dist/progress.js CHANGED
@@ -11,6 +11,7 @@
11
11
  // ⛔ THE TERMINAL SINK IS NOT HERE. Writing to a real stderr is Node's, so it is in
12
12
  // `progress-node.ts`; what is left runs in a page, where the same reporter drives a caller's
13
13
  // own `onProgress`.
14
+ import { reachFetch } from "./reach.js";
14
15
  /** A reporter that says nothing. What `--json` gets, and what a test gets by default. */
15
16
  export function silentSink() {
16
17
  return { write: () => { }, interactive: false };
@@ -71,12 +72,16 @@ export class Progress {
71
72
  *
72
73
  * ⚠ `duplex: "half"` is required by the fetch specification for a streaming body and Node enforces
73
74
  * it. Without it the request throws before a single byte is sent.
75
+ *
76
+ * ⛔ IT WRAPS `reachFetch`, NOT THE GLOBAL. Counting the bytes must not be a way around the
77
+ * function a caller asked every request to go through — this is the one request in an upload
78
+ * that carries the file.
74
79
  */
75
80
  export function countingFetch(onSent, chunkBytes = 256 * 1024) {
76
81
  return async (url, init) => {
77
82
  const body = init?.body;
78
83
  if (!(body instanceof Uint8Array))
79
- return fetch(url, init);
84
+ return reachFetch(url, init);
80
85
  const total = body.length;
81
86
  let sent = 0;
82
87
  const stream = new ReadableStream({
@@ -101,6 +106,6 @@ export function countingFetch(onSent, chunkBytes = 256 * 1024) {
101
106
  if (!headers.has("content-length"))
102
107
  headers.set("content-length", String(total));
103
108
  next.headers = headers;
104
- return fetch(url, next);
109
+ return reachFetch(url, next);
105
110
  };
106
111
  }
@@ -0,0 +1,40 @@
1
+ /** What a caller may say about where this client talks, and what it talks through. */
2
+ export interface Reach {
3
+ /**
4
+ * The storage network's upload relay to write through, instead of the network's own.
5
+ *
6
+ * ⚠ ONE host, not a list: the relay is named inside the transaction that pays its tip, so a
7
+ * write picks its host before the storage is bought and never moves.
8
+ */
9
+ relay?: string | undefined;
10
+ /**
11
+ * The Sui JSON-RPC endpoints to ask, in order, instead of the network's own.
12
+ *
13
+ * ⛔ IT REPLACES THE LIST rather than adding to it — somebody who names a node is saying *those*,
14
+ * and quietly reaching a public mirror as well would send their traffic somewhere they did
15
+ * not choose.
16
+ */
17
+ suiRpc?: readonly string[] | undefined;
18
+ /** Hosts to read stored bytes from, instead of the public aggregators for the network. */
19
+ aggregators?: readonly string[] | undefined;
20
+ /**
21
+ * The function every request this package makes goes through. Absent, the runtime's own.
22
+ *
23
+ * It is where a proxy goes: an agent, a SOCKS tunnel, a recorder, a counter. Nothing about a
24
+ * proxy is built into this package, because one function is the whole of what it would need.
25
+ */
26
+ fetch?: typeof fetch | undefined;
27
+ }
28
+ /** What the caller has said. */
29
+ export declare function reach(): Reach;
30
+ /** Tell this package what the caller chose. Fields that are absent leave what was there. */
31
+ export declare function useReach(next: Reach): void;
32
+ /** Start again with nothing — the runtime's own addresses and its own `fetch`. For tests. */
33
+ export declare function forgetReach(): void;
34
+ /**
35
+ * The one function every request in this package goes through.
36
+ *
37
+ * With nothing injected it is the runtime's `fetch`, called as the runtime's own — which is what
38
+ * the command-line tool has always done, byte for byte.
39
+ */
40
+ export declare const reachFetch: typeof fetch;
package/dist/reach.js ADDED
@@ -0,0 +1,52 @@
1
+ // Where this program talks, and what it talks through — the caller's answer, not the runtime's.
2
+ //
3
+ // ⛔ WHY THIS IS NOT THE HOST. `host.ts` holds what a RUNTIME provides: an engine, a store, an
4
+ // environment, somewhere for progress to go, a zstd encoder. What is here is what a CALLER
5
+ // chose: a relay, a set of Sui nodes, a set of aggregators, and the function every request goes
6
+ // through. The command-line tool sets none of it and reads its addresses out of the environment
7
+ // exactly as it always has; a library's caller has no environment to write, and until this file
8
+ // existed the options it passed for two of those addresses were read only by the browser host —
9
+ // silently ignored on Node, which is the defect this fixes.
10
+ //
11
+ // ⛔ AN OPTION THAT WAS PASSED IS HONOURED ON EVERY HOST, or refused by name. Nothing in this
12
+ // package may quietly reach an address the caller did not choose: for somebody routing their
13
+ // traffic through a proxy, one leak makes the proxy a lie rather than a weaker promise.
14
+ //
15
+ // ⛔ IT IS READ AT THE MOMENT OF THE REQUEST, not copied when a client is made. `reachFetch` looks
16
+ // the function up on every call, so a caller that set one after building its client is not
17
+ // holding a stale copy.
18
+ //
19
+ // ⚠ ONE PER PROCESS, AND THE LAST WRITER WINS THE FIELDS IT NAMES. This is the same arrangement
20
+ // the SDK's `host-options.ts` already describes for a page: two clients pointed at different
21
+ // relays would be two answers to a question with one answer. On a server that means two clients
22
+ // with two different proxies share whichever was set last — said here rather than discovered.
23
+ //
24
+ // ⛔ NO `node:` IMPORT, EVER. This file is reachable from `portable.ts`, which promises that.
25
+ let current = {};
26
+ /** What the caller has said. */
27
+ export function reach() {
28
+ return current;
29
+ }
30
+ /** Tell this package what the caller chose. Fields that are absent leave what was there. */
31
+ export function useReach(next) {
32
+ const merged = { ...current };
33
+ for (const key of Object.keys(next)) {
34
+ if (next[key] !== undefined)
35
+ Reflect.set(merged, key, next[key]);
36
+ }
37
+ current = merged;
38
+ }
39
+ /** Start again with nothing — the runtime's own addresses and its own `fetch`. For tests. */
40
+ export function forgetReach() {
41
+ current = {};
42
+ }
43
+ /**
44
+ * The one function every request in this package goes through.
45
+ *
46
+ * With nothing injected it is the runtime's `fetch`, called as the runtime's own — which is what
47
+ * the command-line tool has always done, byte for byte.
48
+ */
49
+ export const reachFetch = (input, init) => {
50
+ const given = current.fetch;
51
+ return given === undefined ? globalThis.fetch(input, init) : given(input, init);
52
+ };
@@ -79,6 +79,16 @@ export interface ExtendPlanSeams {
79
79
  epochs?: string | number | undefined;
80
80
  /** Which of this key's wallets pays. Absent = the account's own number, out of the list read here. */
81
81
  wallet?: number | undefined;
82
+ /**
83
+ * A wallet OUTSIDE this tool that pays instead — its address, because this is where the price is
84
+ * measured against a balance.
85
+ *
86
+ * ⛔ THE SIGNATURE HAS TO COME FROM THE SAME ADDRESS (`wallet-sign-external.ts`), and the blobs
87
+ * have to be ones that wallet paid for: extending storage is a payment by whoever holds it.
88
+ */
89
+ payer?: {
90
+ address: string;
91
+ } | undefined;
82
92
  /** The instant to measure against. Passed in so one run reports one moment. */
83
93
  now: number;
84
94
  /** What this caller wants said in a refusal instead of the neutral sentence. */
@@ -107,7 +107,7 @@ export async function planExtension(input, target, seams) {
107
107
  // ⛔ WHICH WALLET PAYS comes out of the list this run already read, before the price is measured
108
108
  // against a balance: the address below is the one that will sign.
109
109
  const wallet = seams.wallet ?? activeWalletOf(settings);
110
- const address = await walletAddress(input.code, wallet);
110
+ const address = seams.payer?.address ?? (await walletAddress(input.code, wallet));
111
111
  const budget = await readBudget(reads, { address, objectIds, epochs, priceFrost: frost });
112
112
  return {
113
113
  facts: {
package/dist/sui-rpc.js CHANGED
@@ -9,6 +9,7 @@
9
9
  // ⛔ NOT A RETRIER. Each host is asked once. Anything other than "no answer" — any 4xx that is not
10
10
  // 429 — is an answer, and asking a different node the same question gets the same one.
11
11
  import { JsonRpcHTTPTransport } from "@mysten/sui/jsonRpc";
12
+ import { reachFetch } from "./reach.js";
12
13
  import { suiRpcHosts } from "./walrus.js";
13
14
  /** HTTP statuses that mean "no answer came", the only ones worth asking a second node about. */
14
15
  function worthAnotherHost(status) {
@@ -39,7 +40,7 @@ export function suiRpcTransport(network) {
39
40
  if (host === undefined)
40
41
  continue;
41
42
  try {
42
- const res = await fetch(new URL(asked.pathname + asked.search, host), init);
43
+ const res = await reachFetch(new URL(asked.pathname + asked.search, host), init);
43
44
  if (worthAnotherHost(res.status) && step < hosts.length - 1) {
44
45
  lastError = new Error(`${host} answered ${res.status}`);
45
46
  continue;
@@ -119,6 +119,16 @@ export interface Reservation {
119
119
  * a part under the wrong payer.
120
120
  */
121
121
  paidFrom?: "wallet";
122
+ /**
123
+ * Wallet rail: the address that signed, when the wallet paying was one OUTSIDE this tool. Absent
124
+ * when the wallet this NMTS key derives paid, which is what it has always been.
125
+ *
126
+ * ⛔ WRITTEN SO A RESUME CANNOT CHANGE PAYER. What a registration creates belongs to the address
127
+ * that signed for it: only that wallet can certify the part or ever reclaim its storage. A
128
+ * later run paying from somewhere else would spend a fee to be refused on-chain, so
129
+ * `upload-wallet.ts` compares this and says so instead.
130
+ */
131
+ payerAddress?: string;
122
132
  /** Wallet rail: present once the certify transaction executed — the part is finished on-chain. */
123
133
  certifyTxDigest?: string;
124
134
  /** Wallet rail: the epoch the bought storage ends at, read from the blob object after registering. */
@@ -24,8 +24,10 @@ import { blobIdFromInt, blobIdToInt, MAINNET_WALRUS_PACKAGE_CONFIG, TESTNET_WALR
24
24
  import { fromBase64Url } from "./bytes.js";
25
25
  import { NmtsError } from "./errors.js";
26
26
  import { extendReads, netGasFee, readBlobLease } from "./extend-chain.js";
27
+ import { reachFetch } from "./reach.js";
27
28
  import { readOwnedStorage, readStorageType } from "./shared/lib/storage-control/chain.js";
28
29
  import { registerIntoStorage, splitStorageToFit } from "./shared/lib/storage-control/reuse.js";
30
+ import { storageNodesThrough } from "./walrus.js";
29
31
  import { suiRpcTransport } from "./sui-rpc.js";
30
32
  import { readBalances, walCoinType } from "./wallet.js";
31
33
  import { chainReader } from "./wallet-chain.js";
@@ -46,7 +48,10 @@ export function packageConfig(network) {
46
48
  return network === "mainnet" ? MAINNET_WALRUS_PACKAGE_CONFIG : TESTNET_WALRUS_PACKAGE_CONFIG;
47
49
  }
48
50
  function build(network, relayUrl) {
49
- return new SuiJsonRpcClient({ network, transport: suiRpcTransport(network) }).$extend(walrus({ uploadRelay: { host: relayUrl, sendTip: { max: RELAY_TIP_CEILING_MIST[network] } } }));
51
+ return new SuiJsonRpcClient({ network, transport: suiRpcTransport(network) }).$extend(walrus({
52
+ ...storageNodesThrough(),
53
+ uploadRelay: { host: relayUrl, sendTip: { max: RELAY_TIP_CEILING_MIST[network] }, fetch: reachFetch },
54
+ }));
50
55
  }
51
56
  /** A Walrus client bound to ONE relay, able to pay that relay's tip. */
52
57
  export function payingClient(network, relayUrl) {
@@ -28,8 +28,24 @@ export interface WalletPutContext {
28
28
  * ⛔ THE CALLER RESOLVES IT, BEFORE ANYTHING IS PRICED. It is the account's own number, kept in
29
29
  * the sealed file list (`wallet-pay-index.ts`), and a library that guessed at it here would
30
30
  * price one address and sign with another.
31
+ *
32
+ * ⚠ Ignored when `payer` names a wallet this key does not derive — see below.
31
33
  */
32
34
  wallet: number;
35
+ /**
36
+ * A wallet OUTSIDE this tool that pays instead: somebody's browser extension, a hardware wallet,
37
+ * a remote signer.
38
+ *
39
+ * ⛔ IT IS THE ADDRESS, HERE, BECAUSE THIS IS WHERE THE PRICE IS MEASURED. Everything below reads
40
+ * one address — the quote's sender, both balances, the measured register fee, the review, and
41
+ * the sentence that says where to send coins — and that address has to be the one that will
42
+ * sign. Absent, it is the wallet `wallet` names, exactly as before; present, the `sign` seam
43
+ * must be the signer of that same address (`wallet-sign-external.ts`), and nothing here derives
44
+ * a key at all.
45
+ */
46
+ payer?: {
47
+ address: string;
48
+ } | undefined;
33
49
  }
34
50
  /** One file and where it goes — already resolved, because a library resolves nothing by asking. */
35
51
  export interface WalletPutFile {
@@ -73,8 +73,9 @@ export async function walletPut(ctx, file, seams = {}) {
73
73
  const epochs = chooseUploadEpochs(seams.epochs, window);
74
74
  const endEpoch = window.clock.current + epochs;
75
75
  const quotes = await reads.quoteParts(sealedLens, epochs);
76
- // ⛔ THE ADDRESS THAT IS PRICED IS THE ADDRESS THAT SIGNS — the same number the rail carries.
77
- const address = await walletAddress(ctx.code, ctx.wallet);
76
+ // ⛔ THE ADDRESS THAT IS PRICED IS THE ADDRESS THAT SIGNS — the same wallet the rail carries,
77
+ // whether that is a number this key derives or a wallet the caller holds the key to.
78
+ const address = ctx.payer?.address ?? (await walletAddress(ctx.code, ctx.wallet));
78
79
  let storage = { kind: "buy" };
79
80
  let heldResources = null;
80
81
  if (storageAsk !== null) {
@@ -159,6 +160,7 @@ export async function walletPut(ctx, file, seams = {}) {
159
160
  network: ctx.network,
160
161
  code: ctx.code,
161
162
  wallet: ctx.wallet,
163
+ ...(ctx.payer === undefined ? {} : { payer: ctx.payer }),
162
164
  relayUrl: protocol.relayUrl,
163
165
  epochs,
164
166
  storage,
@@ -10,6 +10,17 @@ export interface WalletRailContext {
10
10
  /** Which of this key's wallets pays — the account's own number, resolved before anything was
11
11
  * priced (`wallet-pay-index.ts`), so the address in the review is the address that signs. */
12
12
  wallet: number;
13
+ /**
14
+ * Set when a wallet OUTSIDE this tool is paying, and then it is that wallet's address.
15
+ *
16
+ * ⛔ IT GOES INTO THE RECORD SO A RESUME CANNOT CHANGE PAYER. The blob object a registration
17
+ * creates belongs to the address that signed for it, and only that address can certify it or
18
+ * reclaim its storage. A second run that finished this part from another wallet would spend a
19
+ * fee to be refused by the chain, so the mismatch is said here instead.
20
+ */
21
+ payer?: {
22
+ address: string;
23
+ } | undefined;
13
24
  relayUrl: string;
14
25
  epochs: number;
15
26
  /** Where the storage comes from. A held resource serves one blob, so it applies to a one-part file. */
@@ -41,6 +41,19 @@ async function buyAndPushPartWithWallet(ctx, input) {
41
41
  "to start over. Nothing was sent.",
42
42
  });
43
43
  }
44
+ // ⛔ THE SAME WALLET FINISHES WHAT IT STARTED. The record names the payer when one was outside
45
+ // this tool; whoever is paying now has to be the same address, because the blob object and its
46
+ // storage belong to the wallet that registered them.
47
+ if (existing !== null && (existing.payerAddress ?? null) !== (ctx.payer?.address ?? null)) {
48
+ const started = existing.payerAddress ?? "the wallet this NMTS key derives";
49
+ throw new UploadError({
50
+ phase: "reserve",
51
+ message: `This upload was started with ${started} paying, and this run would pay from ${ctx.payer?.address ?? "the wallet this NMTS key derives"}.`,
52
+ paid: existing.registerTxDigest !== undefined,
53
+ nextStep: "Nothing was sent. Run it again with the wallet that started it, or clear the unfinished " +
54
+ "upload records to start over — the storage the first wallet bought stays that wallet's.",
55
+ });
56
+ }
44
57
  if (existing !== null && (existing.partIndex !== input.part.index || existing.partTotal !== input.part.total)) {
45
58
  throw new UploadError({
46
59
  phase: "reserve",
@@ -97,6 +110,7 @@ async function buyAndPushPartWithWallet(ctx, input) {
97
110
  contentHashCt: input.entry.contentHashCt,
98
111
  name: input.entry.name,
99
112
  parentId: input.entry.parentId,
113
+ ...(ctx.payer === undefined ? {} : { payerAddress: ctx.payer.address }),
100
114
  };
101
115
  // ⛔ BEFORE THE SIGNATURE. See the module header.
102
116
  await writeReservation(key, record, sealed);
@@ -0,0 +1,120 @@
1
+ import type { SignExtension } from "./extend-plan.ts";
2
+ import { type KeepTryingOptions } from "./net-retry.ts";
3
+ import type { SignBlobCertify, SignBlobRegister, SignStorageOp } from "./wallet-sign-seams.ts";
4
+ /** What a wallet answers once it has signed: the bytes it signed, and the signature over them. */
5
+ export interface SignedTransaction {
6
+ /** Base64 — what a browser wallet answers — or the raw bytes. */
7
+ bytes: Uint8Array | string;
8
+ signature: string;
9
+ }
10
+ /**
11
+ * The wallet that pays, from outside this tool.
12
+ *
13
+ * ⚠ THE SHAPE IS THE WALLET STANDARD'S, so a page hands over what `useSignTransaction()` gives it
14
+ * and a server hands over whatever signs for the person whose storage this is.
15
+ */
16
+ export interface ExternalPayer {
17
+ /**
18
+ * The address that pays: the sender of every transaction below, and the address whose balances
19
+ * the price was measured against.
20
+ */
21
+ address: string;
22
+ /** Asked once per transaction. `chain` is `sui:mainnet` or `sui:testnet`. */
23
+ signTransaction(input: {
24
+ bytes: Uint8Array;
25
+ chain: string;
26
+ }): Promise<SignedTransaction>;
27
+ }
28
+ /** What the chain says about one submitted transaction. */
29
+ export interface SubmittedTransaction {
30
+ digest: string;
31
+ effects?: unknown;
32
+ objectChanges?: unknown;
33
+ }
34
+ /**
35
+ * Just the three calls a submitted transaction needs.
36
+ *
37
+ * ⚠ NARROW ON PURPOSE: a test hands in a client that answers from a table, and every real client
38
+ * fits it. Asking the node the plain question is also why the wallet is only ever asked to SIGN —
39
+ * a wallet's own "sign and execute" would answer a digest and leave the judging to nobody.
40
+ */
41
+ export interface SubmitClient {
42
+ executeTransactionBlock(input: {
43
+ transactionBlock: Uint8Array;
44
+ signature: string | string[];
45
+ options: {
46
+ showEffects: true;
47
+ showObjectChanges: true;
48
+ };
49
+ }): Promise<SubmittedTransaction>;
50
+ getTransactionBlock(input: {
51
+ digest: string;
52
+ options: {
53
+ showEffects: true;
54
+ showObjectChanges: true;
55
+ };
56
+ }): Promise<SubmittedTransaction>;
57
+ waitForTransaction(input: {
58
+ digest: string;
59
+ }): Promise<unknown>;
60
+ }
61
+ /** What a caller is told when one of these transactions does not go through. */
62
+ export interface ExternalRefusals {
63
+ /** What is true when the WALLET said no. Nothing was signed, by definition. */
64
+ unsigned: string;
65
+ /** What the chain refused, named as a sentence, and what is true once it has. */
66
+ refused: {
67
+ what: string;
68
+ nextStep: string;
69
+ };
70
+ }
71
+ /**
72
+ * One transaction, from bytes to a judged result: ask the wallet, submit it once, read the effects.
73
+ *
74
+ * ⛔ THE ONLY THING THAT CAN THROW BEFORE A SIGNATURE EXISTS IS THE WALLET SAYING NO, and it is
75
+ * named `WALLET_REFUSED` rather than passed on as whatever the wallet threw: a person who
76
+ * declined is not a broken wallet, and a caller that cannot tell them apart shows the wrong
77
+ * sentence to somebody who did exactly what they meant to.
78
+ */
79
+ export declare function signAndSubmit(client: SubmitClient, payer: ExternalPayer, input: {
80
+ network: string;
81
+ bytes: Uint8Array;
82
+ refusals: ExternalRefusals;
83
+ /**
84
+ * How long a dropped line is waited out, and how the waiting is done.
85
+ *
86
+ * ⚠ A SEAM, NOT AN OPTION, and `retryable` is not part of it: what may be repeated is decided
87
+ * here. `sleep`, `now` and `random` are injected so a test runs a flapping link in
88
+ * milliseconds rather than in minutes, and `onWait` is how a caller says it is waiting.
89
+ */
90
+ retry?: Omit<KeepTryingOptions, "retryable"> | undefined;
91
+ }): Promise<SubmittedTransaction>;
92
+ /**
93
+ * The two halves of a wallet-paid upload, signed by a wallet outside this tool: registering one
94
+ * part's blob (which buys the storage or binds a held resource, and pays the relay's tip) and
95
+ * certifying it (gas only).
96
+ *
97
+ * ⛔ THE BUILDERS ARE `upload-wallet-chain.ts`'s OWN — the same ones the measured fee came from and
98
+ * the same ones the keypair signers use. What is registered, bought and tipped is therefore the
99
+ * same transaction whichever wallet signs it.
100
+ */
101
+ export declare function externalBlobSigners(payer: ExternalPayer): {
102
+ register: SignBlobRegister;
103
+ certify: SignBlobCertify;
104
+ };
105
+ /**
106
+ * Extending every blob under one file by `epochs`, in ONE transaction signed by a wallet outside
107
+ * this tool. The ids are de-duplicated: naming a blob twice pays for the same epochs twice.
108
+ *
109
+ * ⚠ The transaction is the shape `extend-chain.ts` measured the fee of — sender, de-duplicated ids,
110
+ * one fragment per blob — so what is approved is what was priced.
111
+ */
112
+ export declare function externalExtendSigner(payer: ExternalPayer): SignExtension;
113
+ /**
114
+ * Cutting, joining or handing over a storage resource, signed by a wallet outside this tool.
115
+ *
116
+ * ⛔ THE RESOURCE MUST BE THAT WALLET'S. The review reads the resources at the address it was given
117
+ * and this signs as the same address, so a resource held somewhere else is refused by the chain
118
+ * rather than half-done here.
119
+ */
120
+ export declare function externalStorageOpSigner(payer: ExternalPayer): SignStorageOp;
@@ -0,0 +1,221 @@
1
+ // Paying with a wallet this tool holds no key to: the caller signs, this file submits and judges.
2
+ //
3
+ // ⛔ WHY IT IS NOT IN `wallet-sign.ts`. That file is the one place a key is derived from the NMTS
4
+ // key, and every signature in it is made by a keypair it builds itself. Here the key is somebody
5
+ // else's — a browser extension, a hardware wallet, a remote signer — and nothing below ever
6
+ // holds one. The TRANSACTIONS ARE THE SAME BUILDERS those signers use, so a wallet-paid upload
7
+ // buys exactly the same thing whoever signs it; what differs is who is asked.
8
+ //
9
+ // ⛔ THE NMTS KEY ARRIVES HERE AND IS NOT READ. The seams carry `code` and `wallet` because the
10
+ // keypair signers need them; every function below names only the fields it uses, so a reader can
11
+ // see that the account's key plays no part in a transaction somebody else's wallet signs.
12
+ //
13
+ // ⛔ THE SENDER IS THE PAYER'S ADDRESS, AND IT IS THE ADDRESS THE PRICE WAS MEASURED AGAINST. An
14
+ // upload and an extension take `payer` before they read a balance (`upload-wallet-put.ts`,
15
+ // `storage-control/extend.ts`), so the quote, both balances, the measured fee and the sentence
16
+ // that says where to send coins all name this wallet. A signer used without that payer would
17
+ // price one wallet and sign with another — which is why neither is reachable without the other.
18
+ //
19
+ // ⛔ ONE SIGNATURE IS SUBMITTED ONCE, HOWEVER OFTEN THE LINE DROPS. A transaction's digest is a hash
20
+ // of its bytes, so the same bytes are the same transaction: a submission whose reply was lost is
21
+ // looked up by that digest before anything is sent again. Re-signing instead would pay twice for
22
+ // a registration and be refused as "already certified" for a certification.
23
+ //
24
+ // ⛔ A DIGEST IS NOT A SUCCESS. A transaction that executed and FAILED has one, and its fee is
25
+ // spent; the effects are read and a failure is said as one, exactly as the keypair signers do.
26
+ //
27
+ // ⛔ EVERY TRANSACTION IS ONE CALL TO THE CALLER'S FUNCTION. Nothing here batches signatures,
28
+ // approves one silently or keeps a record of what was spent: a wallet outside this process
29
+ // decides each time, and a part of a file is a signature of its own.
30
+ //
31
+ // ⚠ WHAT IS SUBMITTED IS WHAT THE WALLET ANSWERED WITH. The wallet standard has a wallet hand back
32
+ // the bytes it signed, and some wallets adjust a transaction before signing one (a sponsor, a gas
33
+ // station); the signature is over those bytes, so those are the bytes that go to the chain. The
34
+ // effects read afterwards are what judge the result.
35
+ import { Transaction, TransactionDataBuilder } from "@mysten/sui/transactions";
36
+ import { fromBase64 } from "@mysten/sui/utils";
37
+ import { NmtsError } from "./errors.js";
38
+ import { walrusClient } from "./extend-chain.js";
39
+ import { isRecord } from "./guards.js";
40
+ import { isTransient, keepTrying } from "./net-retry.js";
41
+ import { storageOpTransaction } from "./storage-control-chain.js";
42
+ import { certifyTransaction, createdBlob, payingClient, registerTransaction } from "./upload-wallet-chain.js";
43
+ function why(error) {
44
+ return error instanceof Error ? error.message : String(error);
45
+ }
46
+ /** What a refused execution said, or null when the effects say it went through. */
47
+ function refusedBecause(result) {
48
+ const status = isRecord(result.effects) ? result.effects["status"] : undefined;
49
+ if (!isRecord(status) || status["status"] !== "failure")
50
+ return null;
51
+ const reason = status["error"];
52
+ return typeof reason === "string" ? reason : "no reason was given";
53
+ }
54
+ /** `sui:mainnet` or `sui:testnet` — what a wallet is told the transaction is for. */
55
+ function chainOf(network) {
56
+ return `sui:${network === "mainnet" ? "mainnet" : "testnet"}`;
57
+ }
58
+ /**
59
+ * One transaction, from bytes to a judged result: ask the wallet, submit it once, read the effects.
60
+ *
61
+ * ⛔ THE ONLY THING THAT CAN THROW BEFORE A SIGNATURE EXISTS IS THE WALLET SAYING NO, and it is
62
+ * named `WALLET_REFUSED` rather than passed on as whatever the wallet threw: a person who
63
+ * declined is not a broken wallet, and a caller that cannot tell them apart shows the wrong
64
+ * sentence to somebody who did exactly what they meant to.
65
+ */
66
+ export async function signAndSubmit(client, payer, input) {
67
+ let answered;
68
+ try {
69
+ answered = await payer.signTransaction({ bytes: input.bytes, chain: chainOf(input.network) });
70
+ }
71
+ catch (error) {
72
+ throw new NmtsError(`WALLET_REFUSED: the wallet did not sign — ${why(error)}`, {
73
+ exitCode: 4,
74
+ nextStep: `${input.refusals.unsigned} A wallet refuses when somebody declines it, when it is on another network, or when it cannot sign this shape at all.`,
75
+ });
76
+ }
77
+ const signed = typeof answered.bytes === "string" ? fromBase64(answered.bytes) : answered.bytes;
78
+ const digest = TransactionDataBuilder.getDigestFromBytes(signed);
79
+ const options = { showEffects: true, showObjectChanges: true };
80
+ let sent = false;
81
+ const result = await keepTrying(async () => {
82
+ if (sent) {
83
+ // The attempt before this one may have reached the chain and lost only its reply. An
84
+ // unknown digest and a node that did not answer look the same here, and both mean "send
85
+ // the same bytes again" — which is safe precisely because they are the same bytes.
86
+ const seen = await client.getTransactionBlock({ digest, options }).catch(() => null);
87
+ if (seen !== null)
88
+ return seen;
89
+ }
90
+ sent = true;
91
+ return client.executeTransactionBlock({ transactionBlock: signed, signature: answered.signature, options });
92
+ }, { ...input.retry, retryable: isTransient });
93
+ // ⛔ SUCCESS IS ALREADY DECIDED BY THE EFFECTS BELOW. This wait is for what happens NEXT — the
94
+ // relay being told the digest, the blob object being read back — because a node that has not
95
+ // indexed the transaction yet answers those as if nothing had happened. A wait that times out
96
+ // changes nothing about what was signed, so it is not a failure of this transaction.
97
+ await client.waitForTransaction({ digest: result.digest }).catch(() => undefined);
98
+ const refused = refusedBecause(result);
99
+ if (refused !== null) {
100
+ throw new NmtsError(`${input.refusals.refused.what}: ${refused}.`, {
101
+ exitCode: 1,
102
+ nextStep: input.refusals.refused.nextStep,
103
+ });
104
+ }
105
+ return result;
106
+ }
107
+ /**
108
+ * The two halves of a wallet-paid upload, signed by a wallet outside this tool: registering one
109
+ * part's blob (which buys the storage or binds a held resource, and pays the relay's tip) and
110
+ * certifying it (gas only).
111
+ *
112
+ * ⛔ THE BUILDERS ARE `upload-wallet-chain.ts`'s OWN — the same ones the measured fee came from and
113
+ * the same ones the keypair signers use. What is registered, bought and tipped is therefore the
114
+ * same transaction whichever wallet signs it.
115
+ */
116
+ export function externalBlobSigners(payer) {
117
+ return {
118
+ register: async ({ network, relayUrl, epochs, storage, part }) => {
119
+ const client = payingClient(network, relayUrl);
120
+ const tx = await registerTransaction(client, network, { epochs, storage, part, sender: payer.address });
121
+ const result = await signAndSubmit(client, payer, {
122
+ network,
123
+ bytes: await tx.build({ client }),
124
+ refusals: {
125
+ unsigned: "No storage was bought, nothing was sent, and the tip was not paid.",
126
+ refused: {
127
+ what: "The storage network refused the registration",
128
+ nextStep: `Nothing is stored and no storage was bought. The transaction fee was spent. The usual ` +
129
+ `causes are too little WAL or SUI in the paying wallet — ${payer.address} — or a held ` +
130
+ `storage resource too small for this part once encoded.`,
131
+ },
132
+ },
133
+ });
134
+ // The blob object is found by its type in what the transaction created, not by position.
135
+ return { digest: result.digest, ...(await createdBlob(client, result.objectChanges)) };
136
+ },
137
+ certify: async ({ network, relayUrl, blobId, blobObjectId, certificate }) => {
138
+ const client = payingClient(network, relayUrl);
139
+ const tx = certifyTransaction(client, { blobId, blobObjectId, certificate });
140
+ tx.setSender(payer.address);
141
+ const result = await signAndSubmit(client, payer, {
142
+ network,
143
+ bytes: await tx.build({ client }),
144
+ refusals: {
145
+ unsigned: "The storage is bought and the bytes are on the network; only the certification is unsigned. " +
146
+ "Running the same upload again asks for that one signature and buys nothing.",
147
+ refused: {
148
+ what: "The storage network refused the certification",
149
+ nextStep: `The storage is bought and the bytes are on the network; only the certification failed, ` +
150
+ `and its fee was spent. Running the same upload again certifies again, which costs gas ` +
151
+ `and nothing else.`,
152
+ },
153
+ },
154
+ });
155
+ return result.digest;
156
+ },
157
+ };
158
+ }
159
+ /**
160
+ * Extending every blob under one file by `epochs`, in ONE transaction signed by a wallet outside
161
+ * this tool. The ids are de-duplicated: naming a blob twice pays for the same epochs twice.
162
+ *
163
+ * ⚠ The transaction is the shape `extend-chain.ts` measured the fee of — sender, de-duplicated ids,
164
+ * one fragment per blob — so what is approved is what was priced.
165
+ */
166
+ export function externalExtendSigner(payer) {
167
+ return async ({ network, objectIds, epochs }) => {
168
+ const unique = [...new Set(objectIds)];
169
+ if (unique.length === 0) {
170
+ throw new NmtsError("There is nothing on this file that can be extended.", { exitCode: 4 });
171
+ }
172
+ if (!Number.isSafeInteger(epochs) || epochs <= 0) {
173
+ throw new NmtsError("An extension must be a positive whole number of epochs.", { exitCode: 2 });
174
+ }
175
+ const client = walrusClient(network);
176
+ const tx = new Transaction();
177
+ // The sender goes first: the fragments below pick this address's WAL when they resolve.
178
+ tx.setSender(payer.address);
179
+ for (const blobObjectId of unique)
180
+ tx.add(client.walrus.extendBlob({ blobObjectId, epochs }));
181
+ const result = await signAndSubmit(client, payer, {
182
+ network,
183
+ bytes: await tx.build({ client }),
184
+ refusals: {
185
+ unsigned: "The storage was NOT extended and the file still ends when it did. Nothing was spent.",
186
+ refused: {
187
+ what: "The storage network refused the extension",
188
+ nextStep: `The storage was NOT extended and the file still ends when it did. The transaction fee was ` +
189
+ `spent. The usual causes are too little WAL or SUI in the paying wallet — ${payer.address} — ` +
190
+ `or a length the network will no longer sell.`,
191
+ },
192
+ },
193
+ });
194
+ return result.digest;
195
+ };
196
+ }
197
+ /**
198
+ * Cutting, joining or handing over a storage resource, signed by a wallet outside this tool.
199
+ *
200
+ * ⛔ THE RESOURCE MUST BE THAT WALLET'S. The review reads the resources at the address it was given
201
+ * and this signs as the same address, so a resource held somewhere else is refused by the chain
202
+ * rather than half-done here.
203
+ */
204
+ export function externalStorageOpSigner(payer) {
205
+ return async ({ network, shape, walrusPackageId }) => {
206
+ const client = walrusClient(network);
207
+ const tx = storageOpTransaction(shape, { walrusPackageId, sender: payer.address });
208
+ const result = await signAndSubmit(client, payer, {
209
+ network,
210
+ bytes: await tx.build({ client }),
211
+ refusals: {
212
+ unsigned: "Nothing changed on the resource and nothing was spent.",
213
+ refused: {
214
+ what: "The chain refused it",
215
+ nextStep: "Nothing changed on the resource. The transaction fee was spent.",
216
+ },
217
+ },
218
+ });
219
+ return result.digest;
220
+ };
221
+ }
@@ -1,4 +1,6 @@
1
- // ⛔ THE ONE FILE IN THIS TOOL THAT SIGNS. Everything it can do moves real assets and cannot be
1
+ // ⛔ THE ONE FILE IN THIS TOOL THAT HOLDS A KEY AND SIGNS WITH IT. (A wallet outside this tool signs
2
+ // through `wallet-sign-external.ts`, which builds the same transactions and holds no key at all.)
3
+ // Everything it can do moves real assets and cannot be
2
4
  // reversed by anybody, including NMTS. It signs FIVE SHAPES and no others: extending a file's
3
5
  // storage (`signExtension`), sending SUI or WAL to an address (`signTransfer`), swapping one for
4
6
  // the other on a venue (`signSwap`), and the two halves of a wallet-paid upload — registering one
@@ -17,7 +17,8 @@ import { epochClock } from "./expiry.js";
17
17
  import { epochStartedMs as readEpochStart } from "./shared/lib/extend/epochs.js";
18
18
  import { NmtsError } from "./errors.js";
19
19
  import { countingFetch } from "./progress.js";
20
- import { relayHost } from "./walrus.js";
20
+ import { reachFetch } from "./reach.js";
21
+ import { relayHost, storageNodesThrough } from "./walrus.js";
21
22
  import { suiRpcTransport } from "./sui-rpc.js";
22
23
  /**
23
24
  * How long the relay gets for one blob PUT, sized to the body.
@@ -50,6 +51,7 @@ function extend(network, relayUrl, bodyBytes, onSent) {
50
51
  transport: suiRpcTransport(network),
51
52
  });
52
53
  return base.$extend(walrus({
54
+ ...storageNodesThrough(),
53
55
  uploadRelay: {
54
56
  host: relayUrl,
55
57
  sendTip: { max: TIP_CEILING_UNUSED_MIST },
@@ -58,7 +60,10 @@ function extend(network, relayUrl, bodyBytes, onSent) {
58
60
  // PUT is the one step of an upload that takes real time — a person watching a large
59
61
  // file with no feedback cannot tell a slow upload from a hung one, and neither can an
60
62
  // agent deciding whether to give up.
61
- ...(onSent ? { fetch: countingFetch(onSent) } : {}),
63
+ //
64
+ // ⛔ AND EITHER WAY IT IS THE CALLER'S `fetch`: the counting wrapper goes through it too,
65
+ // so the request that carries the file cannot be the one that misses a proxy.
66
+ fetch: onSent ? countingFetch(onSent) : reachFetch,
62
67
  },
63
68
  }));
64
69
  }
@@ -131,7 +136,7 @@ export async function readCurrentEpoch(network) {
131
136
  const base = new SuiJsonRpcClient({
132
137
  network: network === "mainnet" ? "mainnet" : "testnet",
133
138
  transport: suiRpcTransport(network),
134
- }).$extend(walrus({}));
139
+ }).$extend(walrus(storageNodesThrough()));
135
140
  // The epoch lives on the COMMITTEE, not beside it: the system state describes capacity and
136
141
  // the deny lists as well, and only the committee is stamped with which epoch it serves.
137
142
  const state = await base.walrus.systemState();
@@ -162,7 +167,7 @@ export async function readEpochWindow(network) {
162
167
  const base = new SuiJsonRpcClient({
163
168
  network: network === "mainnet" ? "mainnet" : "testnet",
164
169
  transport: suiRpcTransport(network),
165
- }).$extend(walrus({}));
170
+ }).$extend(walrus(storageNodesThrough()));
166
171
  const [system, staking] = await Promise.all([base.walrus.systemState(), base.walrus.stakingState()]);
167
172
  // Both numbers can arrive as strings — Sui reports 64-bit values that way — so they are
168
173
  // converted here and the constructor below refuses whatever did not survive it.
package/dist/walrus.d.ts CHANGED
@@ -29,19 +29,46 @@ export declare const SUI_RPC_HOSTS: Readonly<Record<string, readonly string[]>>;
29
29
  /** How long one host gets before the next is tried. A read that stalls is a read that failed. */
30
30
  export declare const READ_TIMEOUT_MS = 60000;
31
31
  export { AGGREGATOR_ENV_VAR, RELAY_ENV_VAR, SUI_RPC_ENV_VAR } from "./env-vars.ts";
32
- /** The relay this run writes through: the environment's if it named one, else the network's. */
32
+ /**
33
+ * The relay this run writes through: the caller's if it named one, then the environment's, then
34
+ * the network's.
35
+ *
36
+ * ⛔ THE CALLER COMES FIRST AND IS READ ON EVERY HOST. A library's caller has no environment to
37
+ * write, and until this order existed the `relay` option was answered by the browser host alone
38
+ * — so a program on a server named a relay and its bytes went to the public one, silently.
39
+ */
33
40
  export declare function relayHost(network: string): string;
34
41
  /**
35
- * Every Sui JSON-RPC node this run may ask, in order.
42
+ * Every Sui JSON-RPC node this run may ask, in order: the caller's list if it named one, then the
43
+ * environment's, then the network's.
36
44
  *
37
- * ⛔ Naming one in the environment REPLACES the list rather than adding to it — the same rule the
38
- * aggregator override follows, and for the same reason: somebody who names a node is saying
39
- * *that one*, and quietly reaching a public mirror instead would send their traffic somewhere
40
- * they did not choose.
45
+ * ⛔ Naming nodes REPLACES the list rather than adding to it — the same rule the aggregator
46
+ * override follows, and for the same reason: somebody who names a node is saying *those*, and
47
+ * quietly reaching a public mirror instead would send their traffic somewhere they did not
48
+ * choose.
49
+ *
50
+ * ⚠ THE CALLER MAY NAME SEVERAL AND A VARIABLE MAY NAME ONE. The failover below is the same
51
+ * either way; a single name is a list of one.
41
52
  */
42
53
  export declare function suiRpcHosts(network: string): readonly string[];
43
54
  /** The node whose address gets RECORDED — the first one, since that is the one normally asked. */
44
55
  export declare function suiRpcHost(network: string): string;
56
+ /**
57
+ * What a storage-network client talks to the storage nodes through, spread into its options.
58
+ *
59
+ * ⚠ THIS TOOL DOES NOT NORMALLY REACH A STORAGE NODE — it writes through an upload relay and reads
60
+ * through an aggregator. The option is filled anyway, because the one path that fell back to a
61
+ * node directly would be a request going round whatever the caller asked every request to go
62
+ * through, and the whole worth of that option is that there is no exception to it.
63
+ *
64
+ * ⛔ HERE RATHER THAN IN EACH CLIENT. Five of them are built in this package; five copies of the
65
+ * same line is five places for the sixth to be forgotten.
66
+ */
67
+ export declare function storageNodesThrough(): {
68
+ storageNodeClientOptions: {
69
+ fetch: typeof fetch;
70
+ };
71
+ };
45
72
  export interface ReadOptions {
46
73
  /** Override the host list — for a development stack, or an aggregator somebody runs themselves. */
47
74
  hosts?: readonly string[];
package/dist/walrus.js CHANGED
@@ -13,6 +13,7 @@
13
13
  import { AGGREGATOR_ENV_VAR, RELAY_ENV_VAR, SUI_RPC_ENV_VAR } from "./env-vars.js";
14
14
  import { NmtsError } from "./errors.js";
15
15
  import { host as runtime } from "./host.js";
16
+ import { reach, reachFetch } from "./reach.js";
16
17
  /** Curated Walrus aggregator (read) endpoints per network, preference order. */
17
18
  export const AGGREGATOR_HOSTS = {
18
19
  testnet: ["https://aggregator.walrus-testnet.walrus.space"],
@@ -55,9 +56,16 @@ export const READ_TIMEOUT_MS = 60_000;
55
56
  // Re-exported so every caller still finds them here; the names themselves live in a module with no
56
57
  // imports, because `nmts --help` prints them (`env-vars.ts`).
57
58
  export { AGGREGATOR_ENV_VAR, RELAY_ENV_VAR, SUI_RPC_ENV_VAR } from "./env-vars.js";
58
- /** The relay this run writes through: the environment's if it named one, else the network's. */
59
+ /**
60
+ * The relay this run writes through: the caller's if it named one, then the environment's, then
61
+ * the network's.
62
+ *
63
+ * ⛔ THE CALLER COMES FIRST AND IS READ ON EVERY HOST. A library's caller has no environment to
64
+ * write, and until this order existed the `relay` option was answered by the browser host alone
65
+ * — so a program on a server named a relay and its bytes went to the public one, silently.
66
+ */
59
67
  export function relayHost(network) {
60
- const named = runtime().env(RELAY_ENV_VAR)?.trim();
68
+ const named = reach().relay?.trim() || runtime().env(RELAY_ENV_VAR)?.trim();
61
69
  if (named)
62
70
  return named;
63
71
  const known = RELAY_HOSTS[network]?.[0];
@@ -69,14 +77,21 @@ export function relayHost(network) {
69
77
  return known;
70
78
  }
71
79
  /**
72
- * Every Sui JSON-RPC node this run may ask, in order.
80
+ * Every Sui JSON-RPC node this run may ask, in order: the caller's list if it named one, then the
81
+ * environment's, then the network's.
73
82
  *
74
- * ⛔ Naming one in the environment REPLACES the list rather than adding to it — the same rule the
75
- * aggregator override follows, and for the same reason: somebody who names a node is saying
76
- * *that one*, and quietly reaching a public mirror instead would send their traffic somewhere
77
- * they did not choose.
83
+ * ⛔ Naming nodes REPLACES the list rather than adding to it — the same rule the aggregator
84
+ * override follows, and for the same reason: somebody who names a node is saying *those*, and
85
+ * quietly reaching a public mirror instead would send their traffic somewhere they did not
86
+ * choose.
87
+ *
88
+ * ⚠ THE CALLER MAY NAME SEVERAL AND A VARIABLE MAY NAME ONE. The failover below is the same
89
+ * either way; a single name is a list of one.
78
90
  */
79
91
  export function suiRpcHosts(network) {
92
+ const asked = reach().suiRpc?.map((h) => h.trim()).filter((h) => h !== "");
93
+ if (asked !== undefined && asked.length > 0)
94
+ return asked;
80
95
  const named = runtime().env(SUI_RPC_ENV_VAR)?.trim();
81
96
  if (named)
82
97
  return [named];
@@ -92,6 +107,20 @@ export function suiRpcHosts(network) {
92
107
  export function suiRpcHost(network) {
93
108
  return suiRpcHosts(network)[0] ?? "";
94
109
  }
110
+ /**
111
+ * What a storage-network client talks to the storage nodes through, spread into its options.
112
+ *
113
+ * ⚠ THIS TOOL DOES NOT NORMALLY REACH A STORAGE NODE — it writes through an upload relay and reads
114
+ * through an aggregator. The option is filled anyway, because the one path that fell back to a
115
+ * node directly would be a request going round whatever the caller asked every request to go
116
+ * through, and the whole worth of that option is that there is no exception to it.
117
+ *
118
+ * ⛔ HERE RATHER THAN IN EACH CLIENT. Five of them are built in this package; five copies of the
119
+ * same line is five places for the sixth to be forgotten.
120
+ */
121
+ export function storageNodesThrough() {
122
+ return { storageNodeClientOptions: { fetch: reachFetch } };
123
+ }
95
124
  function fromEnvironment() {
96
125
  const raw = runtime().env(AGGREGATOR_ENV_VAR);
97
126
  if (raw === undefined)
@@ -99,9 +128,20 @@ function fromEnvironment() {
99
128
  const hosts = raw.split(",").map((h) => h.trim()).filter((h) => h !== "");
100
129
  return hosts.length > 0 ? hosts : null;
101
130
  }
131
+ /**
132
+ * Which aggregators this read may ask, in order: the ones this call named, then the ones the
133
+ * caller named for the client, then the environment's, then the network's.
134
+ *
135
+ * ⚠ THE CLIENT'S CHOICE IS NEW HERE. A caller that named aggregators used to be honoured only on
136
+ * the reads that carry a host list down as an argument; the rest of the package quietly went to
137
+ * the public ones, which is the same defect `relay` had.
138
+ */
102
139
  function hostsFor(network, options) {
103
140
  if (options.hosts !== undefined && options.hosts.length > 0)
104
141
  return options.hosts;
142
+ const asked = reach().aggregators;
143
+ if (asked !== undefined && asked.length > 0)
144
+ return asked;
105
145
  const chosen = fromEnvironment();
106
146
  if (chosen !== null)
107
147
  return chosen;
@@ -129,7 +169,7 @@ async function readFrom(network, pathOf, what, options) {
129
169
  const timer = AbortSignal.timeout(options.timeoutMs ?? READ_TIMEOUT_MS);
130
170
  const signal = options.signal === undefined ? timer : AbortSignal.any([timer, options.signal]);
131
171
  try {
132
- const response = await fetch(url, { signal, redirect: "follow", ...headersFor(options) });
172
+ const response = await reachFetch(url, { signal, redirect: "follow", ...headersFor(options) });
133
173
  if (!response.ok) {
134
174
  tried.push(`${host} → ${response.status}`);
135
175
  continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@needmoretruth/nmts-cli",
3
- "version": "0.41.0",
3
+ "version": "0.43.0",
4
4
  "description": "Command-line and MCP access to NMTS (NeedMoreTruthStorage, https://nmts.me): open-source, end-to-end encrypted storage on the Walrus network. No fee to NMTS; you pay the network from your own wallet. For people and for their agents.",
5
5
  "license": "Apache-2.0",
6
6
  "publishConfig": {
@@ -109,6 +109,10 @@
109
109
  "types": "./dist/wallet-sign.d.ts",
110
110
  "default": "./dist/wallet-sign.js"
111
111
  },
112
+ "./wallet-sign-external": {
113
+ "types": "./dist/wallet-sign-external.d.ts",
114
+ "default": "./dist/wallet-sign-external.js"
115
+ },
112
116
  "./vendor/nmts-crypto/*": "./vendor/nmts-crypto/*",
113
117
  "./package.json": "./package.json"
114
118
  },