@needmoretruth/nmts-cli 0.57.0 → 0.59.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 (56) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.ko.md +1 -1
  3. package/README.md +1 -1
  4. package/dist/arg-options.d.ts +2 -0
  5. package/dist/args.js +2 -0
  6. package/dist/artifact-about.d.ts +1 -1
  7. package/dist/commands/expiring.js +2 -2
  8. package/dist/commands/sweep.js +6 -64
  9. package/dist/commands/wallet-storage-buy.d.ts +22 -0
  10. package/dist/commands/wallet-storage-buy.js +111 -0
  11. package/dist/commands/wallet-storage-extend.d.ts +23 -0
  12. package/dist/commands/wallet-storage-extend.js +137 -0
  13. package/dist/commands/wallet.d.ts +3 -0
  14. package/dist/commands/wallet.js +5 -1
  15. package/dist/extend-chain.js +19 -3
  16. package/dist/extend-plan.d.ts +38 -0
  17. package/dist/extend-plan.js +61 -0
  18. package/dist/help-options.js +8 -3
  19. package/dist/help.js +5 -0
  20. package/dist/main.js +1 -1
  21. package/dist/platform-sign.d.ts +12 -0
  22. package/dist/platform-sign.js +29 -1
  23. package/dist/portable.d.ts +7 -2
  24. package/dist/portable.js +7 -2
  25. package/dist/product.d.ts +1 -1
  26. package/dist/product.js +1 -1
  27. package/dist/public-codes.d.ts +14 -3
  28. package/dist/public-codes.js +14 -5
  29. package/dist/rebuild.js +9 -24
  30. package/dist/risk.d.ts +12 -0
  31. package/dist/risk.js +8 -0
  32. package/dist/server-objects.d.ts +21 -0
  33. package/dist/server-objects.js +68 -0
  34. package/dist/sharing.d.ts +1 -1
  35. package/dist/sharing.js +12 -40
  36. package/dist/sponsor-check.d.ts +56 -0
  37. package/dist/sponsor-check.js +270 -0
  38. package/dist/sponsor-facts.d.ts +10 -0
  39. package/dist/sponsor-facts.js +75 -0
  40. package/dist/storage-control/buy.d.ts +65 -0
  41. package/dist/storage-control/buy.js +145 -0
  42. package/dist/storage-control/extend-for.d.ts +84 -0
  43. package/dist/storage-control/extend-for.js +204 -0
  44. package/dist/storage-control/extend.d.ts +57 -12
  45. package/dist/storage-control/extend.js +51 -45
  46. package/dist/storage-control-chain.d.ts +7 -0
  47. package/dist/storage-control-chain.js +19 -1
  48. package/dist/storage-control.d.ts +6 -2
  49. package/dist/storage-control.js +5 -2
  50. package/dist/upload-quote.d.ts +93 -0
  51. package/dist/upload-quote.js +135 -0
  52. package/dist/wallet-sign.d.ts +24 -0
  53. package/dist/wallet-sign.js +31 -1
  54. package/docs/commands/wallet.md +13 -1
  55. package/package.json +1 -1
  56. package/server.json +2 -2
package/dist/sharing.js CHANGED
@@ -8,14 +8,14 @@
8
8
  // byte — the sealing itself is `share.ts`, untouched, and its order is load-bearing.
9
9
  //
10
10
  // ⛔ THE SAME FOR EVERY KEY HOLDER. `ShareAccount.bearer` is an API key or a delegation token. A
11
- // token reaches the two sending doors only with its `share` bit AND the code's proof
12
- // (`accountProof`), so the proof is sent on those two requests and on no other. An API key is
13
- // asked for a live human check there instead, and the proof is simply not needed.
11
+ // token reaches the sending doors and the account's own code doors only with its `share` bit AND
12
+ // the code's proof (`accountProof`), so the proof is sent on those requests and on no other. An
13
+ // API key is asked for a live human check there instead, and the proof is simply not needed.
14
14
  //
15
15
  // ⛔ RECEIVING IS `sharing-inbox.ts`, re-exported here so `./share` is one entry.
16
16
  //
17
17
  // ⛔ NO `node:`, NO `Buffer`, NO `process.` — `test/portable-closure.test.ts` walks this file.
18
- import { request, ServerError } from "./api.js";
18
+ import { request } from "./api.js";
19
19
  import { fromBase64Url, toBase64Url, utf8 } from "./bytes.js";
20
20
  import { AAD, DERIVED, loadCrypto } from "./crypto.js";
21
21
  import { buildIndex, entryAt, fullPathOf, KIND_FILE, normalisePath } from "./drive-paths.js";
@@ -23,9 +23,9 @@ import { NmtsError } from "./errors.js";
23
23
  import { readFileList } from "./manifest.js";
24
24
  import { BINARY_NAME } from "./product.js";
25
25
  import { differentCode, notLiveCode, publicCodeRefusal } from "./public-code-refusals.js";
26
- import { ensureLiveCode, liveCodes, PUBLISH_TRIES } from "./public-codes.js";
26
+ import { ensureLiveCode, liveCodes } from "./public-codes.js";
27
27
  import { identityMatches, sealShare } from "./share.js";
28
- import { shareKeyRing, shareKeysAt } from "./share-codes.js";
28
+ import { shareKeysAt } from "./share-codes.js";
29
29
  export { addressFromTyped } from "./share.js";
30
30
  export { receivedShares, receiveShare } from "./sharing-inbox.js";
31
31
  /** The file at `target`, checked for the key and the hash a share carries. */
@@ -58,21 +58,19 @@ export async function shareableFileAt(account, target) {
58
58
  * Which live code sends: `as` when named, else the lowest-numbered live one — published first when
59
59
  * the account has none, as a first share does.
60
60
  *
61
- * ⚠ A DELEGATION TOKEN CANNOT READ THE CODE LIST (its business replaces a user's one code through
62
- * its own signed batch, and that list stays closed to it). So for a token the codes are asked
63
- * one number at a time at the public lookup, from 0: a revoked one answers 410, the live one 200,
64
- * and the first number never published 404 — there is nothing after it.
61
+ * ⛔ THE SAME ON EVERY ROOT. A delegation token reads the code list and publishes the
62
+ * first code with its `share` bit and the code's proof, the proof this account already carries
63
+ * for the sending door. Until 2026-11-11 a token could not, and a device whose business held no
64
+ * key had no road to a code of its own.
65
65
  */
66
66
  async function senderKeys(crypt, account, as, onFirstCode) {
67
- const door = { server: account.server, token: account.bearer };
67
+ const door = { server: account.server, token: account.bearer, accountProof: account.accountProof };
68
68
  let codes;
69
69
  try {
70
70
  ({ list: codes } = await ensureLiveCode(crypt, account.code, door, onFirstCode));
71
71
  }
72
72
  catch (error) {
73
- if (!(error instanceof ServerError && error.code === "DELEGATION_SCOPE"))
74
- throw publicCodeRefusal(error);
75
- return as === undefined ? await walkToLiveCode(crypt, account) : shareKeysAt(crypt, account.code, as);
73
+ throw publicCodeRefusal(error);
76
74
  }
77
75
  const live = liveCodes(codes);
78
76
  const sender = as === undefined ? live[0] : live.find((c) => c.index === as);
@@ -85,32 +83,6 @@ async function senderKeys(crypt, account, as, onFirstCode) {
85
83
  }
86
84
  return keys;
87
85
  }
88
- async function walkToLiveCode(crypt, account) {
89
- const ring = shareKeyRing(crypt, account.code);
90
- try {
91
- for (let index = 0; index < PUBLISH_TRIES; index += 1) {
92
- const address = toBase64Url(ring.at(index).address);
93
- try {
94
- await request(account.server, `/v1/share-recipients/${encodeURIComponent(address)}`, { token: account.bearer });
95
- return shareKeysAt(crypt, account.code, index);
96
- }
97
- catch (error) {
98
- if (error instanceof ServerError && error.status === 410)
99
- continue;
100
- if (error instanceof ServerError && error.status === 404)
101
- break;
102
- throw error;
103
- }
104
- }
105
- }
106
- finally {
107
- ring.wipe();
108
- }
109
- throw new NmtsError("This account has no public code yet, so nothing can be shared from it.", {
110
- exitCode: 4,
111
- nextStep: "Nothing was shared. The business that issued this token publishes one with setPublicCodes; then share again.",
112
- });
113
- }
114
86
  /**
115
87
  * Seal one file for one public code and send it.
116
88
  *
@@ -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>;
@@ -0,0 +1,75 @@
1
+ // The chain facts a sponsored-transaction check needs, read live for one network.
2
+ //
3
+ // ⛔ WHAT A NODE ANSWERS DOES NOT DECIDE WHAT IS SIGNED BY ITSELF. The system object is this
4
+ // package's own constant (`packageConfig`), so a call on any other object is refused whatever a
5
+ // node says. The Walrus package id is read from that object; a node that lied about it could only
6
+ // point at a call that is still handed coins of written amounts (`sponsor-check.ts`), so the most
7
+ // it could take is the policy's WAL. An operator who wants no node in that answer pins
8
+ // `walrusPackageId` in the policy.
9
+ //
10
+ // ⚠ THE RELAYS' TIP ADDRESSES COME FROM THE RELAYS THEMSELVES — the relay this tool uploads through
11
+ // and the known ones for the network. A relay that cannot be read adds no address, so a tip to it
12
+ // is refused rather than guessed; pin `relayTipAddresses` to decide them yourself.
13
+ import { parseTipConfig } from "./shared/lib/walrus/tip-config.js";
14
+ const TIP_READ_TIMEOUT_MS = 8_000;
15
+ /** Every relay's tip address that answers now, for `network`. */
16
+ export async function readRelayTipAddresses(network, extra = []) {
17
+ const { RELAY_HOSTS, relayHost } = await import("./walrus.js");
18
+ let own = null;
19
+ try {
20
+ own = relayHost(network);
21
+ }
22
+ catch {
23
+ own = null;
24
+ }
25
+ const hosts = [...new Set([...(own === null ? [] : [own]), ...(RELAY_HOSTS[network] ?? []), ...extra])];
26
+ const found = await Promise.all(hosts.map(async (host) => {
27
+ try {
28
+ const res = await fetch(new URL("/v1/tip-config", host), { signal: AbortSignal.timeout(TIP_READ_TIMEOUT_MS) });
29
+ if (!res.ok)
30
+ return null;
31
+ const tip = parseTipConfig(await res.json());
32
+ return tip.kind === "const" || tip.kind === "linear" ? tip.address : null;
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ }));
38
+ return [...new Set(found.filter((a) => a !== null && a !== ""))];
39
+ }
40
+ /**
41
+ * The live facts for `network`, read once and kept: the package, the system object and the tip
42
+ * addresses do not change between two transactions of one upload. `operator` is the address the
43
+ * encoded-length question is asked as (a read; nothing is signed).
44
+ */
45
+ export async function sponsorFacts(network, operator) {
46
+ const [{ packageConfig, payingClient, encodedLength }, { relayHost }, { walrusClient, readBlobLease }] = await Promise.all([
47
+ import("./upload-wallet-chain.js"),
48
+ import("./walrus.js"),
49
+ import("./extend-chain.js"),
50
+ ]);
51
+ const client = payingClient(network, relayHost(network));
52
+ const [system, relayTipAddresses] = await Promise.all([client.walrus.systemObject(), readRelayTipAddresses(network)]);
53
+ const lengths = new Map();
54
+ return {
55
+ walrusPackageId: system.package_id,
56
+ systemObjectId: packageConfig(network).systemObjectId,
57
+ relayTipAddresses,
58
+ async encodedLength(size) {
59
+ const known = lengths.get(size);
60
+ if (known !== undefined)
61
+ return known;
62
+ const n = await encodedLength(client, operator, size);
63
+ lengths.set(size, n);
64
+ return n;
65
+ },
66
+ async blobSize(objectId) {
67
+ try {
68
+ return (await readBlobLease(walrusClient(network), objectId)).size;
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ },
74
+ };
75
+ }
@@ -0,0 +1,65 @@
1
+ import type { ExtendWindow } from "../extend-plan.ts";
2
+ import type { Network } from "../network.ts";
3
+ import type { DryRunVerdict, StorageOpShape } from "../storage-control-chain.ts";
4
+ import { type WalletBalances } from "../wallet.ts";
5
+ import type { SignStorageOp } from "../wallet-sign-seams.ts";
6
+ import type { ReshapeContext } from "./reshape.ts";
7
+ /** One purchase, in the values it is made of. */
8
+ export interface BuyAsk {
9
+ /** The resource's size: encoded bytes, as a listing shows them. */
10
+ sizeBytes: number;
11
+ /** Storage-network epochs from the current one. Default 2, the term `put` buys. */
12
+ epochs?: number | undefined;
13
+ }
14
+ /** What one purchase would be, priced, before anything is signed. */
15
+ export interface BuyReview {
16
+ network: Network;
17
+ /** The wallet that pays and receives the resource. */
18
+ address: string;
19
+ sizeBytes: number;
20
+ epochs: number;
21
+ startEpoch: number;
22
+ endEpoch: number;
23
+ /** WAL it costs, in FROST — storage only; a resource carries no write cost until a blob is written into it. */
24
+ priceFrost: bigint;
25
+ /** The chain fee the dry run measured, in MIST. ⛔ NULL WHEN UNMEASURED, never zero. */
26
+ feeMist: bigint | null;
27
+ /** What the wallet holds. ⛔ NULL IS "NOT READ", never zero. */
28
+ walFrost: bigint | null;
29
+ suiMist: bigint | null;
30
+ /** Set when the wallet is known to be short: both numbers. A real call throws instead of signing. */
31
+ shortfall: string | null;
32
+ }
33
+ export type BuyOutcome = {
34
+ kind: "review";
35
+ review: BuyReview;
36
+ } | {
37
+ kind: "done";
38
+ review: BuyReview;
39
+ digest: string;
40
+ objectId: string | null;
41
+ };
42
+ /** The chain, as a purchase reads it. ⚠ A seam — a test hands in a table. */
43
+ export interface BuyReads {
44
+ readWindow(): Promise<ExtendWindow | null>;
45
+ /** The storage price of a resource of `sizeBytes` encoded bytes for `epochs`, in FROST. */
46
+ price(sizeBytes: number, epochs: number): Promise<bigint>;
47
+ readWallet(address: string): Promise<WalletBalances>;
48
+ walrusPackageId(): Promise<string>;
49
+ walType(): string;
50
+ systemObjectId(): string;
51
+ dryRun(shape: StorageOpShape, sender: string): Promise<DryRunVerdict>;
52
+ /** The storage resource a signed purchase created, or null when the chain did not name one. */
53
+ createdResource(digest: string): Promise<string | null>;
54
+ }
55
+ /** The chain, the signature and the gate. ⚠ Seams, not options. */
56
+ export interface BuySeams {
57
+ reads?: ((network: Network) => BuyReads | Promise<BuyReads>) | undefined;
58
+ sign?: SignStorageOp | undefined;
59
+ onReview?: ((review: BuyReview) => void) | undefined;
60
+ /** ⛔ THE GATE. Throwing here stops the run with nothing signed. */
61
+ agree?: ((review: BuyReview) => void) | undefined;
62
+ dryRun?: boolean | undefined;
63
+ }
64
+ /** Read, judge, price and — unless somebody stops it — sign one purchase of a storage resource. */
65
+ export declare function buyStorage(context: ReshapeContext, ask: BuyAsk, seams?: BuySeams): Promise<BuyOutcome>;