@wasit-dev/core 0.8.0-beta.1 → 0.8.0-beta.3

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 (60) hide show
  1. package/README.md +13 -2
  2. package/dist/baseline.d.ts +3 -1
  3. package/dist/baseline.js +23 -9
  4. package/dist/check.d.ts +1 -1
  5. package/dist/ci-report.js +20 -8
  6. package/dist/config-writer.d.ts +96 -0
  7. package/dist/config-writer.js +281 -0
  8. package/dist/guard/budget.d.ts +7 -4
  9. package/dist/guard/budget.js +11 -4
  10. package/dist/guard/ci-event.d.ts +6 -0
  11. package/dist/guard/ci-event.js +7 -3
  12. package/dist/guard/ci-mainnet.d.ts +59 -0
  13. package/dist/guard/ci-mainnet.js +149 -0
  14. package/dist/guard/horizon.d.ts +30 -0
  15. package/dist/guard/horizon.js +107 -0
  16. package/dist/guard/mainnet-optin.d.ts +3 -1
  17. package/dist/guard/mainnet-optin.js +8 -2
  18. package/dist/guard/mainnet-payer.d.ts +66 -0
  19. package/dist/guard/mainnet-payer.js +92 -0
  20. package/dist/guard/mainnet-plan.d.ts +133 -0
  21. package/dist/guard/mainnet-plan.js +208 -0
  22. package/dist/guard/mainnet-run.d.ts +87 -0
  23. package/dist/guard/mainnet-run.js +225 -0
  24. package/dist/guard/networks.d.ts +9 -8
  25. package/dist/guard/networks.js +21 -10
  26. package/dist/guard/optin.d.ts +106 -0
  27. package/dist/guard/optin.js +202 -0
  28. package/dist/guard/run-ledger.d.ts +212 -0
  29. package/dist/guard/run-ledger.js +426 -0
  30. package/dist/guard/run-lock.d.ts +62 -0
  31. package/dist/guard/run-lock.js +172 -0
  32. package/dist/guard/signed-terms.d.ts +135 -0
  33. package/dist/guard/signed-terms.js +252 -0
  34. package/dist/index.d.ts +18 -7
  35. package/dist/index.js +19 -5
  36. package/dist/mpp/channel-credential.d.ts +13 -1
  37. package/dist/mpp/channel-credential.js +18 -2
  38. package/dist/mpp/channel.d.ts +6 -0
  39. package/dist/mpp/channel.js +7 -3
  40. package/dist/mpp/charge.d.ts +31 -1
  41. package/dist/mpp/charge.js +74 -20
  42. package/dist/mpp/plan.d.ts +77 -0
  43. package/dist/mpp/plan.js +188 -0
  44. package/dist/mpp/suite.d.ts +6 -0
  45. package/dist/mpp/suite.js +2 -1
  46. package/dist/route-reader.d.ts +124 -0
  47. package/dist/route-reader.js +349 -0
  48. package/dist/wallet.d.ts +58 -1
  49. package/dist/wallet.js +128 -0
  50. package/dist/x402/chains/stellar.d.ts +39 -4
  51. package/dist/x402/chains/stellar.js +224 -19
  52. package/dist/x402/chains/svm.js +6 -2
  53. package/dist/x402/chains/types.d.ts +44 -2
  54. package/dist/x402/plan.d.ts +102 -0
  55. package/dist/x402/plan.js +380 -6
  56. package/dist/x402/rejected-request.d.ts +10 -0
  57. package/dist/x402/rejected-request.js +18 -0
  58. package/dist/x402/simulator.d.ts +34 -0
  59. package/dist/x402/simulator.js +461 -50
  60. package/package.json +9 -9
package/README.md CHANGED
@@ -4,7 +4,7 @@ The check suite behind [`@wasit-dev/cli`](https://www.npmjs.com/package/@wasit-d
4
4
 
5
5
  This package holds the actual check logic. The CLI and the MCP server are thin adapters over these same functions, so a CLI run and an agent's run can never disagree about the same target — there is only one implementation of each check.
6
6
 
7
- **Testnet only.** Several checks settle real transactions on-chain. In 0.8.0-beta.1 (npm tag `beta`; `latest` is 0.7.0) every payment check pays on test networks only: any other network, `stellar:pubnet` included, is refused before a key is read.
7
+ **Testnet only.** Several checks settle real transactions on-chain. In 0.8.0-beta.3 (npm tag `beta`; `latest` is 0.7.0) every payment check pays on test networks only: any other network, `stellar:pubnet` included, is refused before a key is read. The mainnet opt-in (beta) is the one exception: x402 on `stellar:pubnet` through `openMainnetOptIn`, which every front end calls.
8
8
 
9
9
  Most people should reach for [`@wasit-dev/cli`](https://www.npmjs.com/package/@wasit-dev/cli) (terminal) or [`@wasit-dev/server`](https://www.npmjs.com/package/@wasit-dev/server) (MCP / agents) instead of this package directly. Install `@wasit-dev/core` yourself only if you're building your own tooling on top of the check suite.
10
10
 
@@ -81,7 +81,7 @@ Every check function returns `Promise<CheckResult[]>` and never rejects for a ta
81
81
  | `checkStatus(result)` | → `"PASS" \| "FAIL" \| "ERROR" \| "SKIP"` |
82
82
  | `summarize(results)` | → `{ passed, failed, errored, skipped, exitCode }` — `exitCode` is `0 \| 1 \| 2`, shared by both front ends so they can never disagree about the same run |
83
83
  | `errored(id, name, error)` | Builds an `ERROR` result — mostly useful writing your own check |
84
- | `skipped(id, name, reason)` | Builds a non-destructive `SKIP` result |
84
+ | `skipped(id, name, reason, kind?)` | Builds a non-destructive `SKIP` result. `kind` says what sort of reason it is: `read-only`, `needs-payer`, `unsupported`, `resource-consumed`, `not-applicable` or `dependency` |
85
85
  | `skippedDestructive(id, name, reason)` | Builds a `SKIP` result for a destructive check not opted into |
86
86
 
87
87
  The full check catalogue — every check's exact pass criteria and spec reference — is in [`docs/CHECKS.md`](https://github.com/wasit-dev/wasit/blob/main/docs/CHECKS.md).
@@ -110,6 +110,16 @@ The catalogue is a short-form companion to [`docs/CHECKS.md`](https://github.com
110
110
  | `classifyCheckError(error)` | → `ClassifiedError` — maps an unknown throw to the `errorKind` (`"unreachable"`, `"configuration"`, `"harness"`) that appears in structured output |
111
111
  | `assertHttpUrl(target)`, `fetchTarget(...)` | The URL guard and bounded fetch the checks themselves use |
112
112
 
113
+ ### Writing a config (`wasit init`, new in 0.8.0-beta.2)
114
+
115
+ The building blocks of `wasit init`: data that is certain in, a `wasit.config.json` that `wasit run` accepts out.
116
+
117
+ | Export | Signature |
118
+ |---|---|
119
+ | `readRoute(url, shape, options?)` | → `Promise<RouteReading>` — sends the route one unpaid request and reads its answer: x402 or MPP, the network, the price, the asset, the receiving address, an MPP channel; or that it answered 200, 500 or 503, or did not answer. Pays and signs nothing |
120
+ | `interpretRouteAnswer(answer)` / `chooseOffer(offers, wanted?)` | The same reading over a recorded answer, without a network; and the one way to pay that `init` writes for the route, or why it writes none |
121
+ | `writeConfigText(input, options?)` | → `{ text, added, unchanged, environmentAdded, serviceAdded, changed }`. Writes only for an environment with `operatedByMe: true` on a test network, checks the result with the loader `wasit run` uses, adds to an existing file and never overwrites it (`replace` starts from nothing). An endpoint the file already has exactly as given is `unchanged`, and `changed` is false when nothing needs writing. Throws `ConfigWriteError`, and writes nothing |
122
+
113
123
  ### Testnet wallet helpers
114
124
 
115
125
  A convenience layer for setting up the keys the check functions read. It is not part of the check surface, and it is exported by name rather than with `export *` so `wallet.ts` stays free to change without that being a breaking change to this package.
@@ -123,6 +133,7 @@ A convenience layer for setting up the keys the check functions read. It is not
123
133
  | `fundWithFriendbot(publicKey, attempts?)` | → `Promise<FriendbotOutcome>` — `"funded"` or `"already-funded"`. Two different claims: an account that already exists is a success, but no transfer happened |
124
134
  | `createUsdcTrustline(secretKey, source?)` | → `Promise<void>` — opens the Circle testnet USDC trustline. A trustline is not a balance |
125
135
  | `sendUsdcFromDistributor(distributorSecretKey, destinationPublicKey, amount)` | → `Promise<void>` — `amount` is a positive decimal string, at most 7 places |
136
+ | `addTestnetUsdc(secretKey, source?)` | → `Promise<UsdcSetupOutcome>` — `{ swapped: true }` or `{ swapped: false, why }`. Opens the trustline and, when the public test exchange gives a usable price, swaps `TESTNET_SWAP_XLM` (10) test XLM for test USDC in the same transaction (at least 80% of the quote); otherwise it opens the trustline alone and says why. Throws only when the trustline fails |
126
137
  | `testnetUsdcAsset()` / `TESTNET_USDC_ISSUER` | The Circle testnet USDC `Asset` and its issuer address |
127
138
  | `describeTransactionError(error)` | → `string` — Horizon result codes formatted for a human |
128
139
 
@@ -42,10 +42,12 @@ export interface RecentFailure {
42
42
  readonly check: string;
43
43
  /** Runs in which the check failed. */
44
44
  readonly failed: number;
45
+ /** Runs in which the check could not run (ERROR), so no verdict was given. */
46
+ readonly errored: number;
45
47
  /** Runs the history holds for it. */
46
48
  readonly runs: number;
47
49
  }
48
- /** The checks that failed in at least one run of the history, most failures first. */
50
+ /** The checks that failed or could not run in at least one run of the history, most first. */
49
51
  export declare function recentFailures(history: History): RecentFailure[];
50
52
  export interface Baseline {
51
53
  readonly report: RunReport;
package/dist/baseline.js CHANGED
@@ -85,7 +85,9 @@ function readResult(raw, path) {
85
85
  ...(entry["skipKind"] === undefined ? {} : { skipKind: oneOf(entry["skipKind"], SKIP_KINDS, at(path, "skipKind")) }),
86
86
  ...(entry["expected"] === undefined ? {} : { expected: text(entry["expected"], at(path, "expected"), 500) }),
87
87
  ...(entry["actual"] === undefined ? {} : { actual: text(entry["actual"], at(path, "actual"), 500) }),
88
- ...(entry["reference"] === undefined ? {} : { reference: text(entry["reference"], at(path, "reference"), 120) }),
88
+ // Wasit writes a reference only on a PASS that read its settlement back (`toStructuredRun`); a file that
89
+ // carries one on another status is not taken at its word.
90
+ ...(entry["reference"] === undefined || status !== "PASS" ? {} : { reference: text(entry["reference"], at(path, "reference"), 120) }),
89
91
  ...(entry["fix"] === undefined ? {} : { fix: text(entry["fix"], at(path, "fix"), 2000) }),
90
92
  ...(entry["docs"] === undefined ? {} : { docs: text(entry["docs"], at(path, "docs"), 300) }),
91
93
  };
@@ -208,17 +210,18 @@ export function updateHistory(previous, report) {
208
210
  ];
209
211
  }));
210
212
  }
211
- /** The checks that failed in at least one run of the history, most failures first. */
213
+ /** The checks that failed or could not run in at least one run of the history, most first. */
212
214
  export function recentFailures(history) {
213
215
  const failures = [];
214
216
  for (const [endpoint, checks] of Object.entries(history)) {
215
217
  for (const [check, letters] of Object.entries(checks)) {
216
218
  const failed = [...letters].filter((letter) => letter === "F").length;
217
- if (failed > 0)
218
- failures.push({ endpoint, check, failed, runs: letters.length });
219
+ const errored = [...letters].filter((letter) => letter === "E").length;
220
+ if (failed + errored > 0)
221
+ failures.push({ endpoint, check, failed, errored, runs: letters.length });
219
222
  }
220
223
  }
221
- return failures.sort((a, b) => b.failed - a.failed);
224
+ return failures.sort((a, b) => b.failed + b.errored - (a.failed + a.errored));
222
225
  }
223
226
  /**
224
227
  * Reads a baseline file. Never throws: a file that is too large, is not JSON, is
@@ -289,11 +292,20 @@ function statuses(endpoint) {
289
292
  }
290
293
  return map;
291
294
  }
295
+ function skippedByTier(result) {
296
+ return result.status === "SKIP" && (result.skipKind === "read-only" || result.skipKind === "needs-payer");
297
+ }
292
298
  /** The checks of an endpoint that its run skipped because of the tier: read-only, or no payer key. */
293
299
  function notRunByTier(endpoint) {
294
- return new Set(endpoint.results
295
- .filter((result) => result.status === "SKIP" && (result.skipKind === "read-only" || result.skipKind === "needs-payer"))
296
- .map((result) => result.id));
300
+ return new Set(endpoint.results.filter(skippedByTier).map((result) => result.id));
301
+ }
302
+ /**
303
+ * Whether the run skipped every check of the endpoint for its tier, so it says
304
+ * nothing about the service: an MPP endpoint on a pull request (no MPP check is
305
+ * read-only), or a run without the key. An endpoint with no results is not.
306
+ */
307
+ function onlyNotRunByTier(endpoint) {
308
+ return endpoint.results.length > 0 && endpoint.results.every(skippedByTier);
297
309
  }
298
310
  /**
299
311
  * What changed against the baseline, by endpoint name: new and removed
@@ -313,7 +325,9 @@ export function diffReports(report, baseline) {
313
325
  }
314
326
  const wasGraded = GRADED.includes(earlier.outcome);
315
327
  const isGraded = GRADED.includes(endpoint.outcome);
316
- if (wasGraded && !isGraded) {
328
+ // Not graded now only because the tier skipped every check of it: no regression (D-021 as amended by
329
+ // Najmi, 2026-11-29). The checks are then all "not run by the tier" below, so no change is listed for it.
330
+ if (wasGraded && !isGraded && !onlyNotRunByTier(endpoint)) {
317
331
  changes.push({ kind: "regression", endpoint: endpoint.name, from: earlier.outcome, to: endpoint.outcome });
318
332
  }
319
333
  else if (!wasGraded && isGraded) {
package/dist/check.d.ts CHANGED
@@ -44,7 +44,7 @@ export interface CheckResult {
44
44
  /**
45
45
  * The settlement a check read back from the chain and found to be this
46
46
  * payment (X402-06's transaction: a Stellar or EVM transaction hash, a Solana
47
- * signature). Set only on a PASS whose settlement was verified on chain; a
47
+ * signature; MPP-01's Stellar transaction hash). Set only on a PASS whose settlement was verified on chain; a
48
48
  * report may link it to an explorer after checking its shape.
49
49
  */
50
50
  reference?: string;
package/dist/ci-report.js CHANGED
@@ -126,21 +126,29 @@ function verdictOf(input) {
126
126
  : "no verdict";
127
127
  return { baseline, note, code: verdict.code, word };
128
128
  }
129
+ /** The check whose settlement a protocol's payment proof links: the one that pays once and is read back from the chain. */
130
+ const PROOF_CHECK = {
131
+ x402: "X402-06",
132
+ "mpp-charge": "MPP-01",
133
+ };
129
134
  /**
130
- * The payment proof under an endpoint: a link to X402-06's transaction on
131
- * Stellar Expert, and only when every part is Wasit's own and checked: the run
132
- * is on `stellar:testnet`, X402-06 passed, and its reference (read back from the
133
- * chain by the check) is a 64-character lower-case hex hash. Never a link built
134
- * from a service's text.
135
+ * The payment proof under an endpoint: a link to the transaction of X402-06
136
+ * (x402) or MPP-01 (MPP charge) on Stellar Expert, and only when every part is
137
+ * Wasit's own and checked: the run is on `stellar:testnet`, that check passed,
138
+ * and its reference (read back from the chain by the check) is a 64-character
139
+ * lower-case hex hash. Never a link built from a service's text.
135
140
  */
136
141
  function paymentProof(endpoint, network) {
137
142
  if (network !== "stellar:testnet")
138
143
  return undefined;
139
- const honest = endpoint.results.find((result) => result.id === "X402-06" && result.status === "PASS");
144
+ const check = PROOF_CHECK[endpoint.protocol];
145
+ if (check === undefined)
146
+ return undefined;
147
+ const honest = endpoint.results.find((result) => result.id === check && result.status === "PASS");
140
148
  const reference = honest?.reference;
141
149
  if (reference === undefined || !STELLAR_TX.test(reference))
142
150
  return undefined;
143
- return (`**Payment proof**: X402-06 settled on stellar:testnet, ` +
151
+ return (`**Payment proof**: ${check} settled on stellar:testnet, ` +
144
152
  `[tx ${reference.slice(0, 4)}…${reference.slice(-4)} on Stellar Expert](https://stellar.expert/explorer/testnet/tx/${reference}).`);
145
153
  }
146
154
  /** An endpoint's heading and the table of its checks, each with its mark, then its payment proof. */
@@ -245,7 +253,11 @@ function renderBody(input) {
245
253
  if (recent.length > 0) {
246
254
  out.push("", "### Recent failures on main");
247
255
  for (const item of recent.slice(0, MAX_RECENT_SHOWN)) {
248
- out.push(`- ${md(item.endpoint)} ${md(item.check)}: failed in ${item.failed} of the last ${item.runs} runs on main`);
256
+ const what = [
257
+ ...(item.failed > 0 ? [`failed in ${item.failed}`] : []),
258
+ ...(item.errored > 0 ? [`could not run in ${item.errored}`] : []),
259
+ ].join(" and ");
260
+ out.push(`- ${md(item.endpoint)} ${md(item.check)}: ${what} of the last ${item.runs} runs on main`);
249
261
  }
250
262
  }
251
263
  if (report.notes.length > 0) {
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The config writer of `wasit init` (spec C; init-skeleton-plan.md section 6,
3
+ * Najmi's rule of 2026-11-15: the writer takes only data that is certain).
4
+ *
5
+ * Data in, the text of a `wasit.config.json` out, checked by the same
6
+ * validator `wasit run` and the Action read it with, so init can never write
7
+ * a file they refuse. Every field is given: the writer has no defaults of its
8
+ * own and guesses nothing. It writes an environment only for a service its
9
+ * operator runs (`operatedByMe` true, literally) and, in this version, only on
10
+ * a test network. It never writes a secret (the validator refuses one), a
11
+ * header of the endpoint (a credential goes in `WASIT_HEADER_*`), the mainnet
12
+ * opt-in (not a config value at all) or anything that enables MPP-13.
13
+ *
14
+ * Adding to an existing file is the default: the file is read as it is, its
15
+ * own keys kept, and the new endpoints appended; an endpoint name it already
16
+ * has, or an environment of the same name with other values, is refused, never
17
+ * overwritten. One exception, so init can be run again on the same route (to
18
+ * set up its key, say): an endpoint the file already has with every value init
19
+ * writes the same, in an environment the file already has the same, is left as
20
+ * it is and counted as unchanged. `replace` starts from nothing.
21
+ *
22
+ * Pure: no file, no network, no key.
23
+ */
24
+ import type { ProtocolId } from "./catalogue.js";
25
+ import { type JsonValue, type PinConfig, type ReadyConfig } from "./config.js";
26
+ import { ConfigurationError } from "./errors.js";
27
+ /** The writer will not write this config: nothing is written. */
28
+ export declare class ConfigWriteError extends ConfigurationError {
29
+ constructor(message: string);
30
+ }
31
+ export interface InitEnvironmentInput {
32
+ readonly name: string;
33
+ readonly baseUrl: string;
34
+ readonly network: string;
35
+ /** Literally true: init writes an environment only for a service its operator runs. */
36
+ readonly operatedByMe: true;
37
+ readonly pinned?: PinConfig;
38
+ }
39
+ export interface InitRejectInput {
40
+ readonly method?: string;
41
+ readonly headers?: Readonly<Record<string, string>>;
42
+ readonly body?: JsonValue;
43
+ readonly note?: string;
44
+ }
45
+ export interface InitEndpointInput {
46
+ readonly name: string;
47
+ readonly protocol: ProtocolId;
48
+ readonly path: string;
49
+ readonly method: string;
50
+ readonly body?: JsonValue;
51
+ /** The request the service must refuse (X402-11). */
52
+ readonly reject?: InitRejectInput;
53
+ /** An MPP channel endpoint: the channel contract it bills through. */
54
+ readonly channel?: string;
55
+ }
56
+ export interface InitServiceInput {
57
+ readonly start: string;
58
+ readonly ready: ReadyConfig;
59
+ }
60
+ export interface ConfigWriteInput {
61
+ readonly environment: InitEnvironmentInput;
62
+ readonly endpoints: readonly InitEndpointInput[];
63
+ readonly service?: InitServiceInput;
64
+ }
65
+ export interface ConfigWriteOptions {
66
+ /** The text of the config already at the destination, when there is one. */
67
+ readonly existing?: string;
68
+ /** Start from nothing instead of adding to `existing` (`--force`). */
69
+ readonly replace?: boolean;
70
+ }
71
+ export interface ConfigWriteResult {
72
+ /** The whole file, two-space JSON, ending in one line break. */
73
+ readonly text: string;
74
+ /** The endpoints this write added, by name. */
75
+ readonly added: readonly string[];
76
+ /** The endpoints the file already had exactly as given, by name: left as they are. */
77
+ readonly unchanged: readonly string[];
78
+ /** Whether the environment is new in the file. */
79
+ readonly environmentAdded: boolean;
80
+ /** Whether the service block is new in the file. */
81
+ readonly serviceAdded: boolean;
82
+ /**
83
+ * Whether the file needs writing: false when it already holds everything
84
+ * given (every endpoint unchanged, the environment and the service already
85
+ * there). The caller then leaves the file as it is, byte for byte.
86
+ */
87
+ readonly changed: boolean;
88
+ }
89
+ /**
90
+ * The text of the config with `input` in it: a new file, or `existing` with
91
+ * the new endpoints appended. Checked by `validateConfig` before it is
92
+ * returned.
93
+ *
94
+ * @throws {ConfigWriteError} When the data, the existing file or the result is not one init writes. Nothing is to be written then.
95
+ */
96
+ export declare function writeConfigText(input: ConfigWriteInput, options?: ConfigWriteOptions): ConfigWriteResult;
@@ -0,0 +1,281 @@
1
+ /**
2
+ * The config writer of `wasit init` (spec C; init-skeleton-plan.md section 6,
3
+ * Najmi's rule of 2026-11-15: the writer takes only data that is certain).
4
+ *
5
+ * Data in, the text of a `wasit.config.json` out, checked by the same
6
+ * validator `wasit run` and the Action read it with, so init can never write
7
+ * a file they refuse. Every field is given: the writer has no defaults of its
8
+ * own and guesses nothing. It writes an environment only for a service its
9
+ * operator runs (`operatedByMe` true, literally) and, in this version, only on
10
+ * a test network. It never writes a secret (the validator refuses one), a
11
+ * header of the endpoint (a credential goes in `WASIT_HEADER_*`), the mainnet
12
+ * opt-in (not a config value at all) or anything that enables MPP-13.
13
+ *
14
+ * Adding to an existing file is the default: the file is read as it is, its
15
+ * own keys kept, and the new endpoints appended; an endpoint name it already
16
+ * has, or an environment of the same name with other values, is refused, never
17
+ * overwritten. One exception, so init can be run again on the same route (to
18
+ * set up its key, say): an endpoint the file already has with every value init
19
+ * writes the same, in an environment the file already has the same, is left as
20
+ * it is and counted as unchanged. `replace` starts from nothing.
21
+ *
22
+ * Pure: no file, no network, no key.
23
+ */
24
+ import { ConfigError, validateConfig } from "./config.js";
25
+ import { ConfigurationError } from "./errors.js";
26
+ import { networkClass } from "./guard/networks.js";
27
+ import { sanitizeText } from "./sanitize.js";
28
+ /** The writer will not write this config: nothing is written. */
29
+ export class ConfigWriteError extends ConfigurationError {
30
+ constructor(message) {
31
+ super(message);
32
+ this.name = "ConfigWriteError";
33
+ }
34
+ }
35
+ function isRecord(value) {
36
+ return typeof value === "object" && value !== null && !Array.isArray(value);
37
+ }
38
+ /** A name or a value for a message: one line, no control characters, bounded. */
39
+ function shown(value) {
40
+ const text = sanitizeText(String(value)).replace(/\s+/g, " ");
41
+ return JSON.stringify(text.length > 80 ? `${text.slice(0, 77)}...` : text);
42
+ }
43
+ function rawEnvironment(environment) {
44
+ return {
45
+ baseUrl: environment.baseUrl,
46
+ network: environment.network,
47
+ operatedByMe: environment.operatedByMe,
48
+ ...(environment.pinned === undefined ? {} : { pinned: { payTo: environment.pinned.payTo, asset: environment.pinned.asset } }),
49
+ };
50
+ }
51
+ function rawEndpoint(endpoint) {
52
+ const reject = endpoint.reject;
53
+ return {
54
+ name: endpoint.name,
55
+ protocol: endpoint.protocol,
56
+ path: endpoint.path,
57
+ method: endpoint.method,
58
+ ...(endpoint.body === undefined ? {} : { body: endpoint.body }),
59
+ ...(reject === undefined
60
+ ? {}
61
+ : {
62
+ reject: {
63
+ ...(reject.method === undefined ? {} : { method: reject.method }),
64
+ ...(reject.headers === undefined ? {} : { headers: { ...reject.headers } }),
65
+ ...(reject.body === undefined ? {} : { body: reject.body }),
66
+ ...(reject.note === undefined ? {} : { note: reject.note }),
67
+ },
68
+ }),
69
+ ...(endpoint.channel === undefined ? {} : { channel: endpoint.channel }),
70
+ };
71
+ }
72
+ function rawService(service) {
73
+ return { start: service.start, ready: { url: service.ready.url, timeoutSeconds: service.ready.timeoutSeconds } };
74
+ }
75
+ /** The rules on the data itself, before any file is looked at. */
76
+ function assertCertain(input) {
77
+ const { environment, endpoints } = input;
78
+ if (environment.operatedByMe !== true) {
79
+ throw new ConfigWriteError("init writes an environment only for a service you operate (operatedByMe true): Wasit tests only services " +
80
+ "their operator runs. Nothing was written.");
81
+ }
82
+ const kind = networkClass(environment.network);
83
+ if (kind !== "test") {
84
+ throw new ConfigWriteError(kind === "mainnet-optin"
85
+ ? `${shown(environment.network)} is Stellar mainnet: init writes test networks only in this version. Nothing was written.`
86
+ : `${shown(environment.network)} is not on Wasit's list of test networks, so init does not write it. Nothing was written.`);
87
+ }
88
+ if (endpoints.length === 0)
89
+ throw new ConfigWriteError("init writes at least one endpoint. Nothing was written.");
90
+ const names = new Set();
91
+ for (const endpoint of endpoints) {
92
+ if (names.has(endpoint.name)) {
93
+ throw new ConfigWriteError(`The endpoint name ${shown(endpoint.name)} is given twice. Nothing was written.`);
94
+ }
95
+ names.add(endpoint.name);
96
+ }
97
+ }
98
+ /** The existing file's JSON, valid as a config, or why init leaves it as it is. */
99
+ function existingConfig(text) {
100
+ const source = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
101
+ let raw;
102
+ try {
103
+ raw = JSON.parse(source);
104
+ validateConfig(raw);
105
+ }
106
+ catch (error) {
107
+ const why = error instanceof ConfigError ? error.message : "it is not valid JSON";
108
+ throw new ConfigWriteError(`The config already there is not valid, so init does not change it (${sanitizeText(why).replace(/\s+/g, " ")}). ` +
109
+ `Fix it, or replace it (--force).`);
110
+ }
111
+ return raw;
112
+ }
113
+ /** Whether the file's environment is the one being written: the same URL, network, operator and pin. */
114
+ function sameEnvironment(existing, environment) {
115
+ if (!isRecord(existing))
116
+ return false;
117
+ const network = existing["network"] ?? "stellar:testnet";
118
+ const pinned = existing["pinned"];
119
+ const pinSame = environment.pinned === undefined
120
+ ? pinned === undefined
121
+ : isRecord(pinned) && pinned["payTo"] === environment.pinned.payTo && pinned["asset"] === environment.pinned.asset;
122
+ return existing["baseUrl"] === environment.baseUrl && network === environment.network && existing["operatedByMe"] === true && pinSame;
123
+ }
124
+ /** Whether two JSON values are equal: objects by their keys, in any order; arrays in order. */
125
+ function sameJson(a, b) {
126
+ if (a === b)
127
+ return true;
128
+ if (Array.isArray(a) || Array.isArray(b)) {
129
+ return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, index) => sameJson(item, b[index]));
130
+ }
131
+ if (!isRecord(a) || !isRecord(b))
132
+ return false;
133
+ const keys = Object.keys(a);
134
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && sameJson(a[key], b[key]));
135
+ }
136
+ /** A method as the loader reads it: GET when it is left out, in capitals. */
137
+ function methodOf(value) {
138
+ const method = value ?? "GET";
139
+ return typeof method === "string" ? method.toUpperCase() : method;
140
+ }
141
+ /**
142
+ * The values init writes of an endpoint, as the loader reads them, from the
143
+ * file or from what init would write. `headers` and `expect` are not among
144
+ * them: init never writes either (a credential goes in `WASIT_HEADER_*`, and
145
+ * a channel's on-chain terms are the builder's to add by hand), so the file's
146
+ * own are the builder's and are kept.
147
+ */
148
+ function writtenValues(endpoint) {
149
+ const reject = endpoint["reject"];
150
+ return {
151
+ name: endpoint["name"],
152
+ protocol: endpoint["protocol"],
153
+ path: endpoint["path"],
154
+ method: methodOf(endpoint["method"]),
155
+ body: endpoint["body"],
156
+ reject: isRecord(reject) ? { ...reject, ...(reject["method"] === undefined ? {} : { method: methodOf(reject["method"]) }) } : reject,
157
+ channel: endpoint["channel"],
158
+ };
159
+ }
160
+ /** The values of an endpoint init writes that differ between the file's endpoint and the one given: their keys, in order. */
161
+ function endpointDifferences(existing, given) {
162
+ const there = writtenValues(existing);
163
+ const here = writtenValues(given);
164
+ return Object.keys(here).filter((key) => !sameJson(there[key], here[key]));
165
+ }
166
+ /** "path", "method and body", "path, method and body". */
167
+ function listed(words) {
168
+ return words.length <= 1 ? (words[0] ?? "") : `${words.slice(0, -1).join(", ")} and ${words.at(-1)}`;
169
+ }
170
+ function sameService(existing, service) {
171
+ if (!isRecord(existing))
172
+ return false;
173
+ const ready = existing["ready"];
174
+ return (existing["start"] === service.start &&
175
+ isRecord(ready) &&
176
+ ready["url"] === service.ready.url &&
177
+ ready["timeoutSeconds"] === service.ready.timeoutSeconds);
178
+ }
179
+ /**
180
+ * The text of the config with `input` in it: a new file, or `existing` with
181
+ * the new endpoints appended. Checked by `validateConfig` before it is
182
+ * returned.
183
+ *
184
+ * @throws {ConfigWriteError} When the data, the existing file or the result is not one init writes. Nothing is to be written then.
185
+ */
186
+ export function writeConfigText(input, options = {}) {
187
+ assertCertain(input);
188
+ const { environment } = input;
189
+ const endpoints = input.endpoints.map(rawEndpoint);
190
+ const base = options.existing !== undefined && options.replace !== true ? existingConfig(options.existing) : undefined;
191
+ let ordered;
192
+ let environmentAdded = true;
193
+ let serviceAdded = input.service !== undefined;
194
+ let appended = endpoints;
195
+ const unchanged = [];
196
+ if (base === undefined) {
197
+ ordered = {
198
+ version: 1,
199
+ ...(input.service === undefined ? {} : { service: rawService(input.service) }),
200
+ defaultEnvironment: environment.name,
201
+ environments: { [environment.name]: rawEnvironment(environment) },
202
+ endpoints,
203
+ };
204
+ }
205
+ else {
206
+ const environments = { ...base["environments"] };
207
+ if (Object.hasOwn(environments, environment.name)) {
208
+ if (!sameEnvironment(environments[environment.name], environment)) {
209
+ throw new ConfigWriteError(`The config already has an environment named ${shown(environment.name)} with another URL, network, operator or ` +
210
+ `pin, and init does not overwrite it. Choose another environment name, or replace the file (--force).`);
211
+ }
212
+ environmentAdded = false;
213
+ }
214
+ else {
215
+ environments[environment.name] = rawEnvironment(environment);
216
+ }
217
+ const before = base["endpoints"];
218
+ appended = [];
219
+ for (const endpoint of endpoints) {
220
+ const there = before.find((other) => other["name"] === endpoint["name"]);
221
+ if (there === undefined) {
222
+ appended.push(endpoint);
223
+ continue;
224
+ }
225
+ const differences = endpointDifferences(there, endpoint);
226
+ // The same route in the same environment: nothing to add, and nothing overwritten.
227
+ if (differences.length === 0 && !environmentAdded) {
228
+ unchanged.push(endpoint["name"]);
229
+ continue;
230
+ }
231
+ throw new ConfigWriteError(differences.length === 0
232
+ ? `The config already has an endpoint named ${shown(endpoint["name"])}, and init does not add it again with the ` +
233
+ `new environment ${shown(environment.name)}. Choose another name, or replace the file (--force).`
234
+ : `The config already has an endpoint named ${shown(endpoint["name"])} whose ${listed(differences)} ` +
235
+ `${differences.length === 1 ? "differs" : "differ"}, and init does not overwrite it. Choose another name, or ` +
236
+ "replace the file (--force).");
237
+ }
238
+ let service = base["service"];
239
+ if (input.service !== undefined) {
240
+ if (service === undefined) {
241
+ service = rawService(input.service);
242
+ }
243
+ else if (!sameService(service, input.service)) {
244
+ throw new ConfigWriteError("The config already says how to start the service, differently, and init does not overwrite it. " +
245
+ "Leave the start command out, or replace the file (--force).");
246
+ }
247
+ else {
248
+ serviceAdded = false;
249
+ }
250
+ }
251
+ // A file with one environment and no defaultEnvironment ran that environment; with a second one it keeps doing so.
252
+ const previous = Object.keys(base["environments"]);
253
+ const defaultEnvironment = base["defaultEnvironment"] ?? (previous.length === 1 ? previous[0] : undefined);
254
+ ordered = {
255
+ ...(base["$schema"] === undefined ? {} : { $schema: base["$schema"] }),
256
+ version: 1,
257
+ ...(service === undefined ? {} : { service }),
258
+ ...(defaultEnvironment === undefined ? {} : { defaultEnvironment }),
259
+ environments,
260
+ endpoints: [...before, ...appended],
261
+ };
262
+ }
263
+ const text = `${JSON.stringify(ordered, null, 2)}\n`;
264
+ try {
265
+ validateConfig(JSON.parse(text));
266
+ }
267
+ catch (error) {
268
+ if (error instanceof ConfigError) {
269
+ throw new ConfigWriteError(`init would write a config that wasit run does not accept, so it writes nothing:\n${error.message}`);
270
+ }
271
+ throw error;
272
+ }
273
+ return {
274
+ text,
275
+ added: appended.map((endpoint) => endpoint["name"]),
276
+ unchanged,
277
+ environmentAdded,
278
+ serviceAdded,
279
+ changed: appended.length > 0 || environmentAdded || serviceAdded,
280
+ };
281
+ }
@@ -6,8 +6,9 @@
6
6
  * in USDC (the SDK client's default assets, plus Circle's USDC on Ethereum
7
7
  * Sepolia), so the table below lists USDC on each test network with its
8
8
  * decimals, and a payment in any other asset is refused: Wasit cannot hold it
9
- * to the cap. Nothing on mainnet is listed: this version pays on test networks
10
- * only, and the mainnet USDC constant waits for the opt-in (B4, B12).
9
+ * to the cap. On mainnet it lists Circle's USDC on Stellar mainnet only, the
10
+ * one asset a mainnet run pays in (B4); L0 refuses that network without the
11
+ * mainnet opt-in, so valuing it allows nothing by itself.
11
12
  *
12
13
  * Amounts in dollars are bigints at 10^-18 of a dollar, so 6 and 7 decimal
13
14
  * tokens add up exactly.
@@ -26,7 +27,7 @@ export interface UsdAsset {
26
27
  readonly symbol: string;
27
28
  }
28
29
  /**
29
- * USDC on each test network. Sources (read 2026-11-16): `@x402/stellar` 2.28.0
30
+ * USDC on each test network. Sources (read 2026-11-16, the same in 2.32.0 on 2026-11-29): `@x402/stellar` 2.28.0
30
31
  * `USDC_TESTNET_ADDRESS`, `DEFAULT_TOKEN_DECIMALS = 7`; `@x402/evm` 2.28.0 default
31
32
  * asset of `eip155:84532`, decimals 6; Circle's USDC on Ethereum Sepolia as
32
33
  * `chains/evm.ts` (`ETHEREUM_SEPOLIA_USDC`, 6 decimals read from the contract
@@ -37,11 +38,13 @@ export declare const USD_ASSETS: readonly UsdAsset[];
37
38
  export declare function sameAddress(network: string, a: string, b: string): boolean;
38
39
  /** The dollar asset `asset` is on `network`, if Wasit knows it. */
39
40
  export declare function usdAsset(network: string, asset: string): UsdAsset | undefined;
41
+ /** `amount` base units of a dollar token with `decimals` decimals, in this module's dollar units. */
42
+ export declare function usdFromBaseUnits(amount: bigint, decimals: number): bigint;
40
43
  /** Whole and fractional dollars, rounded down to a millionth: a cap is never rounded up. */
41
44
  export declare function usdFromDollars(dollars: number): bigint;
42
45
  /** "$4.50", "$0.0000001": exact, at least two decimals. */
43
46
  export declare function formatUsd(amount: bigint): string;
44
- export type GuardRefusal = "price" | "asset" | "amount" | "pin" | "plan" | "run-cap" | "accepted";
47
+ export type GuardRefusal = "price" | "asset" | "amount" | "pin" | "plan" | "run-cap" | "accepted" | "signed-terms";
45
48
  /**
46
49
  * A payment the guard will not sign, or, with `signed`, a signed payment it
47
50
  * will not send. A setup error: it says nothing about the target, and the
@@ -6,8 +6,9 @@
6
6
  * in USDC (the SDK client's default assets, plus Circle's USDC on Ethereum
7
7
  * Sepolia), so the table below lists USDC on each test network with its
8
8
  * decimals, and a payment in any other asset is refused: Wasit cannot hold it
9
- * to the cap. Nothing on mainnet is listed: this version pays on test networks
10
- * only, and the mainnet USDC constant waits for the opt-in (B4, B12).
9
+ * to the cap. On mainnet it lists Circle's USDC on Stellar mainnet only, the
10
+ * one asset a mainnet run pays in (B4); L0 refuses that network without the
11
+ * mainnet opt-in, so valuing it allows nothing by itself.
11
12
  *
12
13
  * Amounts in dollars are bigints at 10^-18 of a dollar, so 6 and 7 decimal
13
14
  * tokens add up exactly.
@@ -23,7 +24,7 @@ export const PER_RUN_CAP_USD = 5;
23
24
  /** A dollar, in the units this module counts in. */
24
25
  const DOLLAR = 10n ** 18n;
25
26
  /**
26
- * USDC on each test network. Sources (read 2026-11-16): `@x402/stellar` 2.28.0
27
+ * USDC on each test network. Sources (read 2026-11-16, the same in 2.32.0 on 2026-11-29): `@x402/stellar` 2.28.0
27
28
  * `USDC_TESTNET_ADDRESS`, `DEFAULT_TOKEN_DECIMALS = 7`; `@x402/evm` 2.28.0 default
28
29
  * asset of `eip155:84532`, decimals 6; Circle's USDC on Ethereum Sepolia as
29
30
  * `chains/evm.ts` (`ETHEREUM_SEPOLIA_USDC`, 6 decimals read from the contract
@@ -34,6 +35,8 @@ export const USD_ASSETS = [
34
35
  { network: "eip155:84532", asset: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", decimals: 6, symbol: "USDC" },
35
36
  { network: "eip155:11155111", asset: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238", decimals: 6, symbol: "USDC" },
36
37
  { network: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", asset: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU", decimals: 6, symbol: "USDC" },
38
+ // MAINNET_USDC of guard/mainnet-plan.ts (checked three ways there); a test asserts they are the same.
39
+ { network: "stellar:pubnet", asset: "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75", decimals: 7, symbol: "USDC" },
37
40
  ];
38
41
  /** Whether two addresses on `network` are the same: an EVM address in any letter case, others exactly. */
39
42
  export function sameAddress(network, a, b) {
@@ -45,9 +48,13 @@ export function sameAddress(network, a, b) {
45
48
  export function usdAsset(network, asset) {
46
49
  return USD_ASSETS.find((entry) => entry.network === network && sameAddress(network, entry.asset, asset));
47
50
  }
51
+ /** `amount` base units of a dollar token with `decimals` decimals, in this module's dollar units. */
52
+ export function usdFromBaseUnits(amount, decimals) {
53
+ return (amount * DOLLAR) / 10n ** BigInt(decimals);
54
+ }
48
55
  /** `amount` base units of `asset`, in this module's dollar units. */
49
56
  function toUsd(asset, amount) {
50
- return (amount * DOLLAR) / 10n ** BigInt(asset.decimals);
57
+ return usdFromBaseUnits(amount, asset.decimals);
51
58
  }
52
59
  /** Whole and fractional dollars, rounded down to a millionth: a cap is never rounded up. */
53
60
  export function usdFromDollars(dollars) {