@wasit-dev/core 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.
Files changed (88) hide show
  1. package/README.md +13 -2
  2. package/dist/baseline.d.ts +109 -0
  3. package/dist/baseline.js +353 -0
  4. package/dist/catalogue.js +10 -0
  5. package/dist/check.d.ts +57 -2
  6. package/dist/check.js +46 -6
  7. package/dist/ci-report.d.ts +74 -0
  8. package/dist/ci-report.js +399 -0
  9. package/dist/config-writer.d.ts +96 -0
  10. package/dist/config-writer.js +281 -0
  11. package/dist/config.d.ts +205 -0
  12. package/dist/config.js +1011 -0
  13. package/dist/denied-env.d.ts +33 -0
  14. package/dist/denied-env.js +86 -0
  15. package/dist/errors.d.ts +44 -1
  16. package/dist/errors.js +151 -2
  17. package/dist/guard/budget.d.ts +138 -0
  18. package/dist/guard/budget.js +206 -0
  19. package/dist/guard/ci-event.d.ts +56 -0
  20. package/dist/guard/ci-event.js +129 -0
  21. package/dist/guard/ci-mainnet.d.ts +59 -0
  22. package/dist/guard/ci-mainnet.js +149 -0
  23. package/dist/guard/horizon.d.ts +30 -0
  24. package/dist/guard/horizon.js +107 -0
  25. package/dist/guard/mainnet-payer.d.ts +66 -0
  26. package/dist/guard/mainnet-payer.js +92 -0
  27. package/dist/guard/mainnet-plan.d.ts +133 -0
  28. package/dist/guard/mainnet-plan.js +208 -0
  29. package/dist/guard/mainnet-run.d.ts +87 -0
  30. package/dist/guard/mainnet-run.js +225 -0
  31. package/dist/guard/networks.d.ts +51 -0
  32. package/dist/guard/networks.js +91 -0
  33. package/dist/guard/optin.d.ts +106 -0
  34. package/dist/guard/optin.js +202 -0
  35. package/dist/guard/rpc-identity.d.ts +45 -0
  36. package/dist/guard/rpc-identity.js +156 -0
  37. package/dist/guard/rpc-in-use.d.ts +48 -0
  38. package/dist/guard/rpc-in-use.js +84 -0
  39. package/dist/guard/run-ledger.d.ts +212 -0
  40. package/dist/guard/run-ledger.js +426 -0
  41. package/dist/guard/run-lock.d.ts +62 -0
  42. package/dist/guard/run-lock.js +172 -0
  43. package/dist/guard/signed-terms.d.ts +96 -0
  44. package/dist/guard/signed-terms.js +207 -0
  45. package/dist/index.d.ts +44 -4
  46. package/dist/index.js +42 -2
  47. package/dist/mpp/channel-commitment.d.ts +48 -2
  48. package/dist/mpp/channel-commitment.js +80 -4
  49. package/dist/mpp/channel-credential.d.ts +13 -1
  50. package/dist/mpp/channel-credential.js +21 -2
  51. package/dist/mpp/channel.d.ts +6 -0
  52. package/dist/mpp/channel.js +36 -3
  53. package/dist/mpp/charge.d.ts +33 -1
  54. package/dist/mpp/charge.js +90 -20
  55. package/dist/mpp/network.js +4 -1
  56. package/dist/mpp/plan.d.ts +77 -0
  57. package/dist/mpp/plan.js +188 -0
  58. package/dist/mpp/suite.d.ts +6 -0
  59. package/dist/mpp/suite.js +12 -3
  60. package/dist/report.d.ts +163 -0
  61. package/dist/report.js +282 -0
  62. package/dist/route-reader.d.ts +124 -0
  63. package/dist/route-reader.js +349 -0
  64. package/dist/sanitize.d.ts +52 -0
  65. package/dist/sanitize.js +106 -0
  66. package/dist/settlement.d.ts +14 -0
  67. package/dist/settlement.js +1 -1
  68. package/dist/verdict.d.ts +24 -0
  69. package/dist/verdict.js +46 -0
  70. package/dist/versions.d.ts +50 -0
  71. package/dist/versions.js +123 -0
  72. package/dist/wallet.d.ts +58 -1
  73. package/dist/wallet.js +128 -0
  74. package/dist/x402/chains/evm.js +3 -0
  75. package/dist/x402/chains/index.d.ts +8 -0
  76. package/dist/x402/chains/index.js +13 -2
  77. package/dist/x402/chains/stellar.d.ts +8 -1
  78. package/dist/x402/chains/stellar.js +259 -4
  79. package/dist/x402/chains/types.d.ts +104 -2
  80. package/dist/x402/plan.d.ts +184 -0
  81. package/dist/x402/plan.js +520 -0
  82. package/dist/x402/rejected-request.d.ts +156 -0
  83. package/dist/x402/rejected-request.js +287 -0
  84. package/dist/x402/requirements.d.ts +1 -0
  85. package/dist/x402/requirements.js +37 -4
  86. package/dist/x402/simulator.d.ts +86 -1
  87. package/dist/x402/simulator.js +863 -87
  88. package/package.json +1 -1
@@ -0,0 +1,287 @@
1
+ /**
2
+ * X402-11, "Rejected Request Not Settled" (spec B7 as D-032 changed it).
3
+ *
4
+ * Wasit sends a valid payment, for the advertised terms exactly, with a request
5
+ * the builder's config declares invalid (`endpoints[].reject`), then reads the
6
+ * chain: the nonce of that payment's authorization must still be unused once
7
+ * its expiration ledger has passed. The verdict comes from one read that asks
8
+ * for that nonce and for X402-06's, which was used and must be found: a read
9
+ * that cannot find X402-06's cannot show that ours is absent. The payer's
10
+ * balance and the transfer events are second readings; when they disagree with
11
+ * the nonce, there is no verdict.
12
+ *
13
+ * The wait (Najmi, 2026-11-16): a payment whose advertised lifetime
14
+ * (`maxTimeoutSeconds`) is at most 300 s is waited out, with a hard stop 360 s
15
+ * after it was sent; a longer one is not signed at all (it is read again on the
16
+ * challenge the payment is signed from), and an authorization the client signs
17
+ * to outlive it is not sent. A lifetime below 30 s is not signed either, and an
18
+ * authorization with fewer than 3 ledgers left is not sent (2026-11-17).
19
+ *
20
+ * This file holds the parts that need no network: the rules, the reject
21
+ * request's shape, the watch loop over a chain's reads, and the verdict. The
22
+ * check itself, which pays, is in `simulator.ts` with the other payment checks.
23
+ */
24
+ import { errored, skipped } from "../check.js";
25
+ import { CheckSetupError } from "../errors.js";
26
+ import { sanitizeText } from "../sanitize.js";
27
+ export const REJECTED_REQUEST_ID = "X402-11";
28
+ export const REJECTED_REQUEST_NAME = "Rejected Request Not Settled";
29
+ /** The longest advertised lifetime X402-11 waits out on a test network. */
30
+ export const REJECTED_REQUEST_MAX_LIFETIME_SECONDS = 300;
31
+ /**
32
+ * The shortest advertised lifetime X402-11 signs for (Najmi, 2026-11-17,
33
+ * screening S-1): a payment valid for a few seconds can expire before a service
34
+ * that settles it has it on chain, and its unused authorization would then show
35
+ * nothing about the service.
36
+ */
37
+ export const REJECTED_REQUEST_MIN_LIFETIME_SECONDS = 30;
38
+ /** The fewest units of validity a signed authorization must have left when X402-11 sends it. */
39
+ export const REJECTED_REQUEST_MIN_UNITS_LEFT = 3;
40
+ /**
41
+ * How long after the payment is sent the watch stops, whatever the lifetime:
42
+ * a 300 s lifetime is 60 ledgers of 5 s, and the verdict needs the ledger
43
+ * after it, so about 305 s; the rest is slack for a slow ledger or RPC.
44
+ */
45
+ export const REJECTED_REQUEST_HARD_STOP_MS = 360_000;
46
+ let hardStopForTesting;
47
+ /**
48
+ * Tests only: a shorter hard stop, so "still valid when the watch stopped" can
49
+ * be shown without a six-minute test. It can only lower the stop. Not exported
50
+ * from the package index; no flag, setting or tool argument reaches it.
51
+ */
52
+ export function setRejectedRequestHardStopForTesting(ms) {
53
+ hardStopForTesting = ms;
54
+ }
55
+ export function rejectedRequestHardStopMs() {
56
+ return hardStopForTesting === undefined
57
+ ? REJECTED_REQUEST_HARD_STOP_MS
58
+ : Math.min(hardStopForTesting, REJECTED_REQUEST_HARD_STOP_MS);
59
+ }
60
+ const BODYLESS = new Set(["GET", "HEAD"]);
61
+ /**
62
+ * The endpoint's own request with the reject case over it: its method when it
63
+ * names one, its headers over the endpoint's (by name, ignoring case), and its
64
+ * body instead of the endpoint's. A method that carries no body drops the
65
+ * endpoint's body; the config already refuses a reject body on such a method.
66
+ */
67
+ export function rejectRequestShape(shape, reject) {
68
+ const method = (reject.method ?? shape.method ?? "GET").toUpperCase();
69
+ const replaced = new Set(Object.keys(reject.headers ?? {}).map((name) => name.toLowerCase()));
70
+ const headers = {};
71
+ for (const [name, value] of Object.entries(shape.headers ?? {})) {
72
+ if (!replaced.has(name.toLowerCase()))
73
+ headers[name] = value;
74
+ }
75
+ Object.assign(headers, reject.headers ?? {});
76
+ const body = reject.body !== undefined ? reject.body : BODYLESS.has(method) ? undefined : shape.body;
77
+ return {
78
+ method,
79
+ ...(Object.keys(headers).length === 0 ? {} : { headers }),
80
+ ...(body === undefined ? {} : { body }),
81
+ };
82
+ }
83
+ function message(error) {
84
+ return sanitizeText(error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ").slice(0, 200);
85
+ }
86
+ class ReadTimedOut extends Error {
87
+ }
88
+ /** `promise`, or `ReadTimedOut` once `ms` have passed (at once when `ms` is 0 or less). */
89
+ function withinMs(promise, ms) {
90
+ // A read that answers after the stop is ignored, and its failure too.
91
+ promise.catch(() => undefined);
92
+ return new Promise((resolve, reject) => {
93
+ const timer = setTimeout(() => reject(new ReadTimedOut()), Math.max(0, ms));
94
+ promise.then((value) => {
95
+ clearTimeout(timer);
96
+ resolve(value);
97
+ }, (error) => {
98
+ clearTimeout(timer);
99
+ reject(error);
100
+ });
101
+ });
102
+ }
103
+ /**
104
+ * Reads the chain once a ledger until the authorization is used, or a read
105
+ * past its expiration ledger finds it unused, or the hard stop comes. Every
106
+ * read asks for the control too; one that does not return it ends the watch
107
+ * with no reading. Never throws: a failed read is an `unread` outcome.
108
+ */
109
+ export async function watchAuthorization(input) {
110
+ const now = input.now ?? Date.now;
111
+ const sleep = input.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
112
+ const stop = input.sentAt + rejectedRequestHardStopMs();
113
+ for (;;) {
114
+ let read;
115
+ try {
116
+ // A read that has not answered by the hard stop ends the watch there: the
117
+ // stop holds while a read is in flight, not only between reads.
118
+ read = await withinMs(input.watch.read(input.network, input.rpcUrl, [input.ours, input.control]), stop - now());
119
+ }
120
+ catch (error) {
121
+ if (error instanceof ReadTimedOut) {
122
+ return {
123
+ kind: "unread",
124
+ why: `the chain did not answer a read before the watch's hard stop, ${Math.round(rejectedRequestHardStopMs() / 1000)} s after the payment was sent`,
125
+ };
126
+ }
127
+ return { kind: "unread", why: `the chain read failed: ${message(error)}` };
128
+ }
129
+ if (read.used[1] === undefined) {
130
+ return {
131
+ kind: "unread",
132
+ why: "the chain's answer left out X402-06's authorization, which was used, so it cannot show that this one was not",
133
+ };
134
+ }
135
+ const usedAt = read.used[0];
136
+ if (usedAt !== undefined)
137
+ return { kind: "used", ledger: usedAt, latest: read.latest };
138
+ if (read.latest > input.ours.expiresAt)
139
+ return { kind: "unused", latest: read.latest };
140
+ const left = stop - now();
141
+ if (left <= 0)
142
+ return { kind: "still-valid", latest: read.latest };
143
+ await sleep(Math.max(1, Math.min(input.watch.unitMs, left)));
144
+ }
145
+ }
146
+ function refusal(status, reason) {
147
+ return reason === undefined ? `HTTP ${status}` : `HTTP ${status}: ${reason}`;
148
+ }
149
+ /** Why the second readings do not support "taken", or undefined when they do. */
150
+ function notTaken(evidence) {
151
+ const { balance, transfers, amount } = evidence;
152
+ if (balance === undefined || transfers === undefined)
153
+ return "the payer's balance or the transfer events were not read";
154
+ const fell = balance.before - balance.after;
155
+ if (transfers.length === 0)
156
+ return `no transfer of ${amount} base units from the payer to payTo was recorded`;
157
+ if (fell < amount)
158
+ return `the payer's balance fell by ${fell} base units, less than the ${amount} paid`;
159
+ return undefined;
160
+ }
161
+ /** Why the second readings do not support "not taken", or undefined when they do. */
162
+ function notUntaken(evidence) {
163
+ const { balance, transfers, amount } = evidence;
164
+ if (balance === undefined || transfers === undefined)
165
+ return "the payer's balance or the transfer events were not read";
166
+ const fell = balance.before - balance.after;
167
+ if (transfers.length > 0) {
168
+ return `a transfer of ${amount} base units from the payer to payTo was recorded (${transfers.map((item) => item.reference).join(", ")})`;
169
+ }
170
+ if (fell >= amount)
171
+ return `the payer's balance fell by ${fell} base units, at least the ${amount} paid`;
172
+ return undefined;
173
+ }
174
+ /**
175
+ * The settlement the chain shows for X402-11's payment, for the run ledger:
176
+ * the chain records its authorization as used, and the second readings agree
177
+ * (a transfer of the price from the payer to payTo, and the payer's balance
178
+ * down by at least it). The nonce read is a reading of this payment's own
179
+ * authorization, so the settlement counts as verified. The reference is the
180
+ * one transfer in the ledger the nonce was used in, or the only one the watch
181
+ * saw; when neither names one, undefined, and the ledger leaves it unverified.
182
+ */
183
+ export function rejectedRequestSettlement(evidence) {
184
+ const { watch, transfers } = evidence;
185
+ if (watch.kind !== "used" || transfers === undefined || notTaken(evidence) !== undefined)
186
+ return undefined;
187
+ const there = transfers.filter((transfer) => transfer.ledger === watch.ledger);
188
+ if (there.length === 1)
189
+ return there[0].reference;
190
+ return transfers.length === 1 ? transfers[0].reference : undefined;
191
+ }
192
+ const SERVED_HINT = "Refuse an invalid request before its payment is settled. The official x402 Express middleware does not settle " +
193
+ "when the handler answers 400 or above; a route that serves every request it is paid for sells what it should refuse.";
194
+ const TAKEN_HINT = "A refused request must not cost the payer: settle a payment only after the request has been accepted. The " +
195
+ "official x402 Express middleware does not settle when the handler answers 400 or above; code that settles " +
196
+ "before validating the request, or settles on its own, takes the payment for a request it then refuses.";
197
+ /**
198
+ * X402-11's verdict from what the service answered and what the chain shows.
199
+ *
200
+ * - served (2xx): FAIL, whatever the chain shows; the chain only adds whether it settled.
201
+ * - refused, used, the second readings agree: FAIL, the payment was taken.
202
+ * - refused, unused past the expiry, the second readings agree: PASS.
203
+ * - refused and still valid at the hard stop: SKIP, "not settled by ledger N; still valid until ledger M".
204
+ * - anything else (a reading that disagrees or is missing, a read that failed): no verdict, never PASS.
205
+ */
206
+ export function rejectedRequestVerdict(evidence) {
207
+ const id = REJECTED_REQUEST_ID;
208
+ const name = REJECTED_REQUEST_NAME;
209
+ const { watch, unit, expiresAt, amount, status } = evidence;
210
+ const served = status >= 200 && status < 300;
211
+ if (served) {
212
+ let note;
213
+ if (watch.kind === "used") {
214
+ const why = notTaken(evidence);
215
+ note =
216
+ why === undefined
217
+ ? ` The payment was taken: ${evidence.transfers.map((item) => `${item.reference} (${unit} ${item.ledger})`).join(", ")}.`
218
+ : ` The chain records its authorization as used (${unit} ${watch.ledger}), but ${why}, so whether it was taken is not stated.`;
219
+ }
220
+ else if (watch.kind === "unused") {
221
+ const why = notUntaken(evidence);
222
+ note =
223
+ why === undefined
224
+ ? ` The payment did not settle: its authorization expired at ${unit} ${expiresAt} unused.`
225
+ : ` Whether the payment settled is not stated: the chain records its authorization as unused, but ${why}.`;
226
+ }
227
+ else if (watch.kind === "still-valid") {
228
+ note = ` Whether the payment settled is not known: it was still valid at ${unit} ${watch.latest}, until ${unit} ${expiresAt}, when Wasit stopped waiting.`;
229
+ }
230
+ else {
231
+ note = ` Whether the payment settled was not read: ${watch.why}.`;
232
+ }
233
+ return {
234
+ id,
235
+ name,
236
+ pass: false,
237
+ detail: `A request the config declares invalid was served (HTTP ${status}) with a valid payment for ${amount} base units.${note}`,
238
+ hint: SERVED_HINT,
239
+ expected: "the invalid request refused",
240
+ actual: `HTTP ${status}`,
241
+ };
242
+ }
243
+ const refused = `The request the config declares invalid was refused (${refusal(status, evidence.reason)})`;
244
+ const noVerdict = (text) => errored(id, name, new CheckSetupError(text));
245
+ switch (watch.kind) {
246
+ case "used": {
247
+ const why = notTaken(evidence);
248
+ if (why !== undefined) {
249
+ return noVerdict(`${refused}. The chain records this payment's authorization as used (${unit} ${watch.ledger}), but ${why}, ` +
250
+ `so the readings disagree and there is no verdict.`);
251
+ }
252
+ const where = evidence.transfers.map((item) => `${item.reference} (${unit} ${item.ledger})`).join(", ");
253
+ return {
254
+ id,
255
+ name,
256
+ pass: false,
257
+ detail: `${refused} and the payment was taken: ${amount} base units moved from the payer to payTo in ${where}; ` +
258
+ `the chain records its authorization as used.`,
259
+ hint: TAKEN_HINT,
260
+ expected: "a refused request leaves its payment unsettled",
261
+ actual: `the payment settled (${unit} ${watch.ledger})`,
262
+ };
263
+ }
264
+ case "unused": {
265
+ const why = notUntaken(evidence);
266
+ if (why !== undefined) {
267
+ return noVerdict(`${refused}. The chain records this payment's authorization as unused past its expiry (${unit} ${expiresAt}), ` +
268
+ `but ${why}, so the readings disagree and there is no verdict.`);
269
+ }
270
+ return {
271
+ id,
272
+ name,
273
+ pass: true,
274
+ detail: `${refused}, and the payment was not taken: its authorization expired at ${unit} ${expiresAt} unused ` +
275
+ `(read at ${unit} ${watch.latest}, in the same read that found X402-06's used authorization); no transfer ` +
276
+ `of it to payTo was recorded, and the payer's balance did not fall by it.`,
277
+ };
278
+ }
279
+ case "still-valid":
280
+ return skipped(id, name, `the request was refused (${refusal(status, evidence.reason)}), and its payment was not settled by ${unit} ` +
281
+ `${watch.latest}; still valid until ${unit} ${expiresAt} when Wasit stopped waiting (at most ` +
282
+ `${REJECTED_REQUEST_HARD_STOP_MS / 1000} s on a test network), so whether it settles is not known.`);
283
+ case "unread":
284
+ return noVerdict(`${refused}, but the chain was not read to the end of the payment's validity (${watch.why}), so whether it ` +
285
+ `settled is not known.`);
286
+ }
287
+ }
@@ -30,6 +30,7 @@ export type NetworkVerdict = {
30
30
  readonly valid: false;
31
31
  readonly reason: string;
32
32
  readonly fix: string;
33
+ readonly expected: string;
33
34
  };
34
35
  /**
35
36
  * Validates one network identifier against CAIP-2, which x402 v2 requires,
@@ -7,7 +7,7 @@
7
7
  * network of every payment option with a CAIP-2 identifier, and a challenge
8
8
  * may offer several options on several chains at once.
9
9
  */
10
- import { skipped } from "../check.js";
10
+ import { quoteValue, skipped } from "../check.js";
11
11
  function asRecord(value) {
12
12
  return typeof value === "object" && value !== null
13
13
  ? value
@@ -96,10 +96,15 @@ function fieldProblem(accept, version) {
96
96
  `service speaks that version.`,
97
97
  ],
98
98
  missing: false,
99
+ expected: `the field \`${expected}\` (v${version})`,
100
+ actual: `the field \`${wrongVersionField}\` (v${version === 2 ? 1 : 2})`,
99
101
  };
100
102
  }
101
103
  const missing = [];
102
104
  const wrongType = [];
105
+ // The same findings as short expected and actual values, in the same order.
106
+ const wrongExpected = [];
107
+ const wrongActual = [];
103
108
  for (const field of REQUIRED_FIELDS[version]) {
104
109
  const value = accept?.[field];
105
110
  if (value === undefined || value === null || value === "") {
@@ -109,10 +114,14 @@ function fieldProblem(accept, version) {
109
114
  // A zero or negative timeout leaves the client no time to pay.
110
115
  if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
111
116
  wrongType.push(`maxTimeoutSeconds must be a positive number of seconds (got ${describeValue(value)})`);
117
+ wrongExpected.push("maxTimeoutSeconds as a positive number");
118
+ wrongActual.push(`maxTimeoutSeconds is ${describeValue(value)}`);
112
119
  }
113
120
  }
114
121
  else if (typeof value !== "string") {
115
122
  wrongType.push(`${field} must be a string (got ${describeValue(value)})`);
123
+ wrongExpected.push(`${field} as a string`);
124
+ wrongActual.push(`${field} is ${describeValue(value)}`);
116
125
  }
117
126
  }
118
127
  if (missing.length === 0 && wrongType.length === 0)
@@ -132,7 +141,13 @@ function fieldProblem(accept, version) {
132
141
  ]
133
142
  : []),
134
143
  ];
135
- return { detail, fixes, missing: missing.length > 0 };
144
+ return {
145
+ detail,
146
+ fixes,
147
+ missing: missing.length > 0,
148
+ expected: [...(missing.length > 0 ? [`${missing.join(", ")} present`] : []), ...wrongExpected].join("; "),
149
+ actual: [...(missing.length > 0 ? [`${missing.join(", ")} missing`] : []), ...wrongActual].join("; "),
150
+ };
136
151
  }
137
152
  /** X402-04: every payment option must carry the fields its version requires. */
138
153
  export function checkRequiredFields(payload) {
@@ -148,10 +163,13 @@ export function checkRequiredFields(payload) {
148
163
  `neither 1 nor 2. The payment terms use different field names per ` +
149
164
  `version, so they cannot be checked against an unknown one.`,
150
165
  hint: "Set `x402Version` to 2, the current protocol version, and use its field names.",
166
+ expected: "x402Version 2",
167
+ actual: version === undefined ? "no x402Version" : `x402Version ${quoteValue(version)}`,
151
168
  };
152
169
  }
153
170
  const accepts = acceptsOf(payload);
154
171
  if (accepts === undefined || accepts.length === 0) {
172
+ const raw = asRecord(payload)?.["accepts"];
155
173
  return {
156
174
  id,
157
175
  name,
@@ -160,6 +178,8 @@ export function checkRequiredFields(payload) {
160
178
  `there is no price, network or payTo to read.`,
161
179
  hint: "List at least one payment option in `accepts`, each with " +
162
180
  `${REQUIRED_FIELDS[version].join(", ")}.`,
181
+ expected: "at least one entry in accepts",
182
+ actual: raw === undefined ? "accepts is missing" : Array.isArray(raw) ? "accepts is empty" : "accepts is not a list",
163
183
  };
164
184
  }
165
185
  const problems = accepts
@@ -167,7 +187,12 @@ export function checkRequiredFields(payload) {
167
187
  const problem = fieldProblem(accept, version);
168
188
  return problem === undefined
169
189
  ? undefined
170
- : { ...problem, detail: optionLabel(index, accepts.length) + problem.detail };
190
+ : {
191
+ ...problem,
192
+ detail: optionLabel(index, accepts.length) + problem.detail,
193
+ expected: optionLabel(index, accepts.length) + problem.expected,
194
+ actual: optionLabel(index, accepts.length) + problem.actual,
195
+ };
171
196
  })
172
197
  .filter((problem) => problem !== undefined);
173
198
  if (problems.length > 0) {
@@ -183,6 +208,8 @@ export function checkRequiredFields(payload) {
183
208
  pass: false,
184
209
  detail: problems.map((problem) => problem.detail).join(" "),
185
210
  hint: fixes.join(" "),
211
+ expected: problems.map((problem) => problem.expected).join("; "),
212
+ actual: problems.map((problem) => problem.actual).join("; "),
186
213
  };
187
214
  }
188
215
  return {
@@ -226,6 +253,7 @@ const NAMESPACE_RULES = {
226
253
  reason: `"stellar:${reference}" does not match stellar:testnet or stellar:pubnet, ` +
227
254
  `the only Stellar networks CAIP-2 defines.`,
228
255
  fix: "Use stellar:testnet or stellar:pubnet.",
256
+ expected: "stellar:testnet or stellar:pubnet",
229
257
  },
230
258
  eip155: (reference) => /^[1-9][0-9]*$/.test(reference)
231
259
  ? undefined
@@ -233,6 +261,7 @@ const NAMESPACE_RULES = {
233
261
  reason: `"eip155:${reference}" does not carry an EIP-155 chain id in base 10, ` +
234
262
  `which the eip155 namespace requires (Base Sepolia is eip155:84532).`,
235
263
  fix: eip155Fix(reference),
264
+ expected: "eip155:<chain id in base 10>",
236
265
  },
237
266
  solana: (reference) => BASE58_32.test(reference)
238
267
  ? undefined
@@ -243,6 +272,7 @@ const NAMESPACE_RULES = {
243
272
  fix: "Use the first 32 characters of the cluster's genesis hash (RPC " +
244
273
  "getGenesisHash): solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 for devnet, " +
245
274
  "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp for mainnet.",
275
+ expected: "solana:<first 32 characters of the base58 genesis hash>",
246
276
  },
247
277
  };
248
278
  /**
@@ -262,6 +292,7 @@ export function validateNetwork(network) {
262
292
  reason: `"${network}" is not a CAIP-2 identifier (namespace:reference, e.g. ` +
263
293
  `stellar:testnet or eip155:84532), which x402 v2 requires.`,
264
294
  fix: `Use the network's CAIP-2 id, namespace:reference, such as ${CAIP2_EXAMPLES}.`,
295
+ expected: "a CAIP-2 id, namespace:reference, such as stellar:testnet",
265
296
  };
266
297
  }
267
298
  const namespace = match[1];
@@ -283,7 +314,7 @@ export function checkNetworkIdentifier(payload) {
283
314
  .filter((entry) => nonEmptyString(entry.network));
284
315
  // Absent is X402-04's finding, not a second one: report it there only.
285
316
  if (advertised.length === 0) {
286
- return skipped(id, name, "the challenge carries no network field to validate (see X402-04).");
317
+ return skipped(id, name, "the challenge carries no network field to validate (see X402-04).", "dependency");
287
318
  }
288
319
  const v1 = asRecord(payload)?.["x402Version"] === 1;
289
320
  const verdicts = advertised.map((entry) => ({ ...entry, verdict: validateNetwork(entry.network) }));
@@ -300,6 +331,8 @@ export function checkNetworkIdentifier(payload) {
300
331
  pass: false,
301
332
  detail: reasons.join(" ") + v1Note,
302
333
  hint: [...new Set(problems.map((problem) => problem.fix))].join(" "),
334
+ expected: invalid.map((entry, i) => optionLabel(entry.index, accepts.length) + problems[i].expected).join("; "),
335
+ actual: invalid.map((entry) => optionLabel(entry.index, accepts.length) + quoteValue(entry.network)).join("; "),
303
336
  };
304
337
  }
305
338
  const unknownNamespaces = [
@@ -1,4 +1,10 @@
1
1
  import { type CheckResult } from "../check.js";
2
+ import { ConfigurationError } from "../errors.js";
3
+ import { RunBudget, type PinTerms } from "../guard/budget.js";
4
+ import { type MainnetOptIn } from "../guard/optin.js";
5
+ import { type PaymentLedger } from "../guard/run-ledger.js";
6
+ import type { EndpointPlan } from "./plan.js";
7
+ import { type RejectCase } from "./rejected-request.js";
2
8
  export type { CheckResult };
3
9
  /**
4
10
  * How to address the target's paid endpoint.
@@ -27,6 +33,15 @@ export interface X402SimulatorOptions extends RequestShape {
27
33
  */
28
34
  readonly onResult?: (result: CheckResult) => void;
29
35
  }
36
+ /**
37
+ * Validates a request shape and turns it into fetch init.
38
+ *
39
+ * A bad method, or a body on a verb that cannot carry one, is a configuration
40
+ * error rather than a finding: nothing has been learned about the target.
41
+ * Exported for `wasit init`'s unpaid request (route-reader.ts), which sends
42
+ * the route what the read checks send it.
43
+ */
44
+ export declare function buildInit(shape: RequestShape): RequestInit;
30
45
  /**
31
46
  * Reads an x402 v1 challenge from a 402 response body, if that is what it is.
32
47
  *
@@ -43,6 +58,7 @@ export declare function readV1BodyChallenge(body: string): Record<string, unknow
43
58
  * be evaluated, so one broken challenge produces one finding.
44
59
  */
45
60
  export declare function runX402ReadChecks(options: X402SimulatorOptions): Promise<CheckResult[]>;
61
+ import type { PaymentRequirements } from "@x402/core/types";
46
62
  import { type PaymentChain } from "./chains/index.js";
47
63
  export { corruptAuthSignature } from "./chains/stellar.js";
48
64
  export interface X402PaymentCheckOptions extends RequestShape {
@@ -53,7 +69,76 @@ export interface X402PaymentCheckOptions extends RequestShape {
53
69
  readonly rpcUrl?: string;
54
70
  /** See {@link X402SimulatorOptions.onResult} — same contract. */
55
71
  readonly onResult?: (result: CheckResult) => void;
72
+ /**
73
+ * The run's budget, shared by every endpoint of one run. Without one, these
74
+ * checks get their own: $5, of which they sign at most 3.5 times a $1 price.
75
+ */
76
+ readonly budget?: RunBudget;
77
+ /** Every `exact` option on the run's network must pay this `payTo` in this asset. */
78
+ readonly pin?: PinTerms;
79
+ /** This endpoint's entry of the run's plan (L1): no signature beyond it. */
80
+ readonly plan?: EndpointPlan;
81
+ /** The request the service must refuse (`endpoints[].reject`), for X402-11. Absent: X402-11 is skipped. */
82
+ readonly reject?: RejectCase;
83
+ /**
84
+ * The run ledger of this endpoint (spec B5): each signature's intent is
85
+ * written before the key is asked to sign, then what became of it. A ledger
86
+ * that cannot take an intent stops that payment, with nothing signed.
87
+ * Optional on a test network. On mainnet the opt-in's own ledger is used,
88
+ * and one handed in here is refused.
89
+ */
90
+ readonly ledger?: PaymentLedger;
91
+ /**
92
+ * The mainnet opt-in of the run (spec B5), made by `openMainnetOptIn`, its
93
+ * plan passed and its ledger open. On `stellar:pubnet` nothing is paid
94
+ * without it, and the checks pay by its budget, pin, plan, ledger and RPC
95
+ * only: a different one handed in beside it is refused.
96
+ */
97
+ readonly mainnet?: MainnetOptIn;
98
+ /**
99
+ * Called with one line when a check starts a long wait on the chain (X402-11
100
+ * waits up to six minutes), so a log does not look stuck. The line holds no
101
+ * text from the service.
102
+ */
103
+ readonly onProgress?: (line: string) => void;
56
104
  }
105
+ /**
106
+ * No payment adapter pays on this network, so the payment checks cannot be
107
+ * graded here. A `ConfigurationError`, so a caller that does not know the class
108
+ * still reads it as no verdict; preflight turns it into a skip of kind
109
+ * `unsupported` (spec A3). It is not the guard's refusal: `stellar:pubnet` has
110
+ * an adapter and is refused by `assertPaymentNetworkAllowed`, as an error.
111
+ */
112
+ export declare class UnsupportedPaymentNetworkError extends ConfigurationError {
113
+ readonly network: string;
114
+ constructor(network: string);
115
+ }
116
+ /**
117
+ * What a payment check reads before it can pay: the challenge, the URL to pay
118
+ * at, and the one option it would pay. Shared by `preparePayment` and the plan
119
+ * (L1), so both judge the same option by the same rules.
120
+ *
121
+ * Throws `PaymentNotAttemptedError` when there is nothing to pay: an
122
+ * unreadable or v1 challenge, no option on the run's network, or none in the
123
+ * `exact` scheme.
124
+ */
125
+ export declare function readPaymentChallenge(options: RequestShape & {
126
+ readonly target: string;
127
+ readonly network: string;
128
+ }): Promise<{
129
+ payUrl: string;
130
+ paymentRequired: import("@x402/fetch").PaymentRequired;
131
+ selected: PaymentRequirements;
132
+ idempotent: boolean;
133
+ }>;
134
+ /**
135
+ * Refuses an RPC an x402 payment on `network` cannot be built through, then
136
+ * checks that it serves `network` (D-023). On Stellar the client accepts only
137
+ * an https RPC. Throws `RpcIdentityError` (a configuration error) before the
138
+ * target is sent anything; the RPC's address is never echoed (it may carry a
139
+ * key). The CLI calls it before it starts a service.
140
+ */
141
+ export declare function assertX402PaymentRpc(network: string, rpcUrl: string): Promise<void>;
57
142
  /**
58
143
  * Reads the settlement a paid response reports, before anything is looked up.
59
144
  *
@@ -94,4 +179,4 @@ export declare const X402_PAYMENT_CHECK_IDS: readonly string[];
94
179
  * target must refuse; a target that accepts the underpaid one may settle it.
95
180
  * See docs/CHECKS.md.
96
181
  */
97
- export declare function runX402PaymentChecks(options: X402PaymentCheckOptions): Promise<CheckResult[]>;
182
+ export declare function runX402PaymentChecks(input: X402PaymentCheckOptions): Promise<CheckResult[]>;