@wasit-dev/cli 0.8.0-beta.1 → 0.8.0-beta.2

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/dist/run.js CHANGED
@@ -11,7 +11,7 @@
11
11
  * The payment tier pays only when every one of these holds (D-022a, B3, A1):
12
12
  * the GitHub event may pay (push to the default branch, schedule,
13
13
  * workflow_dispatch on it; outside GitHub Actions always), the network is a
14
- * test network (L0; the mainnet opt-in is not part of this version), the
14
+ * test network (L0; `stellar:pubnet` pays only through `--mainnet`, below), the
15
15
  * environment has `operatedByMe: true`, the chain's key variable is set, and
16
16
  * the plan (L1) fits the caps. Then one budget is shared by every endpoint, each
17
17
  * endpoint's checks get its entry of the plan, and the pin and `maxRunUsd` come
@@ -19,27 +19,139 @@
19
19
  * run is the read-only tier and says so. A key variable that is set on a run that
20
20
  * may not pay is refused before the service starts (Najmi, 2026-11-16).
21
21
  *
22
- * `--mainnet` asks for the mainnet opt-in, which this version does not have:
23
- * the run is refused at once, exit 2, before the config is read (spec B12).
22
+ * `--mainnet` (spec B5, B18 O2) is the CLI's switch of the mainnet opt-in: an
23
+ * x402 run on `stellar:pubnet` that pays real USDC. Core opens it
24
+ * (`openMainnetOptIn`) only when every rule holds: a pubnet environment with
25
+ * `operatedByMe` and a USDC pin, the key in `WASIT_MAINNET_PAYER_SECRET` only,
26
+ * an https RPC that serves pubnet, no other mainnet run holding the lock in the
27
+ * ledger's folder, and in GitHub Actions the mainnet job rules. All of that is
28
+ * checked before a service starts or the target is asked anything. The first
29
+ * line then says MAINNET RUN; the plan reads the payer and the chain; the
30
+ * ledger takes every signature before the key signs; a refusal stops the whole
31
+ * run; L4 waits for every authorization to expire and compares the balances.
32
+ * The switch is never read from the config or the environment. Without it, a
33
+ * paying run on pubnet is refused. `--dry-run` on pubnet plans by the mainnet
34
+ * rules and reads no key.
24
35
  *
25
36
  * `executeRun` does not call `process.exit` and does not read the process: the
26
37
  * environment and the output are passed in, so it can be tested in-process.
27
38
  */
28
39
  import { readFileSync, statSync, writeFileSync } from "node:fs";
29
- import { ConfigError, ConfigurationError, MAX_BASELINE_BYTES, PER_PAYMENT_CAP_USD, RunBudget, assertPaymentNetworkAllowed, buildEndpointReport, buildRunReport, deniedEnvValues, describePlan, describeRun, errored, formatUsd, inGithubActions, isLoopbackUrl, payerKeyVariables, paymentChainFor, paymentChecksSkipped, paymentEventGate, planX402Run, readBaseline, readConfigFile, readBuildCommit, readGithubEvent, readToolVersions, redactReport, refuseMainnetSwitch, resolveRun, runExitCode, runX402PaymentChecks, runX402ReadChecks, sanitizeText, selectBaseline, skippedPaymentChecks, urlOrigin, MainnetOptInRefusedError, RpcIdentityError, UnsupportedPaymentNetworkError, assertRpcServesNetwork, } from "@wasit-dev/core";
40
+ import path from "node:path";
41
+ import { CHECK_CATALOGUE, CheckSetupError, ConfigError, ConfigurationError, MAINNET_PAYER_KEY_ENV, MAX_BASELINE_BYTES, PER_PAYMENT_CAP_USD, RunBudget, assertPaymentNetworkAllowed, buildEndpointReport, buildRunReport, closeMainnetRun, deniedEnvValues, describePlan, describeRun, errored, formatUsd, githubDefaultBranch, inGithubActions, isLoopbackUrl, mainnetFirstLine, mainnetOpeningLine, openMainnetOptIn, payerKeyVariables, paymentChainFor, paymentChecksSkipped, paymentEventGate, planMainnetDryRun, planX402Run, readBaseline, readConfigFile, readBuildCommit, readGithubEvent, readToolVersions, redactReport, resolveRun, runExitCode, runX402PaymentChecks, runX402ReadChecks, sanitizeText, selectBaseline, skipped, skippedPaymentChecks, urlOrigin, RpcIdentityError, UnsupportedPaymentNetworkError, assertMppPaymentRpc, assertX402PaymentRpc, describePaymentPlan, planPaymentRun, plannedChargeOf, runMppChannelSuite, runMppChargeSuite, } from "@wasit-dev/core";
30
42
  import { formatRun } from "./run-format.js";
31
43
  import { ServiceError, serviceUserFor, startService } from "./service.js";
32
44
  import { CLI_VERSION } from "./version.js";
33
45
  const TIER_NOTE = "Tier: read-only. The payment checks were not run, and nothing was signed.";
34
- const MPP_NOT_IN_RUN = "wasit run does not pay MPP in this version: run wasit mpp-charge or wasit mpp-channel against this endpoint";
46
+ const STELLAR_PUBNET = "stellar:pubnet";
47
+ /** MPP pays on this network only (L0; D-036). The network is the config's: `MPP_STELLAR_NETWORK` is not read. */
48
+ const MPP_NETWORK = "stellar:testnet";
49
+ /** The key variables of the MPP checks: MPP-01's payer, and the channel's commitment key (`wasit init` sets up the same ones). */
50
+ export const MPP_PAYER_KEY_ENV = "MPP_PAYER_SECRET";
51
+ export const MPP_COMMITMENT_KEY_ENV = "COMMITMENT_SECRET_HEX";
52
+ const MPP_NOT_ON_MAINNET = "MPP pays on test networks only: a mainnet run pays its x402 endpoints, so this endpoint's MPP checks were not run";
53
+ const MPP_CHANNEL_NOTE = "MPP channel: the commitments MPP-11, MPP-12 and MPP-14 sign are off-chain, and Wasit sends no transaction for " +
54
+ "them, so they are not charged to the cap. MPP-13 (close) is never run by wasit run.";
35
55
  function skippedFor(protocol, step) {
36
56
  if (step.reason === undefined && (step.kind === "read-only" || step.kind === "needs-payer")) {
37
57
  return skippedPaymentChecks(protocol, step.kind);
38
58
  }
39
59
  return paymentChecksSkipped(protocol, step.kind, step.reason ?? "the payment checks were not run");
40
60
  }
41
- /** What the run does for one endpoint. */
42
- async function runEndpoint(endpoint, step) {
61
+ /** Every check of a protocol, skipped: the endpoints of a mainnet run after it stopped. */
62
+ function everyCheckSkipped(protocol, reason) {
63
+ const why = `the mainnet run stopped, and nothing more is signed in it: ${sanitizeText(reason).slice(0, 400)}`;
64
+ // MPP-13 closes a channel for good and is never listed (report.ts).
65
+ return CHECK_CATALOGUE.filter((entry) => entry.protocol === protocol && entry.id !== "MPP-13").map((entry) => skipped(entry.id, entry.name, why));
66
+ }
67
+ /**
68
+ * Why an MPP endpoint is not sent anything: the MPP checks send a plain GET in
69
+ * this version, so a method, a body or headers the config gives it (from the
70
+ * file or `WASIT_HEADER_*`) would not reach the service, and a verdict on what
71
+ * it then answers would be about another request. Undefined when it is a plain GET.
72
+ * Names no header and no value: header values are secrets.
73
+ */
74
+ function mppShapeProblem(endpoint) {
75
+ const parts = [
76
+ ...(endpoint.method === "GET" ? [] : [`the method ${endpoint.method}`]),
77
+ ...(endpoint.body === undefined ? [] : ["a body"]),
78
+ ...(Object.keys(endpoint.headers).length === 0 ? [] : ["headers"]),
79
+ ];
80
+ if (parts.length === 0)
81
+ return undefined;
82
+ return (`wasit run sends MPP requests as a plain GET in this version, and this endpoint has ${parts.join(", ")} ` +
83
+ `(from the config or WASIT_HEADER_*): nothing was sent to it`);
84
+ }
85
+ /** The MPP charge endpoints a run can plan and pay: plain GET requests. */
86
+ function mppChargeInputs(resolved) {
87
+ return resolved.endpoints
88
+ .filter((endpoint) => endpoint.protocol === "mpp-charge" && mppShapeProblem(endpoint) === undefined)
89
+ .map((endpoint) => ({ name: endpoint.name, target: endpoint.url }));
90
+ }
91
+ /**
92
+ * The step of one MPP mode in the payment tier on an event that may pay: the
93
+ * rules of x402 (operatedByMe, the key variable) and a test network that MPP
94
+ * pays on.
95
+ */
96
+ function mppStep(resolved, env, keyEnv, keyLabel, operatorRefusal) {
97
+ if (operatorRefusal !== undefined)
98
+ return { pay: false, kind: "read-only", reason: `payment checks not run: ${operatorRefusal}` };
99
+ if (resolved.network !== MPP_NETWORK) {
100
+ return {
101
+ pay: false,
102
+ kind: "unsupported",
103
+ reason: `the MPP checks run on ${MPP_NETWORK} only, and environment ${resolved.environment} is on ${resolved.network}`,
104
+ };
105
+ }
106
+ const value = env[keyEnv];
107
+ if (value === undefined || value.trim() === "") {
108
+ return { pay: false, kind: "needs-payer", reason: `payment checks not run: no ${keyLabel}: set ${keyEnv} on the Wasit step` };
109
+ }
110
+ return { pay: true, key: value.trim() };
111
+ }
112
+ /** One MPP endpoint of a run of the payment tier on an event that may pay. */
113
+ async function runMppEndpoint(endpoint, mpp) {
114
+ const own = endpoint.protocol === "mpp-charge" ? mpp.charge : mpp.channel;
115
+ if (!own.pay)
116
+ return skippedFor(endpoint.protocol, own);
117
+ const shape = mppShapeProblem(endpoint);
118
+ if (shape !== undefined)
119
+ return paymentChecksSkipped(endpoint.protocol, "unsupported", shape);
120
+ const rpc = mpp.rpcUrl === undefined ? {} : { rpcUrl: mpp.rpcUrl };
121
+ if (endpoint.protocol === "mpp-charge") {
122
+ // Every plain MPP charge endpoint was planned; one that is not in the plan is not paid.
123
+ const entry = mpp.plan?.endpoints.find((planned) => planned.name === endpoint.name);
124
+ if (mpp.budget === undefined || entry === undefined)
125
+ throw new Error(`the plan of this run has no entry for ${endpoint.name}`);
126
+ const planned = plannedChargeOf(entry);
127
+ return runMppChargeSuite({
128
+ target: endpoint.url,
129
+ network: mpp.network,
130
+ payerSecretKey: own.key,
131
+ ...rpc,
132
+ guard: { budget: mpp.budget, ...(planned === undefined ? { notPlanned: entry.reason ?? entry.status } : { planned }) },
133
+ });
134
+ }
135
+ const results = await runMppChannelSuite({
136
+ target: endpoint.url,
137
+ commitmentSecretHex: own.key,
138
+ network: mpp.network,
139
+ ...rpc,
140
+ // The channel and its expected terms come from the config only, never from CHANNEL_CONTRACT. With a
141
+ // channel in the config, MPP-11, 12 and 14 sign commitments for that channel only.
142
+ ...(endpoint.channel === undefined ? {} : { channelOverride: endpoint.channel, onlyChannel: endpoint.channel }),
143
+ ...(endpoint.expect === undefined ? {} : { expected: endpoint.expect }),
144
+ allowDestructive: false,
145
+ });
146
+ // MPP-13 closes a channel for good: wasit run never runs it, and does not list it (report.ts).
147
+ return results.filter((result) => result.id !== "MPP-13");
148
+ }
149
+ /** What the run does for one endpoint. `mpp`: the MPP side of a run of the payment tier that may pay. */
150
+ async function runEndpoint(endpoint, step, mpp) {
151
+ // B3: once a mainnet run is stopped, every remaining check is skipped with the reason, the unpaid ones too.
152
+ const stopped = step.pay ? step.mainnet?.stopped : undefined;
153
+ if (stopped !== undefined)
154
+ return everyCheckSkipped(endpoint.protocol, stopped);
43
155
  try {
44
156
  if (endpoint.protocol === "x402") {
45
157
  const shape = {
@@ -58,6 +170,7 @@ async function runEndpoint(endpoint, step) {
58
170
  target: endpoint.url,
59
171
  network: step.network,
60
172
  payerSecretKey: step.key,
173
+ ...(step.mainnet === undefined ? {} : { mainnet: step.mainnet }),
61
174
  ...(step.rpcUrl === undefined ? {} : { rpcUrl: step.rpcUrl }),
62
175
  budget: step.budget,
63
176
  ...(step.pin === undefined ? {} : { pin: step.pin }),
@@ -69,10 +182,13 @@ async function runEndpoint(endpoint, step) {
69
182
  });
70
183
  return [...challenge, ...payment];
71
184
  }
72
- // Every MPP check pays or signs. The read-only tier has none to run, and the
73
- // payment tier of wasit run does not run them in this version.
185
+ // Every MPP check pays or signs: the payment tier on an event that may pay runs them on a test network.
186
+ if (mpp !== undefined)
187
+ return await runMppEndpoint(endpoint, mpp);
188
+ // A mainnet run pays x402 only; MPP stays on test networks (L0).
74
189
  if (step.pay)
75
- return paymentChecksSkipped(endpoint.protocol, "not-applicable", MPP_NOT_IN_RUN);
190
+ return paymentChecksSkipped(endpoint.protocol, "not-applicable", MPP_NOT_ON_MAINNET);
191
+ // The read-only tier, or an event that may not pay: none to run.
76
192
  return skippedFor(endpoint.protocol, step);
77
193
  }
78
194
  catch (error) {
@@ -100,6 +216,13 @@ function planEndpoints(resolved) {
100
216
  */
101
217
  function keyOnRefusedEvent(keys, reason) {
102
218
  const why = reason.replace(/^payment checks not run: /, "");
219
+ if (keys.includes(MAINNET_PAYER_KEY_ENV)) {
220
+ // The mainnet key has one place: a job started by hand on the default branch (spec B17.4).
221
+ return (`wasit run: ${keys.join(", ")} ${keys.length === 1 ? "is" : "are"} set, and this run may not pay (${why}). ` +
222
+ `Nothing was started, sent or signed. ${MAINNET_PAYER_KEY_ENV} belongs only to a mainnet job started by hand ` +
223
+ `(workflow_dispatch) on the default branch, as the secret of a GitHub environment limited to that branch, with a ` +
224
+ `required reviewer.`);
225
+ }
103
226
  const first = keys[0] ?? "STELLAR_PRIVATE_KEY";
104
227
  return (`wasit run: ${keys.join(", ")} ${keys.length === 1 ? "is" : "are"} set, and this run may not pay (${why}). ` +
105
228
  `Nothing was started or sent: the service of this run would run in the same job as the key. ` +
@@ -126,6 +249,11 @@ function payerAddress(chain, key) {
126
249
  return "(the key is not valid: see the results)";
127
250
  }
128
251
  }
252
+ /** MPP-01's payer for the first line of a paying run: a Stellar secret, read by core's Stellar adapter. */
253
+ function mppPayerAddress(key) {
254
+ const stellar = paymentChainFor(MPP_NETWORK);
255
+ return stellar === undefined ? "(not read)" : payerAddress(stellar, key);
256
+ }
129
257
  /** The baseline file, read; the reason when it cannot be. A file that is not there is the first run on main: no reason. */
130
258
  function readBaselineFile(path) {
131
259
  try {
@@ -145,13 +273,24 @@ function readBaselineFile(path) {
145
273
  */
146
274
  async function printPlan(resolved, stdout, clean, fail) {
147
275
  let plan;
276
+ const mainnet = resolved.network === STELLAR_PUBNET;
277
+ // MPP-01 is planned on the network MPP pays on, for the plain GET endpoints (D-036).
278
+ const mppCharge = resolved.network === MPP_NETWORK ? mppChargeInputs(resolved) : [];
148
279
  try {
149
- plan = await planX402Run({
150
- network: resolved.network,
151
- ...(resolved.pinned === undefined ? {} : { pin: resolved.pinned }),
152
- ...(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd }),
153
- endpoints: planEndpoints(resolved),
154
- });
280
+ // B5: the dry run of a mainnet run needs no opt-in, because it signs nothing, and reads no key.
281
+ plan = mainnet
282
+ ? await planMainnetDryRun({
283
+ ...(resolved.pinned === undefined ? {} : { pin: resolved.pinned }),
284
+ ...(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd }),
285
+ endpoints: planEndpoints(resolved),
286
+ })
287
+ : await planPaymentRun({
288
+ network: resolved.network,
289
+ ...(resolved.pinned === undefined ? {} : { pin: resolved.pinned }),
290
+ ...(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd }),
291
+ x402: planEndpoints(resolved),
292
+ mppCharge,
293
+ });
155
294
  }
156
295
  catch (error) {
157
296
  // L0: a network that is not a test network, refused before any request.
@@ -159,20 +298,40 @@ async function printPlan(resolved, stdout, clean, fail) {
159
298
  return fail(`wasit run --dry-run: ${error.message}`);
160
299
  throw error;
161
300
  }
162
- const lines = [...describeRun(resolved).split("\n"), ...describePlan(plan)];
301
+ const has = { x402: resolved.endpoints.some((endpoint) => endpoint.protocol === "x402"), mppCharge: mppCharge.length > 0 };
302
+ const lines = [...describeRun(resolved).split("\n"), ...(mainnet ? describePlan(plan) : describePaymentPlan(plan, has))];
163
303
  for (const endpoint of resolved.endpoints) {
164
- if (endpoint.protocol !== "x402") {
165
- lines.push(` ${endpoint.name}: not planned: the dry run plans the x402 payment checks; ${endpoint.protocol} is not planned in this version.`);
166
- }
304
+ if (endpoint.protocol === "x402")
305
+ continue;
306
+ const why = mainnet
307
+ ? "MPP pays on test networks only; a mainnet run pays its x402 endpoints."
308
+ : resolved.network !== MPP_NETWORK
309
+ ? `the MPP checks run on ${MPP_NETWORK} only, and this run is on ${resolved.network}.`
310
+ : mppShapeProblem(endpoint) !== undefined
311
+ ? `${mppShapeProblem(endpoint)}.`
312
+ : endpoint.protocol === "mpp-channel"
313
+ ? "the channel checks sign commitments off-chain, and Wasit sends no transaction for them, so they are not " +
314
+ "charged to the cap. MPP-13 (close) is never run by wasit run."
315
+ : undefined;
316
+ // A plain MPP charge endpoint on the MPP network is in the plan above.
317
+ if (why !== undefined)
318
+ lines.push(` ${endpoint.name}: not planned: ${why}`);
167
319
  }
168
320
  const refused = plan.refusal !== undefined || plan.endpoints.some((endpoint) => endpoint.status === "refused");
169
321
  if (!resolved.operatedByMe) {
170
322
  lines.push(`Refused: operatedByMe is not true for environment ${resolved.environment}, so a paying run would be ` +
171
323
  `refused: Wasit pays only a service its operator runs. Nothing was signed.`);
172
324
  }
325
+ if (mainnet) {
326
+ lines.push(`A paying run on ${STELLAR_PUBNET} needs --mainnet, its key in ${MAINNET_PAYER_KEY_ENV} only (a dry run reads ` +
327
+ `no key), and an https RPC that serves ${STELLAR_PUBNET} (rpcUrl or WASIT_RPC_URL): ` +
328
+ (resolved.rpcUrl === undefined
329
+ ? "no RPC is set, so a paying run would be refused."
330
+ : `the RPC is ${urlOrigin(resolved.rpcUrl)} (not read by a dry run).`));
331
+ }
173
332
  for (const line of lines)
174
333
  stdout(clean(line));
175
- return refused || !resolved.operatedByMe ? 2 : 0;
334
+ return refused || !resolved.operatedByMe || (mainnet && resolved.rpcUrl === undefined) ? 2 : 0;
176
335
  }
177
336
  export async function executeRun(options, context) {
178
337
  const secrets = deniedEnvValues(context.env);
@@ -182,18 +341,14 @@ export async function executeRun(options, context) {
182
341
  stderr(message);
183
342
  return 2;
184
343
  };
185
- // B12: the switch exists only to refuse. First, so nothing is read, started, sent or signed.
186
- if (options.mainnet === true) {
187
- try {
188
- refuseMainnetSwitch("--mainnet", inGithubActions(context.env) ? { event: context.env["GITHUB_EVENT_NAME"] ?? "" } : {});
189
- }
190
- catch (error) {
191
- if (error instanceof MainnetOptInRefusedError)
192
- return fail(`wasit run ${error.message}`);
193
- throw error;
194
- }
195
- }
344
+ const mainnet = options.mainnet === true;
196
345
  const dryRun = options.dryRun === true;
346
+ if (mainnet && options.readOnly) {
347
+ return fail("wasit run: --mainnet is for a paying run on stellar:pubnet: choose --mainnet or --read-only, not both.");
348
+ }
349
+ if (options.ledgerDir !== undefined && (!mainnet || dryRun)) {
350
+ return fail("wasit run: --ledger-dir is for a --mainnet run that pays: no other run writes a ledger.");
351
+ }
197
352
  if (dryRun && options.readOnly) {
198
353
  return fail("wasit run: choose --dry-run or --read-only, not both.");
199
354
  }
@@ -215,10 +370,16 @@ export async function executeRun(options, context) {
215
370
  return fail(error.message);
216
371
  throw error;
217
372
  }
373
+ // --mainnet is for stellar:pubnet only, the dry run included.
374
+ if (mainnet && resolved.network !== STELLAR_PUBNET) {
375
+ return fail(`wasit run --mainnet: A mainnet run is on ${STELLAR_PUBNET} only, and environment ${resolved.environment} is on ` +
376
+ `another network. Nothing was started, sent or signed.`);
377
+ }
218
378
  // D-022a: which GitHub events may pay. A key given to a run that may not pay is
219
379
  // refused here, before the service of this run (code that may not be reviewed
220
380
  // yet) starts in the same job as the key. Every tier, the read-only one too.
221
- const gate = paymentEventGate(context.env, readGithubEvent(context.env));
381
+ const event = readGithubEvent(context.env);
382
+ const gate = paymentEventGate(context.env, event);
222
383
  if (gate.ciOutsideGithub === true) {
223
384
  // In a CI that is not GitHub Actions the payment tier does not run at all, and
224
385
  // no tier runs beside a payer key (Najmi, 2026-11-17, review R9 a).
@@ -230,11 +391,25 @@ export async function executeRun(options, context) {
230
391
  const keys = payerKeyVariables(context.env);
231
392
  if (keys.length > 0)
232
393
  return fail(keyOnRefusedEvent(keys, gate.reason ?? "this event"));
394
+ // A mainnet run is never turned into the read-only tier: it stops, and says why.
395
+ if (mainnet && !dryRun) {
396
+ return fail(`wasit run --mainnet: this run may not pay (${(gate.reason ?? "this event").replace(/^payment checks not run: /, "")}). ` +
397
+ `In GitHub Actions a mainnet run is started by hand (workflow_dispatch) on the default branch. ` +
398
+ `Nothing was started, sent or signed.`);
399
+ }
233
400
  }
401
+ // The mainnet run (spec B5): its own path, opened by core before anything is started or sent.
402
+ if (mainnet && !dryRun)
403
+ return executeMainnetRun(options, context, resolved, event, { clean, stderr, fail, secrets });
234
404
  // The payment tier: neither --read-only nor --dry-run. On an event that may not
235
405
  // pay it is the read-only tier, and the report says why.
236
406
  const paymentAsked = !options.readOnly && !dryRun;
237
407
  const paying = paymentAsked && gate.allowed;
408
+ // Without its switch, a paying run on mainnet is refused before anything is started or sent.
409
+ if (paying && resolved.network === STELLAR_PUBNET) {
410
+ return fail(`wasit run: ${STELLAR_PUBNET} is Stellar mainnet: a paying run there needs --mainnet, and every rule of the ` +
411
+ `mainnet opt-in (see wasit run --help). Nothing was started, sent or signed.`);
412
+ }
238
413
  const chain = paying ? paymentChainFor(resolved.network) : undefined;
239
414
  if (paying && (chain !== undefined || resolved.networkClass !== "unknown")) {
240
415
  // L0, before the service starts or anything is sent: a test network only.
@@ -251,71 +426,56 @@ export async function executeRun(options, context) {
251
426
  const keyValue = keyEnv === undefined ? undefined : context.env[keyEnv];
252
427
  const key = keyValue === undefined || keyValue.trim() === "" ? undefined : keyValue;
253
428
  const hasX402 = resolved.endpoints.some((endpoint) => endpoint.protocol === "x402");
254
- /** Why the payment tier that was asked for does not pay, on an event that may pay. */
429
+ const operatorRefusal = paying && !resolved.operatedByMe
430
+ ? `operatedByMe is not true for environment ${resolved.environment}: Wasit pays only a service its operator runs`
431
+ : undefined;
432
+ /** Why the x402 payment checks that were asked for do not pay, on an event that may pay. */
255
433
  const notPaid = !paying
256
434
  ? undefined
257
- : !resolved.operatedByMe
258
- ? `operatedByMe is not true for environment ${resolved.environment}: Wasit pays only a service its operator runs`
259
- : chain !== undefined && key === undefined
260
- ? `no payer key: set ${keyEnv} on the Wasit step`
261
- : undefined;
262
- // D-023a+b: a run that will pay checks its RPC before the service starts or
263
- // anything is sent to it: the payments are built and their settlements read
264
- // through it, so it must serve the run's own network.
265
- if (paying && notPaid === undefined && chain !== undefined && key !== undefined && hasX402) {
435
+ : (operatorRefusal ?? (hasX402 && chain !== undefined && key === undefined ? `no payer key: set ${keyEnv} on the Wasit step` : undefined));
436
+ // The MPP side (W3-1, D-036): each mode by the same rules, on the network MPP pays on, with its own key variable.
437
+ const mppSteps = paying
438
+ ? {
439
+ charge: mppStep(resolved, context.env, MPP_PAYER_KEY_ENV, "payer key", operatorRefusal),
440
+ channel: mppStep(resolved, context.env, MPP_COMMITMENT_KEY_ENV, "commitment key", operatorRefusal),
441
+ }
442
+ : undefined;
443
+ const mppChargePays = mppSteps?.charge.pay === true && mppChargeInputs(resolved).length > 0;
444
+ const mppChannelPays = mppSteps?.channel.pay === true &&
445
+ resolved.endpoints.some((endpoint) => endpoint.protocol === "mpp-channel" && mppShapeProblem(endpoint) === undefined);
446
+ // D-023 for MPP: the payments are built, the commitments prepared and the settlements read through the RPC, so
447
+ // it is checked before the service starts or any endpoint is asked anything.
448
+ if (mppChargePays || mppChannelPays) {
266
449
  try {
267
- await assertRpcServesNetwork(resolved.network, chain.resolveRpcUrl(resolved.network, resolved.rpcUrl));
450
+ await assertMppPaymentRpc(MPP_NETWORK, resolved.rpcUrl, { charge: mppChargePays });
268
451
  }
269
452
  catch (error) {
270
- if (error instanceof RpcIdentityError)
453
+ if (error instanceof ConfigurationError)
271
454
  return fail(`wasit run: ${error.message} The service was not started.`);
272
455
  throw error;
273
456
  }
274
457
  }
275
- // The decision is the CLI's, in one place: --start always starts, --start-if-local starts only
276
- // when service.start is set and the environment is on this machine, and says which it did.
277
- let shouldStart = options.start;
278
- if (options.startIfLocal === true) {
279
- const origin = urlOrigin(resolved.baseUrl);
280
- if (resolved.service?.start === undefined) {
281
- stderr(`wasit run: service.start is not set, so ${origin} is read as it is.`);
282
- }
283
- else if (!isLoopbackUrl(resolved.baseUrl)) {
284
- stderr(`wasit run: environment ${resolved.environment} is at ${origin}, not on this machine, ` +
285
- `so service.start is not used and ${origin} is read as it is.`);
286
- }
287
- else {
288
- shouldStart = true;
289
- }
290
- }
291
- let service;
292
- // D-022a option 2: on a GitHub-hosted runner, a service started while a payer key is set runs as its own user.
293
- const serviceUser = serviceUserFor(context.env);
294
- if (shouldStart) {
295
- const { start, ready } = resolved.service ?? {};
296
- if (start === undefined) {
297
- return fail("wasit run --start needs service.start in the config: the command that starts the service.");
298
- }
299
- if (ready === undefined) {
300
- return fail("wasit run --start needs service.ready in the config: the url on this machine to wait for, " +
301
- 'for example { "url": "http://127.0.0.1:3000/", "timeoutSeconds": 60 }.');
302
- }
458
+ // D-023a+b: a run that will pay checks its RPC before the service starts or
459
+ // anything is sent to it: the payments are built and the settlements read
460
+ // through it, so it must be one the x402 client accepts (https on Stellar)
461
+ // and serve the run's own network.
462
+ if (paying && notPaid === undefined && chain !== undefined && key !== undefined && hasX402) {
303
463
  try {
304
- service = await startService({
305
- command: start,
306
- ready,
307
- env: context.env,
308
- log: (line) => context.stderr(line),
309
- ...(context.cwd === undefined ? {} : { cwd: context.cwd }),
310
- ...(serviceUser === undefined ? {} : { separateUser: { name: serviceUser, ...(context.sudo === undefined ? {} : { sudo: context.sudo }) } }),
311
- });
464
+ await assertX402PaymentRpc(resolved.network, chain.resolveRpcUrl(resolved.network, resolved.rpcUrl));
312
465
  }
313
466
  catch (error) {
314
- if (error instanceof ServiceError)
315
- return fail(error.message);
467
+ if (error instanceof RpcIdentityError)
468
+ return fail(`wasit run: ${error.message} The service was not started.`);
316
469
  throw error;
317
470
  }
318
471
  }
472
+ const decision = startDecision(options, resolved);
473
+ for (const note of decision.notes)
474
+ stderr(note);
475
+ const started = await startIfAsked(decision.start, resolved, context, fail);
476
+ if (typeof started === "number")
477
+ return started;
478
+ const service = started;
319
479
  if (dryRun) {
320
480
  try {
321
481
  return await printPlan(resolved, context.stdout, clean, fail);
@@ -331,6 +491,7 @@ export async function executeRun(options, context) {
331
491
  let step;
332
492
  let tierNote;
333
493
  let budget;
494
+ let mpp;
334
495
  if (!paymentAsked) {
335
496
  step = { pay: false, kind: "read-only" };
336
497
  tierNote = TIER_NOTE;
@@ -340,50 +501,79 @@ export async function executeRun(options, context) {
340
501
  step = { pay: false, kind: "read-only", reason };
341
502
  tierNote = `Tier: read-only (${reason}). Nothing was signed.`;
342
503
  }
343
- else if (notPaid !== undefined) {
344
- step = { pay: false, kind: resolved.operatedByMe ? "needs-payer" : "read-only", reason: `payment checks not run: ${notPaid}` };
345
- tierNote = `Tier: payment on ${resolved.network}, and the payment checks were not run: ${notPaid}. Nothing was signed.`;
346
- }
347
- else if (chain === undefined || key === undefined) {
348
- // No payment adapter for this network: the payment group is unsupported (spec A3), so the
349
- // endpoint has no verdict (Najmi, 2026-11-15). Nothing is fetched for it beyond the challenge.
350
- step = { pay: false, kind: "unsupported", reason: new UnsupportedPaymentNetworkError(resolved.network).message };
351
- tierNote = `Tier: payment on ${resolved.network}, a network Wasit does not pay on. Nothing was signed.`;
352
- }
353
504
  else {
354
- // L1: the plan, read before anything is signed. A run above its cap does not start.
355
- const plan = await planX402Run({
356
- network: resolved.network,
357
- ...(resolved.pinned === undefined ? {} : { pin: resolved.pinned }),
358
- ...(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd }),
359
- endpoints: planEndpoints(resolved),
360
- });
361
- if (plan.refusal !== undefined) {
362
- for (const line of describePlan(plan))
363
- stderr(line);
364
- return fail(`wasit run: ${plan.refusal}`);
505
+ // The payment tier on an event that may pay. L1 first: one plan of everything the run may sign (the x402
506
+ // payment checks it can pay, and MPP-01), read before anything is signed. A run above its cap does not start.
507
+ const x402Pays = hasX402 && notPaid === undefined && chain !== undefined && key !== undefined;
508
+ const charges = mppChargePays ? mppChargeInputs(resolved) : [];
509
+ let plan;
510
+ if (x402Pays || charges.length > 0) {
511
+ plan = await planPaymentRun({
512
+ network: resolved.network,
513
+ ...(resolved.pinned === undefined ? {} : { pin: resolved.pinned }),
514
+ ...(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd }),
515
+ x402: x402Pays ? planEndpoints(resolved) : [],
516
+ mppCharge: charges,
517
+ });
518
+ const has = { x402: x402Pays, mppCharge: charges.length > 0 };
519
+ if (plan.refusal !== undefined) {
520
+ for (const line of describePaymentPlan(plan, has))
521
+ stderr(line);
522
+ return fail(`wasit run: ${plan.refusal}`);
523
+ }
524
+ budget = new RunBudget(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd });
525
+ const payers = [
526
+ ...(x402Pays && chain !== undefined && key !== undefined ? [`Payer ${payerAddress(chain, key)}`] : []),
527
+ ...(mppSteps?.charge.pay === true && charges.length > 0 ? [`MPP-01 payer ${mppPayerAddress(mppSteps.charge.key)}`] : []),
528
+ ];
529
+ say(`Payment tier on ${resolved.network} (test network): test funds. ${payers.join("; ")}; ` +
530
+ `at most ${formatUsd(plan.perPaymentCapUsd)} per payment; this run could spend up to ` +
531
+ `${formatUsd(plan.worstCaseUsd)} of the ${formatUsd(budget.capUsd)} cap.`);
532
+ for (const line of describePaymentPlan(plan, has).slice(1))
533
+ say(line);
534
+ }
535
+ if (notPaid !== undefined) {
536
+ step = { pay: false, kind: resolved.operatedByMe ? "needs-payer" : "read-only", reason: `payment checks not run: ${notPaid}` };
537
+ tierNote = `Tier: payment on ${resolved.network}, and the payment checks were not run: ${notPaid}. Nothing was signed.`;
538
+ }
539
+ else if (!hasX402) {
540
+ // No x402 endpoint: the step is never used for one.
541
+ step = { pay: false, kind: "not-applicable", reason: "payment checks not run: no x402 endpoint" };
542
+ tierNote = "";
543
+ }
544
+ else if (chain === undefined || key === undefined || plan === undefined || budget === undefined) {
545
+ // No payment adapter for this network: the payment group is unsupported (spec A3), so the
546
+ // endpoint has no verdict (Najmi, 2026-11-15). Nothing is fetched for it beyond the challenge.
547
+ step = { pay: false, kind: "unsupported", reason: new UnsupportedPaymentNetworkError(resolved.network).message };
548
+ tierNote = `Tier: payment on ${resolved.network}, a network Wasit does not pay on. Nothing was signed.`;
549
+ }
550
+ else {
551
+ step = {
552
+ pay: true,
553
+ network: resolved.network,
554
+ key,
555
+ ...(resolved.rpcUrl === undefined ? {} : { rpcUrl: resolved.rpcUrl }),
556
+ budget,
557
+ ...(resolved.pinned === undefined ? {} : { pin: resolved.pinned }),
558
+ plan,
559
+ progress: say,
560
+ };
561
+ tierNote = "";
562
+ }
563
+ if (mppSteps !== undefined) {
564
+ mpp = {
565
+ network: resolved.network,
566
+ ...(resolved.rpcUrl === undefined ? {} : { rpcUrl: resolved.rpcUrl }),
567
+ charge: mppSteps.charge,
568
+ channel: mppSteps.channel,
569
+ ...(budget === undefined ? {} : { budget }),
570
+ ...(plan === undefined ? {} : { plan }),
571
+ };
365
572
  }
366
- budget = new RunBudget(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd });
367
- say(`Payment tier on ${resolved.network} (test network): test funds. Payer ${payerAddress(chain, key)}; ` +
368
- `at most ${formatUsd(plan.perPaymentCapUsd)} per payment; this run could spend up to ` +
369
- `${formatUsd(plan.worstCaseUsd)} of the ${formatUsd(budget.capUsd)} cap.`);
370
- for (const line of describePlan(plan).slice(1))
371
- say(line);
372
- step = {
373
- pay: true,
374
- network: resolved.network,
375
- key,
376
- ...(resolved.rpcUrl === undefined ? {} : { rpcUrl: resolved.rpcUrl }),
377
- budget,
378
- ...(resolved.pinned === undefined ? {} : { pin: resolved.pinned }),
379
- plan,
380
- progress: say,
381
- };
382
- tierNote = "";
383
573
  }
384
574
  const endpoints = [];
385
575
  for (const endpoint of resolved.endpoints) {
386
- const results = await runEndpoint(endpoint, step);
576
+ const results = await runEndpoint(endpoint, step, mpp);
387
577
  endpoints.push(buildEndpointReport({
388
578
  name: endpoint.name,
389
579
  protocol: endpoint.protocol,
@@ -398,46 +588,268 @@ export async function executeRun(options, context) {
398
588
  `Tier: payment on ${resolved.network}. The run charged ${formatUsd(budget.spentUsd)} of the ` +
399
589
  `${formatUsd(budget.capUsd)} cap, at most $${PER_PAYMENT_CAP_USD}.00 a payment; every signature is counted as if it settled.`;
400
590
  }
401
- const input = {
402
- environment: resolved.environment,
403
- network: resolved.network,
404
- startedAt,
405
- versions: readToolVersions(CLI_VERSION, readBuildCommit(context.env)),
406
- endpoints,
407
- };
408
- const preliminary = buildRunReport({ ...input, notes: [tierNote] });
409
- const selected = selectBaseline(preliminary, options.baseline === undefined ? undefined : readBaselineFile(options.baseline));
410
- const report = redactReport(selected.note === undefined
411
- ? preliminary
412
- : buildRunReport({ ...input, notes: [tierNote, `Baseline not used: ${selected.note}.`] }), secrets);
413
- let verdict = runExitCode(report, selected.baseline?.report);
591
+ else if (tierNote === "") {
592
+ tierNote = `Tier: payment on ${resolved.network}. No payment was planned, so nothing was charged to the cap.`;
593
+ }
594
+ // The MPP side: what it signed beside the cap, and why a mode the run has did not run.
595
+ const hasCharge = resolved.endpoints.some((endpoint) => endpoint.protocol === "mpp-charge");
596
+ const hasChannel = resolved.endpoints.some((endpoint) => endpoint.protocol === "mpp-channel");
597
+ const mppNotes = [];
598
+ /** Why a mode the run has did not pay on an event that may pay, for lack of a key or of operatedByMe: not green. */
599
+ const unpaid = new Set(notPaid !== undefined && hasX402 ? [notPaid] : []);
600
+ for (const [has, label, own] of [
601
+ [hasCharge, "MPP charge", mpp?.charge],
602
+ [hasChannel, "MPP channel", mpp?.channel],
603
+ ]) {
604
+ if (!has || own === undefined || own.pay)
605
+ continue;
606
+ if (own.kind === "needs-payer" || own.kind === "read-only") {
607
+ const why = (own.reason ?? "").replace(/^payment checks not run: /, "");
608
+ unpaid.add(why);
609
+ if (notPaid !== why)
610
+ mppNotes.push(`${label}: the payment checks were not run: ${why}.`);
611
+ }
612
+ }
613
+ if (hasChannel && mpp?.channel.pay === true)
614
+ mppNotes.push(MPP_CHANNEL_NOTE);
615
+ const firstUnpaid = [...unpaid][0];
616
+ return writeReport({ options, context, resolved, startedAt, endpoints, notes: [tierNote, ...mppNotes], secrets, clean, fail }, (verdict) =>
414
617
  // The payment tier was asked for on an event that may pay and did not pay:
415
618
  // not green (a FAIL still outranks it).
416
- if (notPaid !== undefined && hasX402 && verdict.code === 0) {
417
- verdict = { ...verdict, code: 2, reason: `the payment tier was asked for and its payment checks were not run: ${notPaid}` };
619
+ firstUnpaid !== undefined && verdict.code === 0
620
+ ? { ...verdict, code: 2, reason: `the payment tier was asked for and its payment checks were not run: ${firstUnpaid}` }
621
+ : verdict);
622
+ }
623
+ finally {
624
+ await service?.stop();
625
+ }
626
+ }
627
+ /** Whether this run starts `service.start`, and the notes that say why not. */
628
+ function startDecision(options, resolved) {
629
+ // The decision is the CLI's, in one place: --start always starts, --start-if-local starts only
630
+ // when service.start is set and the environment is on this machine, and says which it did.
631
+ const notes = [];
632
+ let start = options.start;
633
+ if (options.startIfLocal === true) {
634
+ const origin = urlOrigin(resolved.baseUrl);
635
+ if (resolved.service?.start === undefined) {
636
+ notes.push(`wasit run: service.start is not set, so ${origin} is read as it is.`);
418
637
  }
419
- const json = `${JSON.stringify(report, null, 2)}\n`;
420
- if (options.out !== undefined) {
421
- try {
422
- writeFileSync(options.out, json);
423
- }
424
- catch (error) {
425
- const code = error.code;
426
- return fail(`wasit run: cannot write ${options.out}${typeof code === "string" ? ` (${code})` : ""}`);
638
+ else if (!isLoopbackUrl(resolved.baseUrl)) {
639
+ notes.push(`wasit run: environment ${resolved.environment} is at ${origin}, not on this machine, ` +
640
+ `so service.start is not used and ${origin} is read as it is.`);
641
+ }
642
+ else {
643
+ start = true;
644
+ }
645
+ }
646
+ return { start, notes };
647
+ }
648
+ /** Starts the service when asked: the service, undefined when not asked, or the exit code of a failure. */
649
+ async function startIfAsked(start, resolved, context, fail) {
650
+ if (!start)
651
+ return undefined;
652
+ const { start: command, ready } = resolved.service ?? {};
653
+ if (command === undefined) {
654
+ return fail("wasit run --start needs service.start in the config: the command that starts the service.");
655
+ }
656
+ if (ready === undefined) {
657
+ return fail("wasit run --start needs service.ready in the config: the url on this machine to wait for, " +
658
+ 'for example { "url": "http://127.0.0.1:3000/", "timeoutSeconds": 60 }.');
659
+ }
660
+ // D-022a option 2: on a GitHub-hosted runner, a service started while a payer key is set runs as its own user.
661
+ const serviceUser = serviceUserFor(context.env);
662
+ try {
663
+ return await startService({
664
+ command,
665
+ ready,
666
+ env: context.env,
667
+ log: (line) => context.stderr(line),
668
+ ...(context.cwd === undefined ? {} : { cwd: context.cwd }),
669
+ ...(serviceUser === undefined ? {} : { separateUser: { name: serviceUser, ...(context.sudo === undefined ? {} : { sudo: context.sudo }) } }),
670
+ });
671
+ }
672
+ catch (error) {
673
+ if (error instanceof ServiceError)
674
+ return fail(error.message);
675
+ throw error;
676
+ }
677
+ }
678
+ /** Builds, writes and prints the report; returns the exit code, after `adjust` has had its say. */
679
+ function writeReport(input, adjust = (verdict) => verdict) {
680
+ const { options, context, resolved, startedAt, endpoints, notes, secrets, clean, fail } = input;
681
+ const base = {
682
+ environment: resolved.environment,
683
+ network: resolved.network,
684
+ startedAt,
685
+ versions: readToolVersions(CLI_VERSION, readBuildCommit(context.env)),
686
+ endpoints,
687
+ };
688
+ const preliminary = buildRunReport({ ...base, notes: [...notes] });
689
+ const selected = selectBaseline(preliminary, options.baseline === undefined ? undefined : readBaselineFile(options.baseline));
690
+ const report = redactReport(selected.note === undefined ? preliminary : buildRunReport({ ...base, notes: [...notes, `Baseline not used: ${selected.note}.`] }), [...secrets]);
691
+ const verdict = adjust(runExitCode(report, selected.baseline?.report));
692
+ const json = `${JSON.stringify(report, null, 2)}\n`;
693
+ if (options.out !== undefined) {
694
+ try {
695
+ writeFileSync(options.out, json);
696
+ }
697
+ catch (error) {
698
+ const code = error.code;
699
+ return fail(`wasit run: cannot write ${options.out}${typeof code === "string" ? ` (${code})` : ""}`);
700
+ }
701
+ }
702
+ if (options.json) {
703
+ context.stdout(json.trimEnd());
704
+ // The JSON says what was found; this line says what the exit code is and why, for a log.
705
+ context.stderr(clean(`Result: ${verdict.reason} (exit ${verdict.code}).`));
706
+ }
707
+ else {
708
+ for (const line of formatRun(resolved, report, verdict))
709
+ context.stdout(clean(line));
710
+ }
711
+ return verdict.code;
712
+ }
713
+ /** What L4 found, in one line for the run's output. */
714
+ function ledgerLine(close) {
715
+ const file = close.ledgerPath ?? "(no ledger)";
716
+ const consistency = close.consistency;
717
+ if (consistency === undefined)
718
+ return `Ledger: none was opened, so nothing was signed. ${close.problem ?? ""}`.trim();
719
+ if (consistency.result === "consistent") {
720
+ return (`Ledger: consistent: the payer's USDC went down by exactly the settlements this run verified ` +
721
+ `(${consistency.settledUsdc} base units), and its XLM did not move. ${file}`);
722
+ }
723
+ if (consistency.result === "explained")
724
+ return `Ledger: explained: ${consistency.reasons.join(" ")} ${file}`.replace(/\s+/g, " ").trim();
725
+ return `Ledger: INCONSISTENT: ${consistency.reasons.join(" ")} ${close.problem ?? ""} ${file}`.replace(/\s+/g, " ").trim();
726
+ }
727
+ /**
728
+ * `wasit run --mainnet` (spec B5, B18 O2). Core opens the opt-in before a
729
+ * service starts or the target is asked anything; every refusal before that is
730
+ * exit 2 with nothing started, sent or signed. Once it is open, its opt-in is
731
+ * closed on every way out: L4 waits for the run's authorizations to expire,
732
+ * compares the balances after with the ledger, and releases the lock.
733
+ */
734
+ async function executeMainnetRun(options, context, resolved, event, output) {
735
+ const { clean, stderr, fail, secrets } = output;
736
+ const cwd = context.cwd ?? process.cwd();
737
+ const ledgerDir = path.resolve(cwd, options.ledgerDir ?? ".");
738
+ const decision = startDecision(options, resolved);
739
+ const workspace = context.env["GITHUB_WORKSPACE"];
740
+ const installDirs = [
741
+ ...(workspace === undefined || workspace.trim() === "" ? [] : [{ label: "GITHUB_WORKSPACE", dir: workspace }]),
742
+ { label: "the config's directory", dir: path.dirname(path.resolve(cwd, options.config)) },
743
+ ];
744
+ let optIn;
745
+ try {
746
+ optIn = await openMainnetOptIn({
747
+ frontEnd: "cli",
748
+ env: context.env,
749
+ environment: resolved.environment,
750
+ network: resolved.network,
751
+ operatedByMe: resolved.operatedByMe,
752
+ pin: resolved.pinned,
753
+ rpcUrl: resolved.rpcUrl,
754
+ ledgerDir,
755
+ ...(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd }),
756
+ ...(inGithubActions(context.env)
757
+ ? { job: { defaultBranch: githubDefaultBranch(event), startsService: decision.start, baseUrl: resolved.baseUrl, installDirs } }
758
+ : {}),
759
+ });
760
+ }
761
+ catch (error) {
762
+ if (error instanceof ConfigurationError)
763
+ return fail(`wasit run --mainnet: ${error.message}`);
764
+ throw error;
765
+ }
766
+ // Lines about money go where the report is not: stderr with --json, else stdout.
767
+ const say = (line) => (options.json ? stderr(line) : context.stdout(clean(line)));
768
+ let service;
769
+ let close;
770
+ try {
771
+ // B5: a mainnet run says so in its first line, before a service starts or the target is asked anything.
772
+ say(mainnetOpeningLine(optIn));
773
+ for (const note of decision.notes)
774
+ stderr(note);
775
+ const started = await startIfAsked(decision.start, resolved, context, fail);
776
+ if (typeof started === "number")
777
+ return started;
778
+ service = started;
779
+ const startedAt = (context.now?.() ?? new Date()).toISOString();
780
+ let plan;
781
+ try {
782
+ // L1: the payer's balances, the token's decimals and the latest ledger first, then every endpoint.
783
+ plan = await planX402Run({ network: resolved.network, endpoints: planEndpoints(resolved), mainnet: optIn });
784
+ }
785
+ catch (error) {
786
+ if (error instanceof ConfigurationError || error instanceof CheckSetupError)
787
+ return fail(`wasit run --mainnet: ${error.message}`);
788
+ throw error;
789
+ }
790
+ if (plan.refusal !== undefined) {
791
+ for (const line of describePlan(plan))
792
+ stderr(line);
793
+ return fail(`wasit run --mainnet: ${plan.refusal}`);
794
+ }
795
+ say(mainnetFirstLine(plan));
796
+ for (const line of describePlan(plan).slice(1))
797
+ say(line);
798
+ // The ledger's header names the versions flat: "wasit.cli", "sdk.@x402/core" and so on.
799
+ const versions = {};
800
+ for (const [group, entries] of Object.entries(readToolVersions(CLI_VERSION, readBuildCommit(context.env)))) {
801
+ for (const [name, value] of Object.entries(entries)) {
802
+ if (value !== undefined)
803
+ versions[`${group}.${name}`] = String(value);
427
804
  }
428
805
  }
429
- if (options.json) {
430
- context.stdout(json.trimEnd());
431
- // The JSON says what was found; this line says what the exit code is and why, for a log.
432
- context.stderr(clean(`Result: ${verdict.reason} (exit ${verdict.code}).`));
806
+ let ledgerPath;
807
+ try {
808
+ ledgerPath = optIn.openLedger(versions).path;
433
809
  }
434
- else {
435
- for (const line of formatRun(resolved, report, verdict))
436
- context.stdout(clean(line));
810
+ catch (error) {
811
+ if (error instanceof ConfigurationError || error instanceof CheckSetupError)
812
+ return fail(`wasit run --mainnet: ${error.message}`);
813
+ throw error;
814
+ }
815
+ say(`Ledger: ${ledgerPath}: every signature is written there before the key signs.`);
816
+ // The key, read at the moment of use from its one variable (B5, B6); core holds it to the opt-in's payer.
817
+ const key = (context.env[MAINNET_PAYER_KEY_ENV] ?? "").trim();
818
+ const step = { pay: true, network: resolved.network, key, budget: optIn.budget, plan, progress: say, mainnet: optIn };
819
+ const endpoints = [];
820
+ for (const endpoint of resolved.endpoints) {
821
+ const results = await runEndpoint(endpoint, step);
822
+ endpoints.push(buildEndpointReport({ name: endpoint.name, protocol: endpoint.protocol, method: endpoint.method, path: endpoint.path, results }));
437
823
  }
438
- return verdict.code;
824
+ // L4: every authorization expired, the balances after read, the ledger closed, the lock released.
825
+ close = await closeMainnetRun(optIn, { ...(context.sleep === undefined ? {} : { sleep: context.sleep }), onProgress: say });
826
+ say(ledgerLine(close));
827
+ const stopped = optIn.stopped;
828
+ if (stopped !== undefined)
829
+ stderr(`wasit run --mainnet: the run stopped: ${stopped}`);
830
+ // Explained: the payer paid more than the verified settlements, within the payments of checks that FAILed.
831
+ const ledgerResult = close.consistency?.result ?? "inconsistent";
832
+ const notes = [
833
+ `Tier: MAINNET payment on ${resolved.network}: real funds. The run charged ${formatUsd(optIn.budget.spentUsd)} of the ` +
834
+ `${formatUsd(optIn.budget.capUsd)} cap, at most $${PER_PAYMENT_CAP_USD}.00 a payment; every signature is counted as if it settled.`,
835
+ `Run ledger ${path.basename(ledgerPath)}: ${ledgerResult} with the payer's balances on public Horizon.`,
836
+ ...(stopped === undefined ? [] : [`The mainnet run stopped: ${stopped}`]),
837
+ ];
838
+ return writeReport({ options, context, resolved, startedAt, endpoints, notes, secrets, clean, fail }, (verdict) => {
839
+ // B3: a mainnet run that stopped exits 2, and so does one whose ledger does not match the chain. An
840
+ // explained ledger exits by the checks: the FAILs that explain it are the run's verdict.
841
+ if (stopped !== undefined)
842
+ return { ...verdict, code: 2, reason: `the mainnet run stopped: ${stopped}` };
843
+ if (ledgerResult === "inconsistent")
844
+ return { ...verdict, code: 2, reason: "the run ledger is not consistent with the payer's balances" };
845
+ return verdict;
846
+ });
439
847
  }
440
848
  finally {
849
+ // Every way out closes the opt-in; a run that signed waits for its authorizations first.
850
+ if (close === undefined) {
851
+ await closeMainnetRun(optIn, { ...(context.sleep === undefined ? {} : { sleep: context.sleep }), onProgress: say });
852
+ }
441
853
  await service?.stop();
442
854
  }
443
855
  }