@needmoretruth/nmts-cli 0.54.2 → 0.55.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.ko.md +1 -1
  3. package/README.md +1 -1
  4. package/dist/artifact-about.d.ts +1 -1
  5. package/dist/commands/push.js +1 -1
  6. package/dist/commands/put-wallet.js +1 -1
  7. package/dist/commands/put.js +1 -1
  8. package/dist/manifest.js +3 -0
  9. package/dist/node-read.d.ts +2 -0
  10. package/dist/node-read.js +24 -0
  11. package/dist/product.d.ts +1 -1
  12. package/dist/product.js +1 -1
  13. package/dist/read-race.d.ts +35 -0
  14. package/dist/read-race.js +91 -0
  15. package/dist/road-hosts.generated.d.ts +4 -0
  16. package/dist/road-hosts.generated.js +284 -0
  17. package/dist/shared/lib/upload/wallet-storage-estimate.d.ts +16 -0
  18. package/dist/shared/lib/upload/wallet-storage-estimate.js +44 -0
  19. package/dist/shared/lib/wallet/graphql-history.d.ts +7 -2
  20. package/dist/shared/lib/wallet/graphql-history.js +7 -2
  21. package/dist/shared/lib/walrus/credit-tip.d.ts +24 -0
  22. package/dist/shared/lib/walrus/credit-tip.js +61 -0
  23. package/dist/shared/lib/walrus/node-certificate.d.ts +18 -0
  24. package/dist/shared/lib/walrus/node-certificate.js +77 -0
  25. package/dist/shared/lib/walrus/node-quorum.d.ts +17 -0
  26. package/dist/shared/lib/walrus/node-quorum.js +103 -0
  27. package/dist/shared/lib/walrus/tip-config.d.ts +33 -0
  28. package/dist/shared/lib/walrus/tip-config.js +68 -0
  29. package/dist/upload-road.d.ts +26 -4
  30. package/dist/upload-road.js +79 -17
  31. package/dist/upload-steps.js +1 -0
  32. package/dist/upload-wallet-chain.d.ts +1 -1
  33. package/dist/upload-wallet-chain.js +11 -4
  34. package/dist/upload-wallet.js +1 -0
  35. package/dist/upload-wire.d.ts +5 -0
  36. package/dist/upload.js +3 -3
  37. package/dist/walrus-write.js +68 -3
  38. package/dist/walrus.d.ts +20 -4
  39. package/dist/walrus.js +115 -36
  40. package/package.json +1 -1
  41. package/server.json +2 -2
@@ -8,9 +8,14 @@ import type { DeeperHistory } from "./address-history.ts";
8
8
  * failure there left every wallet's older history unread. 01NODE Funding SRL (Bucharest, Romania,
9
9
  * its own network) runs a public mainnet GraphQL at `sui.01.ro`; measured that day from this machine:
10
10
  * the same query and the same rows as Mysten's (the treasury's oldest transaction, 2026-08-02),
11
- * checkpoints back to 2023, `access-control-allow-origin: *`, 1.3 s. Triton One's `rpcpool` answered
12
- * too; it is not used because its company is not one the Privacy Policy names. Testnet keeps one
11
+ * checkpoints back to 2023, `access-control-allow-origin: *`, 1.3 s. Testnet keeps one
13
12
  * operator: development has no second public GraphQL and no one's activity depends on it.
13
+ * ⭐ NO THIRD (2026-11-10, D51). Triton One Limited's `mainnet.sui.rpcpool.com/graphql` answered this
14
+ * file's exact query from real Chromium on an `https://nmts.me` page, with CORS and the same first
15
+ * rows, but Triton's documentation calls that endpoint "for development and evaluation only, not
16
+ * production traffic" and strictly rate limited: the day Mysten and 01NODE fail it would carry
17
+ * every wallet and refuse them. Suiscan, SuiVision, PublicNode, Ankr, Tatum, Pocket, BlockPI and
18
+ * Nodeinfra did not answer it (no service, no CORS, 403, an error body, 500, 404, nothing in 15 s).
14
19
  * Still the second tier and never the only one: when every service fails the answer is
15
20
  * `complete: false`, never "nothing there".
16
21
  */
@@ -15,9 +15,14 @@ import { GrpcTypes, parseGrpcTransactionResponse } from "@mysten/sui/grpc";
15
15
  * failure there left every wallet's older history unread. 01NODE Funding SRL (Bucharest, Romania,
16
16
  * its own network) runs a public mainnet GraphQL at `sui.01.ro`; measured that day from this machine:
17
17
  * the same query and the same rows as Mysten's (the treasury's oldest transaction, 2026-08-02),
18
- * checkpoints back to 2023, `access-control-allow-origin: *`, 1.3 s. Triton One's `rpcpool` answered
19
- * too; it is not used because its company is not one the Privacy Policy names. Testnet keeps one
18
+ * checkpoints back to 2023, `access-control-allow-origin: *`, 1.3 s. Testnet keeps one
20
19
  * operator: development has no second public GraphQL and no one's activity depends on it.
20
+ * ⭐ NO THIRD (2026-11-10, D51). Triton One Limited's `mainnet.sui.rpcpool.com/graphql` answered this
21
+ * file's exact query from real Chromium on an `https://nmts.me` page, with CORS and the same first
22
+ * rows, but Triton's documentation calls that endpoint "for development and evaluation only, not
23
+ * production traffic" and strictly rate limited: the day Mysten and 01NODE fail it would carry
24
+ * every wallet and refuse them. Suiscan, SuiVision, PublicNode, Ankr, Tatum, Pocket, BlockPI and
25
+ * Nodeinfra did not answer it (no service, no CORS, 403, an error body, 500, 404, nothing in 15 s).
21
26
  * Still the second tier and never the only one: when every service fails the answer is
22
27
  * `complete: false`, never "nothing there".
23
28
  */
@@ -0,0 +1,24 @@
1
+ import type { RelayTip } from "./tip-config.ts";
2
+ /** Mysten Labs' relay tip per KiB of encoded size, MIST (base 0). ⚠ MUST match `chain/src/limits.ts::REFERENCE_TIP_PER_KIB_MIST`. */
3
+ export declare const REFERENCE_TIP_PER_KIB_MIST = 40;
4
+ /** How many times Mysten's formula a credit upload may tip. ⚠ MUST match `chain/src/limits.ts::CREDIT_TIP_RATIO`. */
5
+ export declare const CREDIT_TIP_RATIO = 3;
6
+ /** The largest blob the credit rail registers: 2,048 credits of 1 MiB (`chain/src/limits.ts` says why). */
7
+ export declare const LARGEST_CREDIT_BLOB_BYTES: number;
8
+ /** A relay's tip as a line: `baseMist + mulPerKibMist × encoded KiB` (a constant tip has no slope). */
9
+ export interface TipLine {
10
+ baseMist: bigint;
11
+ mulPerKibMist: bigint;
12
+ }
13
+ /** What Mysten's formula charges for a blob of `blobBytes` unencoded bytes, MIST. */
14
+ export declare function referenceTipMist(blobBytes: number): bigint;
15
+ /** True when this tip for a blob of `blobBytes` is one the treasury pays. */
16
+ export declare function creditTipFits(tip: TipLine, blobBytes: number): boolean;
17
+ /**
18
+ * True when the tip fits at every blob size the credit rail registers. Both tips are straight lines in
19
+ * the encoded size, so their ratio only rises or falls between the ends: checking the two ends is
20
+ * checking every size. For a caller that chooses its road before it knows the size.
21
+ */
22
+ export declare function creditTipFitsEverySize(tip: TipLine): boolean;
23
+ /** A tip as a line in the encoded size, or null when the relay's price could not be read. */
24
+ export declare function tipLine(tip: RelayTip): TipLine | null;
@@ -0,0 +1,61 @@
1
+ // Which company relay the treasury may tip on a credit upload (2026-11-10).
2
+ //
3
+ // WHY. Until this day a credit upload went through Mysten Labs' relay or, when it did not answer,
4
+ // straight to the storage nodes: the treasury tipped only Mysten. The owner asked for every company
5
+ // that answers on every road, so that a second closure still leaves a road, and Studio
6
+ // Mirai's relay now carries credit uploads too, after Mysten and before the storage nodes.
7
+ //
8
+ // ⛔ BUT ANOTHER COMPANY NAMES THE PRICE THE TREASURY PAYS. So a relay is a credit road only while its
9
+ // tip for THIS upload is at most `CREDIT_TIP_RATIO` times what Mysten's formula would charge for it;
10
+ // above that the upload goes on to the next road (the storage nodes, no tip). Mysten's formula is
11
+ // pinned, not read live: the relay is needed exactly when Mysten does not answer, and a reference
12
+ // that has to be fetched from the company that is down is no reference.
13
+ //
14
+ // MEASURED 2026-11-10, `GET /v1/tip-config` on mainnet:
15
+ // Mysten Labs {"linear":{"base":0,"encoded_size_mul_per_kib":40}}
16
+ // Studio Mirai {"linear":{"base":3000000,"encoded_size_mul_per_kib":60}}
17
+ // Every blob carries 66,034,000 encoded bytes even when empty (1,000 shards), so Mirai's tip is
18
+ // 2.7 times Mysten's for an empty blob and falls toward 1.5 times as the blob grows: it fits.
19
+ //
20
+ // ⚠ The chain service holds the same rule (`chain/src/limits.ts::referenceTipCeilingMist`) and refuses a
21
+ // tip above it with 403, so a relay the browser picks and the chain refuses is a repricing between
22
+ // the two reads, not a disagreement between two programs.
23
+ import { encodedBlobLength } from "../upload/wallet-storage-estimate.js";
24
+ /** Mysten Labs' relay tip per KiB of encoded size, MIST (base 0). ⚠ MUST match `chain/src/limits.ts::REFERENCE_TIP_PER_KIB_MIST`. */
25
+ export const REFERENCE_TIP_PER_KIB_MIST = 40;
26
+ /** How many times Mysten's formula a credit upload may tip. ⚠ MUST match `chain/src/limits.ts::CREDIT_TIP_RATIO`. */
27
+ export const CREDIT_TIP_RATIO = 3;
28
+ /** The largest blob the credit rail registers: 2,048 credits of 1 MiB (`chain/src/limits.ts` says why). */
29
+ export const LARGEST_CREDIT_BLOB_BYTES = 2 * 1024 * 1024 * 1024;
30
+ function encodedKib(blobBytes) {
31
+ return (BigInt(encodedBlobLength(blobBytes)) + 1023n) / 1024n;
32
+ }
33
+ /** What Mysten's formula charges for a blob of `blobBytes` unencoded bytes, MIST. */
34
+ export function referenceTipMist(blobBytes) {
35
+ return BigInt(REFERENCE_TIP_PER_KIB_MIST) * encodedKib(blobBytes);
36
+ }
37
+ /** True when this tip for a blob of `blobBytes` is one the treasury pays. */
38
+ export function creditTipFits(tip, blobBytes) {
39
+ return tip.baseMist + tip.mulPerKibMist * encodedKib(blobBytes) <= BigInt(CREDIT_TIP_RATIO) * referenceTipMist(blobBytes);
40
+ }
41
+ /**
42
+ * True when the tip fits at every blob size the credit rail registers. Both tips are straight lines in
43
+ * the encoded size, so their ratio only rises or falls between the ends: checking the two ends is
44
+ * checking every size. For a caller that chooses its road before it knows the size.
45
+ */
46
+ export function creditTipFitsEverySize(tip) {
47
+ return creditTipFits(tip, 0) && creditTipFits(tip, LARGEST_CREDIT_BLOB_BYTES);
48
+ }
49
+ /** A tip as a line in the encoded size, or null when the relay's price could not be read. */
50
+ export function tipLine(tip) {
51
+ switch (tip.kind) {
52
+ case "none":
53
+ return { baseMist: 0n, mulPerKibMist: 0n };
54
+ case "const":
55
+ return { baseMist: tip.baseMist, mulPerKibMist: 0n };
56
+ case "linear":
57
+ return { baseMist: tip.baseMist, mulPerKibMist: tip.mulPerKibMist };
58
+ case "unknown":
59
+ return null;
60
+ }
61
+ }
@@ -0,0 +1,18 @@
1
+ import { type WalrusClient } from "@mysten/walrus";
2
+ type CertArgs = Parameters<WalrusClient["certificateFromConfirmations"]>[0];
3
+ type Certificate = Awaited<ReturnType<WalrusClient["certificateFromConfirmations"]>>;
4
+ type SystemState = Awaited<ReturnType<WalrusClient["systemState"]>>;
5
+ type Member = SystemState["committee"]["members"][number];
6
+ /** The chain's quorum (`walrus::bls_aggregate::is_quorum`). */
7
+ export declare const chainQuorum: (weight: number, nShards: number) => boolean;
8
+ /** The message every confirming node signs for this blob in this epoch. */
9
+ export declare function confirmationMessage(epoch: number, blobId: string, deletable: boolean, blobObjectId: string): Uint8Array;
10
+ /**
11
+ * Combine the confirmations whose message and signature hold into a certificate, or throw when their
12
+ * shard weight is short of the chain's quorum. `members` is the BLS committee in signer-index order.
13
+ */
14
+ export declare function certificateByShardWeight(confirmations: CertArgs["confirmations"], members: readonly Pick<Member, "public_key" | "weight">[], nShards: number, expected: Uint8Array): Certificate;
15
+ type Certifier = Pick<WalrusClient, "certificateFromConfirmations" | "systemState">;
16
+ /** Replace the client's node-count certificate with the chain's shard-weight one. */
17
+ export declare function certifyByShardWeight<T extends Certifier>(walrus: T): T;
18
+ export {};
@@ -0,0 +1,77 @@
1
+ // The certificate from node confirmations, by the rule the chain applies (D51, 2026-11-10).
2
+ // ⛔ WHY NOT THE SDK'S. `WalrusClient.certificateFromConfirmations` (1.2.36) refuses unless more than two
3
+ // thirds of the committee's NODES confirmed. The chain counts no nodes: `bls_aggregate::
4
+ // verify_certificate_and_weight` sums the signers' weight (each member's shard count) and asserts
5
+ // `is_quorum`, `3 * weight >= 2 * n_shards + 1`. Members hold uneven shard counts (mainnet and testnet),
6
+ // so a node count waits for confirmations the chain does not need, and on testnet on 2026-11-10 it
7
+ // refused certificates the chain would have taken (63 of 97 nodes confirmed). The writes stop on the
8
+ // same shard rule (node-quorum.ts), so the stop and the certificate cannot disagree.
9
+ // ⛔ WHAT IS CHECKED. Each confirmation must carry the exact message the chain will rebuild (intent,
10
+ // epoch, blob id, persistence) and verify under its member's key; one aggregate check covers the honest
11
+ // case, and only when it fails is each signature checked alone to drop the bad ones.
12
+ import { bls12_381 } from "@noble/curves/bls12-381.js";
13
+ import { bcs } from "@mysten/sui/bcs";
14
+ import { fromBase64 } from "@mysten/sui/utils";
15
+ import { blobIdToInt, NotEnoughBlobConfirmationsError } from "@mysten/walrus";
16
+ /** The chain's quorum (`walrus::bls_aggregate::is_quorum`). */
17
+ export const chainQuorum = (weight, nShards) => 3 * weight >= 2 * nShards + 1;
18
+ const BLOB_CERT_MSG = 1;
19
+ const WALRUS_APP_ID = 3;
20
+ const StorageConfirmation = bcs.struct("ProtocolMessage<StorageConfirmationBody>", {
21
+ intent: bcs.struct("Intent", { type: bcs.u8(), version: bcs.u8(), appId: bcs.u8() }),
22
+ epoch: bcs.u32(),
23
+ messageContents: bcs.struct("StorageConfirmationBody", {
24
+ blobId: bcs.u256(),
25
+ blobType: bcs.enum("BlobPersistenceType", { Permanent: null, Deletable: bcs.struct("Deletable", { objectId: bcs.Address }) }),
26
+ }),
27
+ });
28
+ /** The message every confirming node signs for this blob in this epoch. */
29
+ export function confirmationMessage(epoch, blobId, deletable, blobObjectId) {
30
+ return StorageConfirmation.serialize({
31
+ intent: { type: BLOB_CERT_MSG, version: 0, appId: WALRUS_APP_ID },
32
+ epoch,
33
+ messageContents: {
34
+ blobId: blobIdToInt(blobId),
35
+ blobType: deletable ? { Deletable: { objectId: blobObjectId } } : { Permanent: null },
36
+ },
37
+ }).toBytes();
38
+ }
39
+ const sameBytes = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
40
+ /**
41
+ * Combine the confirmations whose message and signature hold into a certificate, or throw when their
42
+ * shard weight is short of the chain's quorum. `members` is the BLS committee in signer-index order.
43
+ */
44
+ export function certificateByShardWeight(confirmations, members, nShards, expected) {
45
+ const sigs = bls12_381.longSignatures;
46
+ const hashed = sigs.hash(expected);
47
+ const signed = confirmations.flatMap((confirmation, index) => {
48
+ const member = members[index];
49
+ if (!confirmation || !member || !sameBytes(fromBase64(confirmation.serializedMessage), expected))
50
+ return [];
51
+ return [{ index, weight: member.weight, key: new Uint8Array(member.public_key.bytes), signature: fromBase64(confirmation.signature) }];
52
+ });
53
+ const aggregateHolds = (set) => set.length > 0 &&
54
+ sigs.verify(sigs.aggregateSignatures(set.map((s) => s.signature)), hashed, sigs.aggregatePublicKeys(set.map((s) => s.key)));
55
+ const valid = aggregateHolds(signed) ? signed : signed.filter((s) => sigs.verify(s.signature, hashed, s.key));
56
+ const weight = valid.reduce((sum, s) => sum + s.weight, 0);
57
+ if (!chainQuorum(weight, nShards)) {
58
+ throw new NotEnoughBlobConfirmationsError(`Too few confirmed shards for blob (${weight} of ${nShards} from ${valid.length} nodes; the chain needs more than two thirds)`);
59
+ }
60
+ return {
61
+ signers: valid.map((s) => s.index),
62
+ serializedMessage: expected,
63
+ signature: sigs.Signature.toBytes(sigs.aggregateSignatures(valid.map((s) => s.signature))),
64
+ };
65
+ }
66
+ /** Replace the client's node-count certificate with the chain's shard-weight one. */
67
+ export function certifyByShardWeight(walrus) {
68
+ walrus.certificateFromConfirmations = async ({ confirmations, blobId, deletable, blobObjectId }) => {
69
+ const { committee } = await walrus.systemState();
70
+ if (confirmations.length !== committee.members.length) {
71
+ throw new NotEnoughBlobConfirmationsError("Invalid number of confirmations. Confirmations array must contain an entry for each node");
72
+ }
73
+ const expected = confirmationMessage(committee.epoch, blobId, deletable, blobObjectId);
74
+ return certificateByShardWeight(confirmations, committee.members, committee.n_shards, expected);
75
+ };
76
+ return walrus;
77
+ }
@@ -0,0 +1,17 @@
1
+ import type { WalrusClient } from "@mysten/walrus";
2
+ type WriteAll = WalrusClient["writeEncodedBlobToNodes"];
3
+ type Writer = Pick<WalrusClient, "writeEncodedBlobToNode" | "systemState"> & {
4
+ writeEncodedBlobToNodes: WriteAll;
5
+ };
6
+ export declare const QUORUM_GRACE_MIN_MS = 2000;
7
+ export declare const QUORUM_GRACE_MAX_MS = 20000;
8
+ export declare const STALL_FLOOR_MS = 90000;
9
+ export declare const RETRY_WAITS_MS: readonly number[];
10
+ export interface QuorumTiming {
11
+ now?: () => number;
12
+ stallFloorMs?: number;
13
+ retryWaitsMs?: readonly number[];
14
+ }
15
+ /** Replace the client's all-nodes wait with quorum-then-grace. Returns the same client. */
16
+ export declare function stopAtQuorum<T extends Writer>(walrus: T, timing?: QuorumTiming): T;
17
+ export {};
@@ -0,0 +1,103 @@
1
+ import { chainQuorum } from "./node-certificate.js";
2
+ export const QUORUM_GRACE_MIN_MS = 2_000;
3
+ export const QUORUM_GRACE_MAX_MS = 20_000;
4
+ export const STALL_FLOOR_MS = 90_000;
5
+ export const RETRY_WAITS_MS = [3_000, 6_000, 12_000, 24_000];
6
+ /** So many shards lost that the rest can never reach the chain's quorum. */
7
+ const beyondHope = (lostShards, nShards) => !chainQuorum(nShards - lostShards, nShards);
8
+ /** Wait `ms`, or less when the signal aborts. */
9
+ const pause = (ms, signal) => new Promise((resolve) => {
10
+ const timer = setTimeout(resolve, ms);
11
+ signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
12
+ });
13
+ /** Replace the client's all-nodes wait with quorum-then-grace. Returns the same client. */
14
+ export function stopAtQuorum(walrus, timing = {}) {
15
+ const now = timing.now ?? Date.now;
16
+ const stallFloorMs = timing.stallFloorMs ?? STALL_FLOOR_MS;
17
+ const waits = timing.retryWaitsMs ?? RETRY_WAITS_MS;
18
+ /** One node's write, asked again after a failure while the write is open. */
19
+ const writeOne = async (input, signal) => {
20
+ for (let attempt = 0;; attempt++) {
21
+ try {
22
+ return await walrus.writeEncodedBlobToNode(input);
23
+ }
24
+ catch (error) {
25
+ const wait = waits[attempt];
26
+ if (wait === undefined || signal.aborted)
27
+ throw error;
28
+ await pause(wait, signal);
29
+ if (signal.aborted)
30
+ throw error;
31
+ }
32
+ }
33
+ };
34
+ const writeAll = async ({ blobId, metadata, sliversByNode, signal, ...options }) => {
35
+ const { committee } = await walrus.systemState();
36
+ const nShards = committee.n_shards;
37
+ const nNodes = sliversByNode.length;
38
+ const controller = new AbortController();
39
+ const linked = signal ? AbortSignal.any([controller.signal, signal]) : controller.signal;
40
+ const results = sliversByNode.map(() => null);
41
+ const started = now();
42
+ let okShards = 0;
43
+ let lostShards = 0;
44
+ let settled = 0;
45
+ return await new Promise((resolve, reject) => {
46
+ let graceTimer = null;
47
+ let stallTimer = null;
48
+ let stallMs = null;
49
+ let done = false;
50
+ const tooMany = (why) => new Error(`Too many failures while writing blob ${blobId} to nodes (${why})`);
51
+ const quorum = () => chainQuorum(okShards, nShards);
52
+ const finish = (error) => {
53
+ if (done)
54
+ return;
55
+ done = true;
56
+ if (graceTimer !== null)
57
+ clearTimeout(graceTimer);
58
+ if (stallTimer !== null)
59
+ clearTimeout(stallTimer);
60
+ controller.abort(error ?? new Error("quorum reached; the remaining node writes were stopped"));
61
+ if (error)
62
+ reject(error);
63
+ else
64
+ resolve([...results]);
65
+ };
66
+ const check = () => {
67
+ if (settled === nNodes)
68
+ return finish(quorum() ? undefined : tooMany("no quorum"));
69
+ if (graceTimer === null && quorum()) {
70
+ const grace = Math.min(Math.max(now() - started, QUORUM_GRACE_MIN_MS), QUORUM_GRACE_MAX_MS);
71
+ graceTimer = setTimeout(() => finish(), grace);
72
+ }
73
+ if (stallMs === null && okShards * 2 > nShards)
74
+ stallMs = Math.max((now() - started) * 4, stallFloorMs);
75
+ if (stallMs !== null) {
76
+ if (stallTimer !== null)
77
+ clearTimeout(stallTimer);
78
+ stallTimer = setTimeout(() => finish(quorum() ? undefined : tooMany(`${nNodes - settled} nodes did not answer`)), stallMs);
79
+ }
80
+ };
81
+ sliversByNode.forEach((slivers, nodeIndex) => {
82
+ const shards = slivers.primary.length;
83
+ writeOne({ blobId, nodeIndex, metadata, slivers, signal: linked, ...options }, linked)
84
+ .then((confirmation) => {
85
+ results[nodeIndex] = confirmation;
86
+ okShards += shards;
87
+ }, () => {
88
+ lostShards += shards;
89
+ })
90
+ .finally(() => {
91
+ settled += 1;
92
+ if (done)
93
+ return;
94
+ if (beyondHope(lostShards, nShards))
95
+ return finish(tooMany("refused"));
96
+ check();
97
+ });
98
+ });
99
+ });
100
+ };
101
+ walrus.writeEncodedBlobToNodes = writeAll;
102
+ return walrus;
103
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The tip a relay charges, as parsed from its `GET /v1/tip-config`. A relay is free (`none`),
3
+ * flat (`const`), or size-linear (`linear`). `unknown` means the endpoint answered but we could
4
+ * not understand its tip shape — REACHABLE BUT UNUSABLE (scoring gates it out, never guesses a
5
+ * price). All MIST amounts are bigint.
6
+ */
7
+ export type RelayTip = {
8
+ readonly kind: "none";
9
+ } | {
10
+ readonly kind: "const";
11
+ readonly address: string;
12
+ readonly baseMist: bigint;
13
+ } | {
14
+ readonly kind: "linear";
15
+ readonly address: string;
16
+ readonly baseMist: bigint;
17
+ /** MIST added per KiB of ENCODED size (Walrus config `encoded_size_mul_per_kib`). */
18
+ readonly mulPerKibMist: bigint;
19
+ } | {
20
+ readonly kind: "unknown";
21
+ readonly detail: string;
22
+ };
23
+ /**
24
+ * Parse a relay's `/v1/tip-config` JSON into a RelayTip, DEFENSIVELY (an unrecognized/garbled shape
25
+ * becomes `unknown`, never a guessed price). Recognized shapes:
26
+ * no-tip: { "no_tip": ... } → none
27
+ * const: { "send_tip": { "address", "kind": { "const": N } } } → const
28
+ * linear: { "send_tip": { "address",
29
+ * "kind": { "linear": { "base": N,
30
+ * "encoded_size_mul_per_kib": M } } } } → linear
31
+ * Tolerates a missing `send_tip` wrapper (reads `kind` off the root) and camelCase `sendTip`.
32
+ */
33
+ export declare function parseTipConfig(raw: unknown): RelayTip;
@@ -0,0 +1,68 @@
1
+ // A relay's tip, read from its `GET /v1/tip-config`. Kept apart from the relay pool so the
2
+ // command-line tool reads a tip with the same parser the browser uses (it copies this file).
3
+ /** Coerce a JSON tip amount (number | numeric string | bigint) to a non-negative bigint, or null. */
4
+ function toMist(value) {
5
+ if (typeof value === "number")
6
+ return Number.isInteger(value) && value >= 0 ? BigInt(value) : null;
7
+ if (typeof value === "bigint")
8
+ return value >= 0n ? value : null;
9
+ if (typeof value === "string")
10
+ return /^\d+$/.test(value) ? BigInt(value) : null;
11
+ return null;
12
+ }
13
+ /** The value under `key` when `value` is a JSON object that has it; `undefined` otherwise. */
14
+ function field(value, key) {
15
+ return typeof value === "object" && value !== null && key in value ? Reflect.get(value, key) : undefined;
16
+ }
17
+ function isObject(value) {
18
+ return typeof value === "object" && value !== null;
19
+ }
20
+ /**
21
+ * Parse a relay's `/v1/tip-config` JSON into a RelayTip, DEFENSIVELY (an unrecognized/garbled shape
22
+ * becomes `unknown`, never a guessed price). Recognized shapes:
23
+ * no-tip: { "no_tip": ... } → none
24
+ * const: { "send_tip": { "address", "kind": { "const": N } } } → const
25
+ * linear: { "send_tip": { "address",
26
+ * "kind": { "linear": { "base": N,
27
+ * "encoded_size_mul_per_kib": M } } } } → linear
28
+ * Tolerates a missing `send_tip` wrapper (reads `kind` off the root) and camelCase `sendTip`.
29
+ */
30
+ export function parseTipConfig(raw) {
31
+ // A no-tip relay answers the bare JSON string "no_tip" (measured on Mysten's relay image v1.60.1,
32
+ // 2026-11-09; the SDK reads any string as "no tip"). Read as an object, a free relay would be
33
+ // "unknown" and could never be chosen.
34
+ if (raw === "no_tip")
35
+ return { kind: "none" };
36
+ if (!isObject(raw)) {
37
+ return { kind: "unknown", detail: "tip-config was not a JSON object" };
38
+ }
39
+ if ("no_tip" in raw || field(raw, "tip") === "no_tip")
40
+ return { kind: "none" };
41
+ const sendTip = field(raw, "send_tip") ?? field(raw, "sendTip");
42
+ const node = isObject(sendTip) ? sendTip : raw;
43
+ const addressValue = field(node, "address");
44
+ const address = typeof addressValue === "string" ? addressValue : "";
45
+ const kind = field(node, "kind");
46
+ if (!isObject(kind)) {
47
+ return { kind: "unknown", detail: "tip-config had no recognizable send_tip.kind" };
48
+ }
49
+ if ("const" in kind) {
50
+ const baseMist = toMist(field(kind, "const"));
51
+ if (baseMist === null)
52
+ return { kind: "unknown", detail: "const tip amount was not a non-negative integer" };
53
+ return { kind: "const", address, baseMist };
54
+ }
55
+ if ("linear" in kind) {
56
+ const linear = field(kind, "linear");
57
+ if (!isObject(linear)) {
58
+ return { kind: "unknown", detail: "linear tip had no body" };
59
+ }
60
+ const baseMist = toMist(field(linear, "base") ?? 0);
61
+ const mulPerKibMist = toMist(field(linear, "encoded_size_mul_per_kib"));
62
+ if (baseMist === null || mulPerKibMist === null) {
63
+ return { kind: "unknown", detail: "linear tip base/encoded_size_mul_per_kib were not non-negative integers" };
64
+ }
65
+ return { kind: "linear", address, baseMist, mulPerKibMist };
66
+ }
67
+ return { kind: "unknown", detail: "unrecognized tip kind (expected const | linear | no_tip)" };
68
+ }
@@ -4,12 +4,24 @@ export declare const OWN_RELAY_PATH = "/v1/relay";
4
4
  export declare const OWN_RELAY_PART_BYTES: number;
5
5
  /** How long Mysten's relay gets to answer before this run takes the own road. */
6
6
  export declare const ROAD_PROBE_TIMEOUT_MS = 10000;
7
+ /**
8
+ * The "relay address" of the direct road: no host, the storage nodes themselves (D51). The same
9
+ * value as the browser's (`web/src/lib/walrus/node-road.ts`), and it is what a resumable upload's
10
+ * record keeps, so a resumed part goes back to the nodes.
11
+ */
12
+ export declare const NODE_ROAD = "walrus:storage-nodes";
13
+ /** True for the direct road. */
14
+ export declare function isNodeRoad(relayUrl: string): boolean;
15
+ /** True for a road that takes no tip: the own relay and the storage nodes. */
16
+ export declare function isTipFree(relayUrl: string): boolean;
7
17
  /** True for the own relay's address on any NMTS server. */
8
18
  export declare function isOwnRelay(relayUrl: string): boolean;
9
19
  /**
10
- * Decide this run's road, once, before anything is priced. True when the own road was taken.
20
+ * Decide this run's road, once, before anything is priced. True when a small road (the storage
21
+ * nodes, or the own relay) was taken.
11
22
  *
12
- * `probe` is the request that asks Mysten's relay (tests pass a fake one).
23
+ * `probe` is the request that asks Mysten's relay (tests pass a fake one). `nodeRoad: false` is a
24
+ * machine that cannot write to the storage nodes itself; it goes to the own relay, as before D51.
13
25
  */
14
26
  export declare function chooseUploadRoad(input: {
15
27
  network: string;
@@ -17,12 +29,22 @@ export declare function chooseUploadRoad(input: {
17
29
  apiKey: string;
18
30
  probe?: typeof fetch;
19
31
  timeoutMs?: number;
32
+ nodeRoad?: boolean;
33
+ /** A wallet upload: the person pays the tip, so the other company relays may carry it. */
34
+ otherCompanies?: boolean;
35
+ /** A credit upload: the other company relays may carry it while their tip fits the credit ceiling. */
36
+ credit?: boolean;
20
37
  }): Promise<boolean>;
38
+ /**
39
+ * The own relay to try when a direct write failed, with the fetch that carries this account's key,
40
+ * or null when this run did not choose the small roads (a named relay, or Mysten's).
41
+ */
42
+ export declare function ownRelayFallback(): string | null;
21
43
  /** Forget the choice (tests; a library caller between runs). */
22
44
  export declare function resetUploadRoad(): void;
23
- /** The relay this run writes through: the own one when it was chosen, else the usual one. */
45
+ /** The road this run writes through: the storage nodes or the own relay when chosen, else the usual relay. */
24
46
  export declare function uploadRelay(network: string): string;
25
- /** The part size a fresh upload uses: unchanged on Mysten's road, at most 64 MiB on ours. */
47
+ /** The part size a fresh upload uses: unchanged on Mysten's road, at most 64 MiB on the small roads. */
26
48
  export declare function partSizeForRoad(partSize: number): number;
27
49
  /**
28
50
  * The fetch the relay client uses. On the own road it carries this account's key, and while another
@@ -1,5 +1,19 @@
1
1
  /**
2
- * NMTS's own upload relay — the second road for uploads from this tool (D50, 2026-11-09).
2
+ * The roads an upload from this tool can take (D50 · D51, 2026-11-09).
3
+ *
4
+ * ⭐ ORDER (owner, 2026-11-09). Mysten Labs' relay; when it does not answer, the Walrus storage
5
+ * nodes straight from this machine (`NODE_ROAD`, no relay, no tip); NMTS's own relay last, only
6
+ * for a part the direct write could not carry. The own relay is a server the owner pays for and
7
+ * shares with the site, so it is the road taken when nothing else carried the bytes.
8
+ * Between them, the other company relays of `RELAY_HOSTS` (Studio Mirai since 2026-11-10, found by
9
+ * a live probe; the registry lists no relays). On a wallet upload the person pays that relay's tip
10
+ * and sees it before signing. On a credit upload the treasury pays it only while its tip fits the
11
+ * credit ceiling at every size (`credit-tip.ts`, three times Mysten's formula; the chain service
12
+ * refuses above it), because this road is chosen before the size is known.
13
+ *
14
+ * ⭐ THE TWO LAST ROADS COST THE SAME AND CUT THE SAME. Neither takes a tip, and both send 64 MiB
15
+ * parts, so the price shown before the first signature holds whichever of them carries a part,
16
+ * and the registration a part was bought with serves either.
3
17
  *
4
18
  * ⛔ WHY. Every upload reached Walrus through Mysten Labs' relay alone; the day it stops answering,
5
19
  * nobody can upload. NMTS runs the same relay software (Mysten's image, no tip) behind its own
@@ -17,51 +31,99 @@
17
31
  */
18
32
  import { reachFetch } from "./reach.js";
19
33
  import { RELAY_HOSTS, relayHost } from "./walrus.js";
34
+ import { creditTipFitsEverySize, tipLine } from "./shared/lib/walrus/credit-tip.js";
35
+ import { parseTipConfig } from "./shared/lib/walrus/tip-config.js";
20
36
  /** Where the own relay answers, after the NMTS server's address. */
21
37
  export const OWN_RELAY_PATH = "/v1/relay";
22
38
  /** The part size on the own road: an existing preset, the size whose relay peak fits the server. */
23
39
  export const OWN_RELAY_PART_BYTES = 64 * 2 ** 20;
24
40
  /** How long Mysten's relay gets to answer before this run takes the own road. */
25
41
  export const ROAD_PROBE_TIMEOUT_MS = 10_000;
42
+ /**
43
+ * The "relay address" of the direct road: no host, the storage nodes themselves (D51). The same
44
+ * value as the browser's (`web/src/lib/walrus/node-road.ts`), and it is what a resumable upload's
45
+ * record keeps, so a resumed part goes back to the nodes.
46
+ */
47
+ export const NODE_ROAD = "walrus:storage-nodes";
48
+ /** True for the direct road. */
49
+ export function isNodeRoad(relayUrl) {
50
+ return relayUrl === NODE_ROAD;
51
+ }
52
+ /** True for a road that takes no tip: the own relay and the storage nodes. */
53
+ export function isTipFree(relayUrl) {
54
+ return isNodeRoad(relayUrl) || isOwnRelay(relayUrl);
55
+ }
26
56
  let chosen = null;
57
+ /** A company relay after Mysten's, taken when Mysten's did not answer (D51). */
58
+ let companyRelay = null;
27
59
  /** True for the own relay's address on any NMTS server. */
28
60
  export function isOwnRelay(relayUrl) {
29
61
  return relayUrl.replace(/\/+$/, "").endsWith(OWN_RELAY_PATH);
30
62
  }
31
63
  /**
32
- * Decide this run's road, once, before anything is priced. True when the own road was taken.
64
+ * Decide this run's road, once, before anything is priced. True when a small road (the storage
65
+ * nodes, or the own relay) was taken.
33
66
  *
34
- * `probe` is the request that asks Mysten's relay (tests pass a fake one).
67
+ * `probe` is the request that asks Mysten's relay (tests pass a fake one). `nodeRoad: false` is a
68
+ * machine that cannot write to the storage nodes itself; it goes to the own relay, as before D51.
35
69
  */
36
70
  export async function chooseUploadRoad(input) {
37
71
  chosen = null;
38
- const known = RELAY_HOSTS[input.network]?.[0];
72
+ companyRelay = null;
73
+ const relays = RELAY_HOSTS[input.network] ?? [];
74
+ const known = relays[0];
39
75
  // A caller or an environment that named a relay chose it; nothing is asked.
40
76
  if (known === undefined || relayHost(input.network) !== known)
41
77
  return false;
42
78
  const probe = input.probe ?? reachFetch;
43
- try {
44
- const res = await probe(`${known}/v1/tip-config`, {
45
- signal: AbortSignal.timeout(input.timeoutMs ?? ROAD_PROBE_TIMEOUT_MS),
46
- });
47
- if (res.ok)
79
+ const answers = async (relay) => {
80
+ try {
81
+ const res = await probe(`${relay}/v1/tip-config`, {
82
+ signal: AbortSignal.timeout(input.timeoutMs ?? ROAD_PROBE_TIMEOUT_MS),
83
+ });
84
+ if (!res.ok)
85
+ return false;
86
+ // Mysten's own price is the reference; another company's must fit the credit ceiling.
87
+ if (input.credit !== true || relay === known)
88
+ return true;
89
+ const line = tipLine(parseTipConfig(await res.json()));
90
+ return line !== null && creditTipFitsEverySize(line);
91
+ }
92
+ catch {
48
93
  return false;
94
+ }
95
+ };
96
+ // Asked together, so a dead relay costs one timeout, not one each; Mysten's answer wins.
97
+ const others = input.otherCompanies === true || input.credit === true ? relays.slice(1) : [];
98
+ const answered = await Promise.all([known, ...others].map(answers));
99
+ if (answered[0])
100
+ return false;
101
+ const other = others.find((_, i) => answered[i + 1]);
102
+ if (other !== undefined) {
103
+ companyRelay = other;
104
+ return false;
49
105
  }
50
- catch {
51
- // No answer: the own road below.
52
- }
53
- chosen = { relayUrl: `${input.server.replace(/\/+$/, "")}${OWN_RELAY_PATH}`, apiKey: input.apiKey };
106
+ const ownUrl = `${input.server.replace(/\/+$/, "")}${OWN_RELAY_PATH}`;
107
+ chosen = { relayUrl: input.nodeRoad === false ? ownUrl : NODE_ROAD, apiKey: input.apiKey, ownUrl };
54
108
  return true;
55
109
  }
110
+ /**
111
+ * The own relay to try when a direct write failed, with the fetch that carries this account's key,
112
+ * or null when this run did not choose the small roads (a named relay, or Mysten's).
113
+ */
114
+ export function ownRelayFallback() {
115
+ return chosen === null || chosen.relayUrl === chosen.ownUrl ? null : chosen.ownUrl;
116
+ }
56
117
  /** Forget the choice (tests; a library caller between runs). */
57
118
  export function resetUploadRoad() {
58
119
  chosen = null;
120
+ companyRelay = null;
59
121
  }
60
- /** The relay this run writes through: the own one when it was chosen, else the usual one. */
122
+ /** The road this run writes through: the storage nodes or the own relay when chosen, else the usual relay. */
61
123
  export function uploadRelay(network) {
62
- return chosen?.relayUrl ?? relayHost(network);
124
+ return chosen?.relayUrl ?? companyRelay ?? relayHost(network);
63
125
  }
64
- /** The part size a fresh upload uses: unchanged on Mysten's road, at most 64 MiB on ours. */
126
+ /** The part size a fresh upload uses: unchanged on Mysten's road, at most 64 MiB on the small roads. */
65
127
  export function partSizeForRoad(partSize) {
66
128
  return chosen === null ? partSize : Math.min(partSize, OWN_RELAY_PART_BYTES);
67
129
  }
@@ -76,7 +138,7 @@ const wait = (ms, signal) => new Promise((resolve, reject) => {
76
138
  });
77
139
  export function relayFetch(relayUrl, inner, sleep = wait) {
78
140
  const road = chosen;
79
- if (road === null || road.relayUrl !== relayUrl)
141
+ if (road === null || road.ownUrl !== relayUrl)
80
142
  return inner;
81
143
  return async (input, init) => {
82
144
  const headers = new Headers(init?.headers);