@wasit-dev/cli 0.7.0 → 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 ADDED
@@ -0,0 +1,855 @@
1
+ /**
2
+ * `wasit run`: the endpoints of a `wasit.config.json`, one after another, with
3
+ * one report (spec A2, A8).
4
+ *
5
+ * Three tiers. `--read-only`: an x402 endpoint gets its unpaid challenge checks
6
+ * (X402-01..05); its payment checks, and every MPP check, are reported as
7
+ * skipped for the tier, so the report says which checks need a payer.
8
+ * `--dry-run` (spec B5): L0 and L1 only, the plan of the payment checks
9
+ * printed; no key, no payment, no signature. Neither flag: the payment tier.
10
+ *
11
+ * The payment tier pays only when every one of these holds (D-022a, B3, A1):
12
+ * the GitHub event may pay (push to the default branch, schedule,
13
+ * workflow_dispatch on it; outside GitHub Actions always), the network is a
14
+ * test network (L0; `stellar:pubnet` pays only through `--mainnet`, below), the
15
+ * environment has `operatedByMe: true`, the chain's key variable is set, and
16
+ * the plan (L1) fits the caps. Then one budget is shared by every endpoint, each
17
+ * endpoint's checks get its entry of the plan, and the pin and `maxRunUsd` come
18
+ * from the config; L2 and L3 hold every signature in core. On a pull request the
19
+ * run is the read-only tier and says so. A key variable that is set on a run that
20
+ * may not pay is refused before the service starts (Najmi, 2026-11-16).
21
+ *
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.
35
+ *
36
+ * `executeRun` does not call `process.exit` and does not read the process: the
37
+ * environment and the output are passed in, so it can be tested in-process.
38
+ */
39
+ import { readFileSync, statSync, writeFileSync } from "node:fs";
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";
42
+ import { formatRun } from "./run-format.js";
43
+ import { ServiceError, serviceUserFor, startService } from "./service.js";
44
+ import { CLI_VERSION } from "./version.js";
45
+ const TIER_NOTE = "Tier: read-only. The payment checks were not run, and nothing was signed.";
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.";
55
+ function skippedFor(protocol, step) {
56
+ if (step.reason === undefined && (step.kind === "read-only" || step.kind === "needs-payer")) {
57
+ return skippedPaymentChecks(protocol, step.kind);
58
+ }
59
+ return paymentChecksSkipped(protocol, step.kind, step.reason ?? "the payment checks were not run");
60
+ }
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);
155
+ try {
156
+ if (endpoint.protocol === "x402") {
157
+ const shape = {
158
+ method: endpoint.method,
159
+ ...(endpoint.body === undefined ? {} : { body: endpoint.body }),
160
+ ...(Object.keys(endpoint.headers).length === 0 ? {} : { headers: endpoint.headers }),
161
+ };
162
+ const challenge = await runX402ReadChecks({ target: endpoint.url, ...shape });
163
+ if (!step.pay)
164
+ return [...challenge, ...skippedFor("x402", step)];
165
+ // Every endpoint of the run was planned; one that is not in the plan is not paid.
166
+ const plan = step.plan.endpoints.find((entry) => entry.name === endpoint.name);
167
+ if (plan === undefined)
168
+ throw new Error(`the plan of this run has no entry for ${endpoint.name}`);
169
+ const payment = await runX402PaymentChecks({
170
+ target: endpoint.url,
171
+ network: step.network,
172
+ payerSecretKey: step.key,
173
+ ...(step.mainnet === undefined ? {} : { mainnet: step.mainnet }),
174
+ ...(step.rpcUrl === undefined ? {} : { rpcUrl: step.rpcUrl }),
175
+ budget: step.budget,
176
+ ...(step.pin === undefined ? {} : { pin: step.pin }),
177
+ plan,
178
+ ...shape,
179
+ // X402-11 sends a payment with the request the config says the service must refuse.
180
+ ...(endpoint.reject === undefined ? {} : { reject: endpoint.reject }),
181
+ ...(step.progress === undefined ? {} : { onProgress: step.progress }),
182
+ });
183
+ return [...challenge, ...payment];
184
+ }
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).
189
+ if (step.pay)
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.
192
+ return skippedFor(endpoint.protocol, step);
193
+ }
194
+ catch (error) {
195
+ // A check that throws is a defect in Wasit, not a finding about the service.
196
+ return [errored("PREFLIGHT", "Run Preflight", error)];
197
+ }
198
+ }
199
+ /** The x402 endpoints of a run, as the plan reads them. */
200
+ function planEndpoints(resolved) {
201
+ return resolved.endpoints
202
+ .filter((endpoint) => endpoint.protocol === "x402")
203
+ .map((endpoint) => ({
204
+ name: endpoint.name,
205
+ target: endpoint.url,
206
+ method: endpoint.method,
207
+ ...(endpoint.body === undefined ? {} : { body: endpoint.body }),
208
+ ...(Object.keys(endpoint.headers).length === 0 ? {} : { headers: endpoint.headers }),
209
+ ...(endpoint.reject === undefined ? {} : { reject: endpoint.reject }),
210
+ }));
211
+ }
212
+ /**
213
+ * A key variable is set on a run that may not pay (Najmi, 2026-11-16): refused
214
+ * before the service starts, because the service would run in the same job as
215
+ * the key. A fork's pull request has empty secrets and is not refused.
216
+ */
217
+ function keyOnRefusedEvent(keys, reason) {
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
+ }
226
+ const first = keys[0] ?? "STELLAR_PRIVATE_KEY";
227
+ return (`wasit run: ${keys.join(", ")} ${keys.length === 1 ? "is" : "are"} set, and this run may not pay (${why}). ` +
228
+ `Nothing was started or sent: the service of this run would run in the same job as the key. ` +
229
+ `Give the key only to runs that may pay (push to the default branch, schedule, workflow_dispatch), ` +
230
+ `for example in the env: of the Wasit step:\n` +
231
+ ` ${first}: \${{ github.event_name != 'pull_request' && secrets.WASIT_TESTNET_PAYER || '' }}`);
232
+ }
233
+ /** Why `wasit run` stops in a CI that is not GitHub Actions. */
234
+ function otherCiRefusal(keys) {
235
+ const key = keys.length === 0
236
+ ? ""
237
+ : ` ${keys.join(", ")} ${keys.length === 1 ? "is" : "are"} set: remove ${keys.length === 1 ? "it" : "them"} from ` +
238
+ `this job, since the service of this run would run in the same job as the key.`;
239
+ return (`wasit run: CI is set, and this is not GitHub Actions. In this version the payment tier runs outside CI, or in ` +
240
+ `GitHub Actions, where it pays only on a push to the default branch, a schedule and workflow_dispatch. ` +
241
+ `In this CI, run wasit run --read-only, with no payer key in the job.${key} Nothing was started, sent or signed.`);
242
+ }
243
+ /** The payer's address for the first line of a paying run; the checks report a key that is not valid. */
244
+ function payerAddress(chain, key) {
245
+ try {
246
+ return chain.payerAddress(key);
247
+ }
248
+ catch {
249
+ return "(the key is not valid: see the results)";
250
+ }
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
+ }
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. */
258
+ function readBaselineFile(path) {
259
+ try {
260
+ if (statSync(path).size > MAX_BASELINE_BYTES) {
261
+ return { ok: false, reason: `the baseline is larger than ${MAX_BASELINE_BYTES / 1024} KiB` };
262
+ }
263
+ return readBaseline(readFileSync(path, "utf-8"));
264
+ }
265
+ catch (error) {
266
+ const code = error.code;
267
+ return { ok: false, reason: `the baseline file cannot be read${typeof code === "string" ? ` (${code})` : ""}` };
268
+ }
269
+ }
270
+ /**
271
+ * The dry run: the plan of the x402 payment checks (L0, L1), printed. Exit 0
272
+ * when a paying run could start as planned, 2 when it would be refused.
273
+ */
274
+ async function printPlan(resolved, stdout, clean, fail) {
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) : [];
279
+ try {
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
+ });
294
+ }
295
+ catch (error) {
296
+ // L0: a network that is not a test network, refused before any request.
297
+ if (error instanceof ConfigurationError)
298
+ return fail(`wasit run --dry-run: ${error.message}`);
299
+ throw error;
300
+ }
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))];
303
+ for (const endpoint of resolved.endpoints) {
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}`);
319
+ }
320
+ const refused = plan.refusal !== undefined || plan.endpoints.some((endpoint) => endpoint.status === "refused");
321
+ if (!resolved.operatedByMe) {
322
+ lines.push(`Refused: operatedByMe is not true for environment ${resolved.environment}, so a paying run would be ` +
323
+ `refused: Wasit pays only a service its operator runs. Nothing was signed.`);
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
+ }
332
+ for (const line of lines)
333
+ stdout(clean(line));
334
+ return refused || !resolved.operatedByMe || (mainnet && resolved.rpcUrl === undefined) ? 2 : 0;
335
+ }
336
+ export async function executeRun(options, context) {
337
+ const secrets = deniedEnvValues(context.env);
338
+ const clean = (text) => sanitizeText(text, { redact: secrets });
339
+ const stderr = (text) => context.stderr(clean(text));
340
+ const fail = (message) => {
341
+ stderr(message);
342
+ return 2;
343
+ };
344
+ const mainnet = options.mainnet === true;
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
+ }
352
+ if (dryRun && options.readOnly) {
353
+ return fail("wasit run: choose --dry-run or --read-only, not both.");
354
+ }
355
+ if (dryRun && (options.json || options.out !== undefined || options.baseline !== undefined)) {
356
+ return fail("wasit run --dry-run prints a plan and writes no report: it takes no --json, --out or --baseline.");
357
+ }
358
+ if (options.start && options.startIfLocal === true) {
359
+ return fail("wasit run: choose --start or --start-if-local, not both.");
360
+ }
361
+ let resolved;
362
+ try {
363
+ resolved = resolveRun(readConfigFile(options.config), {
364
+ ...(options.env === undefined ? {} : { environment: options.env }),
365
+ ...(options.endpoint === undefined || options.endpoint.length === 0 ? {} : { endpoints: options.endpoint }),
366
+ }, context.env);
367
+ }
368
+ catch (error) {
369
+ if (error instanceof ConfigError)
370
+ return fail(error.message);
371
+ throw error;
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
+ }
378
+ // D-022a: which GitHub events may pay. A key given to a run that may not pay is
379
+ // refused here, before the service of this run (code that may not be reviewed
380
+ // yet) starts in the same job as the key. Every tier, the read-only one too.
381
+ const event = readGithubEvent(context.env);
382
+ const gate = paymentEventGate(context.env, event);
383
+ if (gate.ciOutsideGithub === true) {
384
+ // In a CI that is not GitHub Actions the payment tier does not run at all, and
385
+ // no tier runs beside a payer key (Najmi, 2026-11-17, review R9 a).
386
+ const keys = payerKeyVariables(context.env);
387
+ if (keys.length > 0 || (!options.readOnly && options.dryRun !== true))
388
+ return fail(otherCiRefusal(keys));
389
+ }
390
+ else if (!gate.allowed) {
391
+ const keys = payerKeyVariables(context.env);
392
+ if (keys.length > 0)
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
+ }
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 });
404
+ // The payment tier: neither --read-only nor --dry-run. On an event that may not
405
+ // pay it is the read-only tier, and the report says why.
406
+ const paymentAsked = !options.readOnly && !dryRun;
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
+ }
413
+ const chain = paying ? paymentChainFor(resolved.network) : undefined;
414
+ if (paying && (chain !== undefined || resolved.networkClass !== "unknown")) {
415
+ // L0, before the service starts or anything is sent: a test network only.
416
+ try {
417
+ assertPaymentNetworkAllowed("x402", resolved.network);
418
+ }
419
+ catch (error) {
420
+ if (error instanceof ConfigurationError)
421
+ return fail(`wasit run: ${error.message} Nothing was started, sent or signed.`);
422
+ throw error;
423
+ }
424
+ }
425
+ const keyEnv = chain?.payerKeyEnv;
426
+ const keyValue = keyEnv === undefined ? undefined : context.env[keyEnv];
427
+ const key = keyValue === undefined || keyValue.trim() === "" ? undefined : keyValue;
428
+ const hasX402 = resolved.endpoints.some((endpoint) => endpoint.protocol === "x402");
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. */
433
+ const notPaid = !paying
434
+ ? undefined
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) {
449
+ try {
450
+ await assertMppPaymentRpc(MPP_NETWORK, resolved.rpcUrl, { charge: mppChargePays });
451
+ }
452
+ catch (error) {
453
+ if (error instanceof ConfigurationError)
454
+ return fail(`wasit run: ${error.message} The service was not started.`);
455
+ throw error;
456
+ }
457
+ }
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) {
463
+ try {
464
+ await assertX402PaymentRpc(resolved.network, chain.resolveRpcUrl(resolved.network, resolved.rpcUrl));
465
+ }
466
+ catch (error) {
467
+ if (error instanceof RpcIdentityError)
468
+ return fail(`wasit run: ${error.message} The service was not started.`);
469
+ throw error;
470
+ }
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;
479
+ if (dryRun) {
480
+ try {
481
+ return await printPlan(resolved, context.stdout, clean, fail);
482
+ }
483
+ finally {
484
+ await service?.stop();
485
+ }
486
+ }
487
+ const startedAt = (context.now?.() ?? new Date()).toISOString();
488
+ // Lines about money go where the report is not: stderr with --json, else stdout.
489
+ const say = (line) => (options.json ? stderr(line) : context.stdout(clean(line)));
490
+ try {
491
+ let step;
492
+ let tierNote;
493
+ let budget;
494
+ let mpp;
495
+ if (!paymentAsked) {
496
+ step = { pay: false, kind: "read-only" };
497
+ tierNote = TIER_NOTE;
498
+ }
499
+ else if (!gate.allowed) {
500
+ const reason = gate.reason ?? "payment checks not run";
501
+ step = { pay: false, kind: "read-only", reason };
502
+ tierNote = `Tier: read-only (${reason}). Nothing was signed.`;
503
+ }
504
+ else {
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
+ };
572
+ }
573
+ }
574
+ const endpoints = [];
575
+ for (const endpoint of resolved.endpoints) {
576
+ const results = await runEndpoint(endpoint, step, mpp);
577
+ endpoints.push(buildEndpointReport({
578
+ name: endpoint.name,
579
+ protocol: endpoint.protocol,
580
+ method: endpoint.method,
581
+ path: endpoint.path,
582
+ results,
583
+ }));
584
+ }
585
+ if (budget !== undefined) {
586
+ // Charged before each signature and never credited back: what the run may have spent.
587
+ tierNote =
588
+ `Tier: payment on ${resolved.network}. The run charged ${formatUsd(budget.spentUsd)} of the ` +
589
+ `${formatUsd(budget.capUsd)} cap, at most $${PER_PAYMENT_CAP_USD}.00 a payment; every signature is counted as if it settled.`;
590
+ }
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) =>
617
+ // The payment tier was asked for on an event that may pay and did not pay:
618
+ // not green (a FAIL still outranks it).
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.`);
637
+ }
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);
804
+ }
805
+ }
806
+ let ledgerPath;
807
+ try {
808
+ ledgerPath = optIn.openLedger(versions).path;
809
+ }
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 }));
823
+ }
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
+ });
847
+ }
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
+ }
853
+ await service?.stop();
854
+ }
855
+ }