@needmoretruth/nmts-cli 0.57.0 → 0.58.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,17 @@
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.58.0 — 2026-11-11
7
+
8
+ - `nmts wallet storage buy --size <n> [--epochs <n>]` buys a storage resource with nothing in it,
9
+ paid in WAL from the wallet, for 2 epochs unless `--epochs` says otherwise. It shows the price and
10
+ the chain fee first, signs only with `--yes`, and needs `nmts unlock wallet`. `put --pay wallet
11
+ --storage <id>` then writes a file into it.
12
+ - A program can price an upload with no account (`@needmoretruth/nmts-cli/portable` exports
13
+ `quoteUpload`), and a business's server can check a transaction a customer's device built before
14
+ its own wallet signs it (`judgeSponsored`, `signSponsored`): only Walrus storage work within the limits
15
+ it sets passes.
16
+
6
17
  ## 0.57.0 — 2026-11-10
7
18
 
8
19
  - A program can share a file the way `nmts share` does: `@needmoretruth/nmts-cli/share` exports
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.57.0 # 버전을 고정할 때
53
+ npm install -g github:needmoretruth/nmts-cli#v0.58.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.57.0 # a pinned version
54
+ npm install -g github:needmoretruth/nmts-cli#v0.58.0 # a pinned version
55
55
  npm install -g https://github.com/needmoretruth/nmts-cli/releases/latest/download/nmts.tgz
56
56
  ```
57
57
 
@@ -11,7 +11,7 @@ export declare const CRYPTO_SPEC_URL = "https://github.com/needmoretruth/nmts-re
11
11
  * is the field's own contract — what the writer says about itself — and a person holding two
12
12
  * copies of one account's artefacts can then tell which program made each.
13
13
  */
14
- export declare const WRITTEN_BY = "nmts-cli 0.57.0";
14
+ export declare const WRITTEN_BY = "nmts-cli 0.58.0";
15
15
  /** Which of the three artefacts a wrapper is. A reader holding several can sort them. */
16
16
  export type ArtifactKind = "recovery-list" | "file-list" | "recovery-kit";
17
17
  /**
@@ -0,0 +1,22 @@
1
+ import { type BuySeams } from "../storage-control.ts";
2
+ import type { SignStorageOp } from "../wallet-sign.ts";
3
+ export interface StorageBuyOptions {
4
+ server?: string | undefined;
5
+ network?: string | undefined;
6
+ json?: boolean;
7
+ write?: (line: string) => void;
8
+ yes?: boolean;
9
+ dryRun?: boolean;
10
+ /** `--size <bytes|KiB|MiB|GiB>`: the resource's size, encoded bytes as the listing shows them. */
11
+ size?: string | undefined;
12
+ /** `--epochs <n>`: the term, from the current epoch. Default 2. */
13
+ epochs?: string | undefined;
14
+ /** `--wallet N`: which wallet pays and receives it, this run only. */
15
+ wallet?: string | undefined;
16
+ now?: number;
17
+ /** ⚠ SEAMS, NOT OPTIONS — no flag reaches them. */
18
+ readActiveWallet?: () => Promise<number>;
19
+ buyReads?: BuySeams["reads"];
20
+ signStorage?: SignStorageOp;
21
+ }
22
+ export declare function walletStorageBuy(options?: StorageBuyOptions): Promise<number>;
@@ -0,0 +1,111 @@
1
+ // `nmts wallet storage buy --size <n> [--epochs <n>]` — buying a storage resource with no file.
2
+ // ⛔ IT SIGNS AND SPENDS WAL. The order, the price, the dry run and the signature are
3
+ // `storage-control/buy.ts`, which the SDK calls as well; this file is the terminal over it: the
4
+ // words typed, the review read, `--yes`, and the wallet unlock held against what the review measured.
5
+ //
6
+ // ⛔ WHY (spec 2026-09-20 Deponejo · gap B2). A resource bought here is cut and handed on with the
7
+ // three commands beside it (`split`, `merge`, `transfer`), in the same place and under the same
8
+ // unlock scope — buying is a change to the wallet's storage like those, only one that costs WAL.
9
+ import { requireAccountCode } from "../code-access.js";
10
+ import { readCredentialsFile } from "../credentials.js";
11
+ import { NmtsError } from "../errors.js";
12
+ import { resolveNetwork } from "../network.js";
13
+ import { BINARY_NAME } from "../product.js";
14
+ import { resolveServer } from "../server.js";
15
+ import { buyStorage } from "../storage-control.js";
16
+ import { explorerTxUrl } from "../shared/lib/wallet/activity.js";
17
+ import { coinAmount, walletAddress } from "../wallet.js";
18
+ import { payingWalletIndex } from "../wallet-pay-index.js";
19
+ import { recordWalletSpend, requireWalletGrant } from "../wallet-grant.js";
20
+ import { parseBytes } from "./wallet-storage-ops.js";
21
+ import { formatBytes } from "./wallet-storage.js";
22
+ export async function walletStorageBuy(options = {}) {
23
+ const say = options.write ?? ((line) => process.stdout.write(`${line}\n`));
24
+ if (options.size === undefined) {
25
+ throw new NmtsError(`\`${BINARY_NAME} wallet storage buy --size <bytes> [--epochs <n>]\``, { exitCode: 2 });
26
+ }
27
+ const sizeBytes = parseBytes(options.size);
28
+ const epochs = options.epochs === undefined ? undefined : Number(options.epochs);
29
+ const resolved = await requireAccountCode();
30
+ const wallet = await payingWalletIndex(options);
31
+ const address = await walletAddress(resolved.code, wallet);
32
+ const stored = resolved.source === "file" || resolved.source === "file-locked" ? readCredentialsFile() : null;
33
+ const server = resolveServer(options.server ?? stored?.server);
34
+ const network = resolveNetwork(server, options.network ?? stored?.network);
35
+ const command = `${BINARY_NAME} wallet storage buy --size ${options.size}${options.epochs === undefined ? "" : ` --epochs ${options.epochs}`}`;
36
+ // ⛔ WITHOUT `--yes` THE RUN STOPS AT THE REVIEW, exactly as `--dry-run` does.
37
+ const stopAtReview = options.dryRun === true || options.yes !== true;
38
+ const outcome = await buyStorage({ network, code: resolved.code, wallet, address }, { sizeBytes, epochs }, {
39
+ reads: options.buyReads,
40
+ sign: options.signStorage,
41
+ dryRun: stopAtReview,
42
+ onReview: (review) => {
43
+ if (!options.json)
44
+ describe(say, review, wallet);
45
+ },
46
+ // The unlock, held against the price and the fee. ⛔ Throwing here signs nothing.
47
+ agree: (review) => {
48
+ requireWalletGrant("reshape", spendOf(review), new Date(options.now ?? Date.now()));
49
+ },
50
+ });
51
+ const { review } = outcome;
52
+ const facts = {
53
+ op: "buy",
54
+ network,
55
+ address,
56
+ sizeBytes: review.sizeBytes,
57
+ epochs: review.epochs,
58
+ endEpoch: review.endEpoch,
59
+ wal: coinAmount(review.priceFrost),
60
+ feeSui: review.feeMist === null ? null : coinAmount(review.feeMist),
61
+ shortfall: review.shortfall,
62
+ };
63
+ if (outcome.kind === "review") {
64
+ if (options.json) {
65
+ say(JSON.stringify({ ...facts, signed: false, dryRun: options.dryRun === true }));
66
+ return options.dryRun === true ? 0 : 4;
67
+ }
68
+ say(``);
69
+ if (options.dryRun === true) {
70
+ say(` Nothing was signed. Run the same command with --yes to buy it.`);
71
+ return 0;
72
+ }
73
+ throw new NmtsError(`Nothing was signed: this needs --yes.`, {
74
+ exitCode: 4,
75
+ nextStep: `Read the review above, then: \`${command} --yes\``,
76
+ });
77
+ }
78
+ recordWalletSpend(spendOf(review));
79
+ const explorerUrl = explorerTxUrl(outcome.digest, network);
80
+ if (options.json) {
81
+ say(JSON.stringify({ ...facts, signed: true, digest: outcome.digest, id: outcome.objectId, explorerUrl }));
82
+ return 0;
83
+ }
84
+ say(``);
85
+ say(` Bought. Transaction ${outcome.digest}`);
86
+ if (outcome.objectId !== null)
87
+ say(` Resource ${outcome.objectId}`);
88
+ say(` ${explorerUrl}`);
89
+ say(` \`${BINARY_NAME} wallet storage\` lists it; \`put --pay wallet --storage <id>\` uploads into it.`);
90
+ return 0;
91
+ }
92
+ /** What a purchase costs this wallet: the price in WAL and the fee the dry run measured. */
93
+ function spendOf(review) {
94
+ return { walFrost: review.priceFrost, suiMist: review.feeMist ?? 0n };
95
+ }
96
+ /** The review a person reads, in the order somebody deciding needs it. */
97
+ function describe(say, review, wallet) {
98
+ say(`Would buy a storage resource of ${formatBytes(review.sizeBytes)} for ${review.epochs} epoch${review.epochs === 1 ? "" : "s"}, epoch ${review.startEpoch} to ${review.endEpoch}.`);
99
+ say(` paid by ${review.address} (wallet ${wallet}), which also receives it`);
100
+ say(` Storage ${coinAmount(review.priceFrost)} WAL. Writing a file into it later costs its own small WAL.`);
101
+ say(review.feeMist === null
102
+ ? ` Chain fee (SUI): could not be measured just now; it is charged with the signature.`
103
+ : ` Chain fee about ${coinAmount(review.feeMist)} SUI, measured by a dry run just now.`);
104
+ const wal = review.walFrost === null ? "WAL not read" : `${coinAmount(review.walFrost)} WAL`;
105
+ const sui = review.suiMist === null ? "SUI not read" : `${coinAmount(review.suiMist)} SUI`;
106
+ say(` The wallet holds ${wal} and ${sui}.`);
107
+ if (review.shortfall !== null)
108
+ say(` ⛔ ${review.shortfall}`);
109
+ say(` The size is what the network holds once a file is encoded, the unit the listing shows.`);
110
+ say(` Nobody, NMTS included, can reverse it.`);
111
+ }
@@ -61,10 +61,12 @@ export async function wallet(what, options = {}) {
61
61
  if (sub === "split" || sub === "merge" || sub === "transfer") {
62
62
  return (await import("./wallet-storage-ops.js")).walletStorageOps(sub, more, options);
63
63
  }
64
+ if (sub === "buy")
65
+ return (await import("./wallet-storage-buy.js")).walletStorageBuy(options);
64
66
  if (sub !== undefined) {
65
67
  throw new NmtsError(`\`${BINARY_NAME} wallet storage ${sub}\` is not something this command does.`, {
66
68
  exitCode: 2,
67
- nextStep: `\`${BINARY_NAME} wallet storage\` lists; \`split\`, \`merge\` and \`transfer\` sign — \`${BINARY_NAME} help wallet\`.`,
69
+ nextStep: `\`${BINARY_NAME} wallet storage\` lists; \`buy\`, \`split\`, \`merge\` and \`transfer\` sign — \`${BINARY_NAME} help wallet\`.`,
68
70
  });
69
71
  }
70
72
  return (await import("./wallet-storage.js")).walletStorage(options);
@@ -101,8 +101,10 @@ export function optionLines() {
101
101
  ` rollback, wallet send, wallet swap, wallet donate),`,
102
102
  ` or extend a file that is nowhere near its deadline (extend)`,
103
103
  ` --epochs <n> How many of the storage network's epochs to add (extend), to buy`,
104
- ` (put, push --pay wallet; default 2), or to keep (wallet storage split)`,
105
- ` --size <bytes> What a cut resource keeps: bytes, or with KiB/MiB/GiB (wallet storage split)`,
104
+ ` (put, push --pay wallet, wallet storage buy; default 2), or to keep`,
105
+ ` (wallet storage split)`,
106
+ ` --size <bytes> What a cut resource keeps, or a bought one holds: bytes, or with`,
107
+ ` KiB/MiB/GiB (wallet storage split, wallet storage buy)`,
106
108
  ` --pay credits|wallet Who pays for an upload's storage (put, push). Default credits.`,
107
109
  ` wallet = the wallet this NMTS key derives signs and pays the`,
108
110
  ` network directly, under a wallet agreement of scope storage`,
package/dist/help.js CHANGED
@@ -75,6 +75,8 @@ export function helpText(version) {
75
75
  ` wallet storage The storage resources (size × time) the wallet holds, unbound`,
76
76
  ` wallet storage split <id> --size <n>|--epochs <n> · merge <id> <id> · transfer <id> <address>`,
77
77
  ` Cut, join or hand over a resource — **signs**, under the wallet unlock`,
78
+ ` wallet storage buy --size <n> [--epochs <n>]`,
79
+ ` Buy a resource with no file — **signs and spends WAL**, under the unlock`,
78
80
  ` wallet send <SUI|WAL> <amount|max> <address>`,
79
81
  ` Send coins to an address — **signs and spends from the wallet**.`,
80
82
  ` Prints the review; sends only with --yes`,
@@ -68,8 +68,13 @@ export type { LinkAccount, ListedLink, MadeLink, OpenedLinkFile } from "./links.
68
68
  export { coinAmount, readBalances, walCoinType, walletAddress } from "./wallet.ts";
69
69
  export type { ChainReader, CoinBalance, WalletBalances } from "./wallet.ts";
70
70
  export { chainReader } from "./wallet-chain.ts";
71
- export { signerAddress, signExtension, signTransfer } from "./wallet-sign.ts";
71
+ export { signerAddress, signExtension, signSponsored, signTransfer } from "./wallet-sign.ts";
72
72
  export type { SignTransfer } from "./wallet-sign.ts";
73
+ export { gasEstimate, MEASURED_GAS, quoteUpload } from "./upload-quote.ts";
74
+ export type { QuotedPart, UploadQuote, UploadQuoteAsk, UploadQuoteReads } from "./upload-quote.ts";
75
+ export { judgeSponsored } from "./sponsor-check.ts";
76
+ export type { SponsorFacts, SponsorPolicy, SponsorRefusal, SponsorSpend, SponsorVerdict } from "./sponsor-check.ts";
77
+ export { readRelayTipAddresses, sponsorFacts } from "./sponsor-facts.ts";
73
78
  export { activeWalletOf, walletCountOf, WALLET_INDEX_LIMIT } from "./shared/lib/drive/manifest-settings.ts";
74
79
  export { classify } from "./shared/lib/drive/preview-classify.ts";
75
80
  export { discoverWallets, WALLET_SCAN_GAP } from "./shared/lib/wallet/discover.ts";
package/dist/portable.js CHANGED
@@ -93,7 +93,12 @@ export { listLinks, listLiveLinks, makeLink, openLink, revokeAllLinks, revokeLin
93
93
  // The wallet the NMTS key derives: reading it, and signing with it.
94
94
  export { coinAmount, readBalances, walCoinType, walletAddress } from "./wallet.js";
95
95
  export { chainReader } from "./wallet-chain.js";
96
- export { signerAddress, signExtension, signTransfer } from "./wallet-sign.js";
96
+ export { signerAddress, signExtension, signSponsored, signTransfer } from "./wallet-sign.js";
97
+ // Money paths with no account (plan 2026-11-10): an upload's price asked with nothing opened, and
98
+ // the check an operator's server runs on a transaction another device built, before signing it.
99
+ export { gasEstimate, MEASURED_GAS, quoteUpload } from "./upload-quote.js";
100
+ export { judgeSponsored } from "./sponsor-check.js";
101
+ export { readRelayTipAddresses, sponsorFacts } from "./sponsor-facts.js";
97
102
  // WHICH of this key's wallets, and which of them have been used. One key derives a wallet at every
98
103
  // index (NCF-3 §1.3), so the account's own number is read out of the sealed list and the rest is a
99
104
  // walk. Both are here so that a library built on this package finds the SAME wallets under the same
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.57.0";
12
+ export declare const VERSION = "0.58.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.57.0";
21
+ export const VERSION = "0.58.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. */
@@ -0,0 +1,56 @@
1
+ import type { Network } from "./network.ts";
2
+ /** What the operator agrees to pay for in ONE transaction. Amounts in base units. */
3
+ export interface SponsorPolicy {
4
+ network: Network;
5
+ /** The operator's address: the only sender and gas owner signed for. */
6
+ operator: string;
7
+ /** Bytes the blobs registered or extended may hold in total (unencoded, as registered). */
8
+ maxBytes: number;
9
+ /** The longest term one reservation or extension may buy, in epochs. */
10
+ maxEpochs: number;
11
+ /** WAL the Walrus calls may take, in FROST. */
12
+ maxWalFrost: bigint | number | string;
13
+ /** SUI the transaction may spend — its gas budget plus relay tips — in MIST. */
14
+ maxSuiMist: bigint | number | string;
15
+ /** The highest gas budget accepted, in MIST. Default: `maxSuiMist`. */
16
+ maxGasBudgetMist?: bigint | number | string | undefined;
17
+ /** Pin the Walrus package instead of reading it from the chain. */
18
+ walrusPackageId?: string | undefined;
19
+ /** Pin the relays' tip addresses instead of asking the relays. */
20
+ relayTipAddresses?: readonly string[] | undefined;
21
+ }
22
+ /** The chain facts a judgement needs. */
23
+ export interface SponsorFacts {
24
+ walrusPackageId: string;
25
+ systemObjectId: string;
26
+ relayTipAddresses: readonly string[];
27
+ /** What a blob of `size` bytes occupies once encoded — the chain's own number. */
28
+ encodedLength(size: number): Promise<number>;
29
+ /** The unencoded size of a blob object, or null when it could not be read. */
30
+ blobSize(objectId: string): Promise<number | null>;
31
+ }
32
+ /** What a passing transaction spends, as decimal strings so a log and JSON carry them whole. */
33
+ export interface SponsorSpend {
34
+ walFrost: string;
35
+ /** Gas budget plus tips: the most SUI it can take. */
36
+ suiMist: string;
37
+ gasBudgetMist: string;
38
+ tipMist: string;
39
+ /** Bytes registered or extended. */
40
+ bytes: number;
41
+ /** The longest term bought, in epochs. 0 for a certification. */
42
+ epochs: number;
43
+ /** The Walrus calls it makes, in order. */
44
+ calls: string[];
45
+ }
46
+ export type SponsorVerdict = {
47
+ ok: true;
48
+ spends: SponsorSpend;
49
+ } | {
50
+ ok: false;
51
+ code: SponsorRefusal;
52
+ reason: string;
53
+ };
54
+ export type SponsorRefusal = "SPONSOR_NOT_A_TRANSACTION" | "SPONSOR_SENDER" | "SPONSOR_GAS_OWNER" | "SPONSOR_GAS_BUDGET" | "SPONSOR_INPUT" | "SPONSOR_COMMAND" | "SPONSOR_CALL" | "SPONSOR_NETWORK" | "SPONSOR_TRANSFER" | "SPONSOR_UNBOUNDED" | "SPONSOR_STORAGE" | "SPONSOR_SIZE" | "SPONSOR_EPOCHS" | "SPONSOR_WAL" | "SPONSOR_SUI" | "SPONSOR_EMPTY";
55
+ /** Judge one transaction against a policy. Never throws for a refusal: the verdict says it. */
56
+ export declare function judgeSponsored(bytes: Uint8Array | string, policy: SponsorPolicy, facts: SponsorFacts): Promise<SponsorVerdict>;
@@ -0,0 +1,270 @@
1
+ // Before an operator's wallet signs a transaction somebody else's device built: is it only the
2
+ // Walrus work the operator agreed to pay for, inside the limits it set?
3
+ //
4
+ // ⛔ WHY (spec 2026-09-20 Deponejo · gap B · plan 2026-11-10 §1.3). A business that takes its
5
+ // customers' money however it likes can let its own wallet pay their storage: the device calls
6
+ // `put(file, { pay: { signer } })` and that signer forwards each transaction to the business's
7
+ // server, which signs as the sender. Without a check the server signs whatever bytes arrive —
8
+ // including a transaction that sends the business's coins to the person who built it. Sui's own
9
+ // gas sponsorship was rejected: it pays only the gas, and WAL can come only from the sender.
10
+ //
11
+ // ⛔ AN ALLOW LIST, READ OFF THE BYTES, NEVER A DENY LIST. What passes is exactly: the sender and the
12
+ // gas owner are the operator; every Move call is `system::reserve_space`, `register_blob`,
13
+ // `certify_blob` or `extend_blob` of the network's Walrus package on the network's own system
14
+ // object, or the coin plumbing the Sui SDK writes for a payment (`coin::redeem_funds`,
15
+ // `coin::destroy_zero`, `coin::zero`, `coin::send_funds` back to the operator); every transfer
16
+ // goes to the operator, except SUI coins of a known amount to an upload relay's tip address; and
17
+ // the size, the term, the WAL and the SUI are within the policy. Anything else is refused with a
18
+ // code and a sentence a log can hold. A new kind of command is refused until somebody decides it
19
+ // here, in the open.
20
+ //
21
+ // ⛔ EVERY COIN THAT LEAVES IS A COIN OF A KNOWN AMOUNT. The WAL a Walrus call may take is bounded by
22
+ // the coins it is handed: each must be cut by `SplitCoins` to an amount written in the bytes (or
23
+ // drawn from the address balance by a reservation of a written amount), and not grown by a merge
24
+ // since. A whole coin, the gas coin, or a coin of unknown amount handed to any call is refused —
25
+ // so even a lying node that named a wrong package could not take more than the policy's WAL.
26
+ //
27
+ // ⚠ PURE: no network and no key. The chain facts it needs — the package, the relays' tip addresses,
28
+ // the encoded length of a size, the size of a blob being extended — are handed in
29
+ // (`sponsor-facts.ts` reads them; a test hands in a table).
30
+ import { bcs } from "@mysten/sui/bcs";
31
+ import { Transaction } from "@mysten/sui/transactions";
32
+ import { fromBase64, normalizeSuiAddress } from "@mysten/sui/utils";
33
+ const WALRUS_CALLS = new Set(["reserve_space", "register_blob", "certify_blob", "extend_blob"]);
34
+ const SUI_TYPE = "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";
35
+ const FRAMEWORK = normalizeSuiAddress("0x2");
36
+ class Refused extends Error {
37
+ code;
38
+ constructor(code, reason) {
39
+ super(reason);
40
+ this.code = code;
41
+ }
42
+ }
43
+ function amountOf(value, name) {
44
+ try {
45
+ const n = BigInt(value);
46
+ if (n >= 0n)
47
+ return n;
48
+ }
49
+ catch {
50
+ // Refused below with the field's name.
51
+ }
52
+ throw new Refused("SPONSOR_NOT_A_TRANSACTION", `the policy's ${name} is not a whole number of base units`);
53
+ }
54
+ function typeIsSui(type) {
55
+ const [address, ...rest] = type.split("::");
56
+ return address !== undefined && `${normalizeSuiAddress(address)}::${rest.join("::")}` === SUI_TYPE;
57
+ }
58
+ /** Judge one transaction against a policy. Never throws for a refusal: the verdict says it. */
59
+ export async function judgeSponsored(bytes, policy, facts) {
60
+ try {
61
+ return { ok: true, spends: await judge(bytes, policy, facts) };
62
+ }
63
+ catch (error) {
64
+ if (error instanceof Refused)
65
+ return { ok: false, code: error.code, reason: error.message };
66
+ throw error;
67
+ }
68
+ }
69
+ async function judge(raw, policy, facts) {
70
+ let data;
71
+ try {
72
+ data = Transaction.from(typeof raw === "string" ? fromBase64(raw) : raw).getData();
73
+ }
74
+ catch (error) {
75
+ throw new Refused("SPONSOR_NOT_A_TRANSACTION", `the bytes are not a Sui transaction (${error instanceof Error ? error.message : String(error)})`);
76
+ }
77
+ const operator = normalizeSuiAddress(policy.operator);
78
+ const maxWal = amountOf(policy.maxWalFrost, "maxWalFrost");
79
+ const maxSui = amountOf(policy.maxSuiMist, "maxSuiMist");
80
+ const maxBudget = policy.maxGasBudgetMist === undefined ? maxSui : amountOf(policy.maxGasBudgetMist, "maxGasBudgetMist");
81
+ const walrus = normalizeSuiAddress(policy.walrusPackageId ?? facts.walrusPackageId);
82
+ const system = normalizeSuiAddress(facts.systemObjectId);
83
+ const tipTo = new Set((policy.relayTipAddresses ?? facts.relayTipAddresses).map((a) => normalizeSuiAddress(a)));
84
+ // ① Who signs and who pays the gas.
85
+ if (data.sender === null || data.sender === undefined || normalizeSuiAddress(data.sender) !== operator) {
86
+ throw new Refused("SPONSOR_SENDER", `the sender is ${data.sender ?? "missing"}, not the operator ${operator}`);
87
+ }
88
+ const gasOwner = data.gasData.owner ?? data.sender;
89
+ if (normalizeSuiAddress(gasOwner) !== operator) {
90
+ throw new Refused("SPONSOR_GAS_OWNER", `the gas is paid by ${gasOwner}, not the operator ${operator}`);
91
+ }
92
+ if (data.gasData.budget === null || data.gasData.budget === undefined) {
93
+ throw new Refused("SPONSOR_GAS_BUDGET", "the transaction names no gas budget");
94
+ }
95
+ const budget = BigInt(data.gasData.budget);
96
+ if (budget > maxBudget)
97
+ throw new Refused("SPONSOR_GAS_BUDGET", `the gas budget ${budget} MIST is over the cap ${maxBudget} MIST`);
98
+ // ② The inputs: plain values, objects, and withdrawals from the operator's own balance only.
99
+ const inputs = data.inputs;
100
+ const pure = (arg, what) => {
101
+ const input = arg?.Input === undefined ? undefined : inputs[arg.Input];
102
+ if (input?.Pure === undefined)
103
+ throw new Refused("SPONSOR_INPUT", `${what} is not a plain value written in the transaction`);
104
+ return fromBase64(input.Pure.bytes);
105
+ };
106
+ const u64 = (arg, what) => BigInt(bcs.u64().parse(pure(arg, what)));
107
+ const u32 = (arg, what) => bcs.u32().parse(pure(arg, what));
108
+ const address = (arg, what) => normalizeSuiAddress(bcs.Address.parse(pure(arg, what)));
109
+ for (const [i, input] of inputs.entries()) {
110
+ if (input.Object?.Receiving !== undefined)
111
+ throw new Refused("SPONSOR_INPUT", `input ${i} receives an object sent to another object`);
112
+ const w = input.FundsWithdrawal;
113
+ if (w !== undefined && w.withdrawFrom.Sender !== true && w.withdrawFrom.Sponsor !== true) {
114
+ throw new Refused("SPONSOR_INPUT", `input ${i} withdraws from an allowance, not from the operator's own balance`);
115
+ }
116
+ }
117
+ // ③ The commands, one by one, with every coin followed from where it was made.
118
+ const coins = new Map();
119
+ const keyOf = (arg) => arg.Result !== undefined ? `${arg.Result}` : arg.NestedResult !== undefined ? `${arg.NestedResult[0]}:${arg.NestedResult[1]}` : null;
120
+ const reserves = new Map();
121
+ const payments = new Map();
122
+ const extended = [];
123
+ const registered = [];
124
+ const calls = [];
125
+ let tips = 0n;
126
+ let epochs = 0;
127
+ const payment = (arg, call) => {
128
+ const key = arg === undefined ? null : keyOf(arg);
129
+ const coin = key === null ? undefined : coins.get(key);
130
+ if (key === null || coin === undefined || coin.amount === null) {
131
+ throw new Refused("SPONSOR_UNBOUNDED", `${call} is paid from a coin whose amount the transaction does not bound`);
132
+ }
133
+ payments.set(key, coin.amount);
134
+ };
135
+ for (const [index, command] of data.commands.entries()) {
136
+ if (command.SplitCoins !== undefined) {
137
+ const source = command.SplitCoins.coin;
138
+ const from = source.GasCoin === true ? { sui: true, amount: null } : (coins.get(keyOf(source) ?? "") ?? { sui: null, amount: null });
139
+ command.SplitCoins.amounts.forEach((amount, j) => {
140
+ const input = amount.Input === undefined ? undefined : inputs[amount.Input];
141
+ coins.set(`${index}:${j}`, { sui: from.sui, amount: input?.Pure === undefined ? null : u64(amount, "a split amount") });
142
+ });
143
+ }
144
+ else if (command.MergeCoins !== undefined) {
145
+ // ⛔ A MERGED-INTO COIN NO LONGER HAS THE AMOUNT IT WAS CUT TO: anything could have joined it.
146
+ const key = keyOf(command.MergeCoins.destination);
147
+ const coin = key === null ? undefined : coins.get(key);
148
+ if (key !== null && coin !== undefined)
149
+ coins.set(key, { sui: coin.sui, amount: null });
150
+ }
151
+ else if (command.TransferObjects !== undefined) {
152
+ const to = address(command.TransferObjects.address, "a transfer's recipient");
153
+ if (to === operator)
154
+ continue;
155
+ if (!tipTo.has(to))
156
+ throw new Refused("SPONSOR_TRANSFER", `command ${index} sends to ${to}, which is neither the operator nor an upload relay's tip address`);
157
+ for (const object of command.TransferObjects.objects) {
158
+ const coin = coins.get(keyOf(object) ?? "");
159
+ if (coin === undefined || coin.sui !== true || coin.amount === null) {
160
+ throw new Refused("SPONSOR_TRANSFER", `command ${index} sends the relay something other than a SUI coin of a written amount`);
161
+ }
162
+ tips += coin.amount;
163
+ }
164
+ }
165
+ else if (command.MoveCall !== undefined) {
166
+ const call = command.MoveCall;
167
+ const args = call.arguments;
168
+ const name = `${call.package}::${call.module}::${call.function}`;
169
+ if (args.some((a) => a.GasCoin === true))
170
+ throw new Refused("SPONSOR_CALL", `${name} is handed the gas coin`);
171
+ const pkg = normalizeSuiAddress(call.package);
172
+ if (pkg === FRAMEWORK && call.module === "coin") {
173
+ if (call.function === "redeem_funds") {
174
+ const input = args[0]?.Input === undefined ? undefined : inputs[args[0].Input];
175
+ const w = input?.FundsWithdrawal;
176
+ if (w === undefined)
177
+ throw new Refused("SPONSOR_CALL", `${name} redeems something other than a withdrawal`);
178
+ coins.set(`${index}`, { sui: typeIsSui(w.typeArg.Balance), amount: BigInt(w.reservation.MaxAmountU64) });
179
+ }
180
+ else if (call.function === "send_funds") {
181
+ const to = address(args[1], "send_funds's recipient");
182
+ if (to !== operator)
183
+ throw new Refused("SPONSOR_TRANSFER", `command ${index} sends funds to ${to}, not back to the operator`);
184
+ }
185
+ else if (call.function !== "destroy_zero" && call.function !== "zero") {
186
+ throw new Refused("SPONSOR_CALL", `${name} is not part of paying for Walrus storage`);
187
+ }
188
+ continue;
189
+ }
190
+ if (pkg !== walrus || call.module !== "system" || !WALRUS_CALLS.has(call.function)) {
191
+ throw new Refused("SPONSOR_CALL", `${name} is not a Walrus reservation, registration, certification or extension`);
192
+ }
193
+ // ⛔ THE NETWORK'S OWN SYSTEM OBJECT, which is what proves the network named is the network signed for.
194
+ const self = args[0]?.Input === undefined ? undefined : inputs[args[0].Input]?.Object?.SharedObject;
195
+ if (self === undefined || normalizeSuiAddress(self.objectId) !== system) {
196
+ throw new Refused("SPONSOR_NETWORK", `${call.function} is not called on the ${policy.network} Walrus system object`);
197
+ }
198
+ calls.push(call.function);
199
+ if (call.function === "reserve_space") {
200
+ const term = u32(args[2], "a reservation's term");
201
+ payment(args[3], call.function);
202
+ reserves.set(`${index}`, { amount: u64(args[1], "a reservation's size"), epochs: term, used: false });
203
+ epochs = Math.max(epochs, term);
204
+ }
205
+ else if (call.function === "register_blob") {
206
+ const reserve = reserves.get(keyOf(args[1] ?? {}) ?? "");
207
+ if (reserve === undefined || reserve.used) {
208
+ throw new Refused("SPONSOR_STORAGE", "a registration binds storage the operator already holds instead of storage bought in this transaction");
209
+ }
210
+ reserve.used = true;
211
+ const size = u64(args[4], "a registration's size");
212
+ if (size > BigInt(Number.MAX_SAFE_INTEGER))
213
+ throw new Refused("SPONSOR_SIZE", `a registration of ${size} bytes`);
214
+ registered.push({ size: Number(size), reserve });
215
+ payment(args[7], call.function);
216
+ }
217
+ else if (call.function === "extend_blob") {
218
+ const blob = args[1]?.Input === undefined ? undefined : inputs[args[1].Input]?.Object?.ImmOrOwnedObject;
219
+ if (blob === undefined)
220
+ throw new Refused("SPONSOR_INPUT", "an extension names no blob object");
221
+ extended.push(blob.objectId);
222
+ const term = u32(args[2], "an extension's term");
223
+ epochs = Math.max(epochs, term);
224
+ payment(args[3], call.function);
225
+ }
226
+ }
227
+ else {
228
+ throw new Refused("SPONSOR_COMMAND", `command ${index} is a ${command.$kind ?? "command"}, which a sponsored upload never needs`);
229
+ }
230
+ }
231
+ // ④ What it all adds up to, against the policy.
232
+ if (calls.length === 0)
233
+ throw new Refused("SPONSOR_EMPTY", "the transaction does no Walrus work");
234
+ if ([...reserves.values()].some((r) => !r.used)) {
235
+ throw new Refused("SPONSOR_STORAGE", "storage is reserved and not written into: that is buying storage, not an upload");
236
+ }
237
+ let bytes = 0;
238
+ for (const { size, reserve } of registered) {
239
+ bytes += size;
240
+ const most = await facts.encodedLength(size);
241
+ if (reserve.amount > BigInt(most)) {
242
+ throw new Refused("SPONSOR_SIZE", `${reserve.amount} bytes are reserved for a blob of ${size}, which needs ${most} once encoded`);
243
+ }
244
+ }
245
+ for (const id of extended) {
246
+ const size = await facts.blobSize(id);
247
+ if (size === null)
248
+ throw new Refused("SPONSOR_SIZE", `the size of blob ${id} could not be read, so the extension is not bounded`);
249
+ bytes += size;
250
+ }
251
+ if (bytes > policy.maxBytes)
252
+ throw new Refused("SPONSOR_SIZE", `${bytes} bytes are over the policy's ${policy.maxBytes}`);
253
+ if (epochs > policy.maxEpochs)
254
+ throw new Refused("SPONSOR_EPOCHS", `${epochs} epochs are over the policy's ${policy.maxEpochs}`);
255
+ const wal = [...payments.values()].reduce((sum, n) => sum + n, 0n);
256
+ if (wal > maxWal)
257
+ throw new Refused("SPONSOR_WAL", `${wal} FROST of WAL is over the policy's ${maxWal}`);
258
+ const sui = budget + tips;
259
+ if (sui > maxSui)
260
+ throw new Refused("SPONSOR_SUI", `${sui} MIST of SUI (gas budget ${budget} + tips ${tips}) is over the policy's ${maxSui}`);
261
+ return {
262
+ walFrost: wal.toString(),
263
+ suiMist: sui.toString(),
264
+ gasBudgetMist: budget.toString(),
265
+ tipMist: tips.toString(),
266
+ bytes,
267
+ epochs,
268
+ calls,
269
+ };
270
+ }
@@ -0,0 +1,10 @@
1
+ import type { Network } from "./network.ts";
2
+ import type { SponsorFacts } from "./sponsor-check.ts";
3
+ /** Every relay's tip address that answers now, for `network`. */
4
+ export declare function readRelayTipAddresses(network: Network, extra?: readonly string[]): Promise<string[]>;
5
+ /**
6
+ * The live facts for `network`, read once and kept: the package, the system object and the tip
7
+ * addresses do not change between two transactions of one upload. `operator` is the address the
8
+ * encoded-length question is asked as (a read; nothing is signed).
9
+ */
10
+ export declare function sponsorFacts(network: Network, operator: string): Promise<SponsorFacts>;