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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +13 -2
  2. package/dist/baseline.js +3 -1
  3. package/dist/check.d.ts +1 -1
  4. package/dist/ci-report.js +15 -7
  5. package/dist/config-writer.d.ts +96 -0
  6. package/dist/config-writer.js +281 -0
  7. package/dist/guard/budget.d.ts +6 -3
  8. package/dist/guard/budget.js +10 -3
  9. package/dist/guard/ci-event.d.ts +6 -0
  10. package/dist/guard/ci-event.js +7 -3
  11. package/dist/guard/ci-mainnet.d.ts +59 -0
  12. package/dist/guard/ci-mainnet.js +149 -0
  13. package/dist/guard/horizon.d.ts +30 -0
  14. package/dist/guard/horizon.js +107 -0
  15. package/dist/guard/mainnet-payer.d.ts +66 -0
  16. package/dist/guard/mainnet-payer.js +92 -0
  17. package/dist/guard/mainnet-plan.d.ts +133 -0
  18. package/dist/guard/mainnet-plan.js +208 -0
  19. package/dist/guard/mainnet-run.d.ts +87 -0
  20. package/dist/guard/mainnet-run.js +225 -0
  21. package/dist/guard/networks.d.ts +9 -8
  22. package/dist/guard/networks.js +21 -10
  23. package/dist/guard/optin.d.ts +106 -0
  24. package/dist/guard/optin.js +202 -0
  25. package/dist/guard/run-ledger.d.ts +212 -0
  26. package/dist/guard/run-ledger.js +426 -0
  27. package/dist/guard/run-lock.d.ts +62 -0
  28. package/dist/guard/run-lock.js +172 -0
  29. package/dist/guard/signed-terms.d.ts +96 -0
  30. package/dist/guard/signed-terms.js +207 -0
  31. package/dist/index.d.ts +18 -7
  32. package/dist/index.js +19 -5
  33. package/dist/mpp/channel-credential.d.ts +13 -1
  34. package/dist/mpp/channel-credential.js +18 -2
  35. package/dist/mpp/channel.d.ts +6 -0
  36. package/dist/mpp/channel.js +7 -3
  37. package/dist/mpp/charge.d.ts +31 -1
  38. package/dist/mpp/charge.js +74 -20
  39. package/dist/mpp/plan.d.ts +77 -0
  40. package/dist/mpp/plan.js +188 -0
  41. package/dist/mpp/suite.d.ts +6 -0
  42. package/dist/mpp/suite.js +2 -1
  43. package/dist/route-reader.d.ts +124 -0
  44. package/dist/route-reader.js +349 -0
  45. package/dist/wallet.d.ts +58 -1
  46. package/dist/wallet.js +128 -0
  47. package/dist/x402/chains/stellar.js +134 -3
  48. package/dist/x402/chains/types.d.ts +36 -2
  49. package/dist/x402/plan.d.ts +102 -0
  50. package/dist/x402/plan.js +380 -6
  51. package/dist/x402/rejected-request.d.ts +10 -0
  52. package/dist/x402/rejected-request.js +18 -0
  53. package/dist/x402/simulator.d.ts +34 -0
  54. package/dist/x402/simulator.js +452 -46
  55. package/package.json +1 -1
  56. package/dist/guard/mainnet-optin.d.ts +0 -58
  57. package/dist/guard/mainnet-optin.js +0 -95
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.2 (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
 
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
  };
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. */
@@ -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.
@@ -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.
@@ -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) {
@@ -25,6 +25,12 @@ export interface PaymentEventGate {
25
25
  */
26
26
  readonly ciOutsideGithub?: true;
27
27
  }
28
+ /**
29
+ * The default branch the event payload names (`repository.default_branch`),
30
+ * in a shape that is safe to echo; undefined otherwise. The mainnet job rules
31
+ * hold the run's ref to it (spec B17.4).
32
+ */
33
+ export declare function githubDefaultBranch(event: unknown): string | undefined;
28
34
  /**
29
35
  * True when the process runs as a step of GitHub Actions, or says it does.
30
36
  * Fail closed: either variable counts, with any value that is not empty, as
@@ -32,8 +32,12 @@ function shownRef(ref) {
32
32
  return "no ref";
33
33
  return PRINTABLE_REF.test(ref) ? ref : "(a ref Wasit does not print)";
34
34
  }
35
- /** The default branch the event payload names, or undefined. */
36
- function defaultBranch(event) {
35
+ /**
36
+ * The default branch the event payload names (`repository.default_branch`),
37
+ * in a shape that is safe to echo; undefined otherwise. The mainnet job rules
38
+ * hold the run's ref to it (spec B17.4).
39
+ */
40
+ export function githubDefaultBranch(event) {
37
41
  if (event === null || typeof event !== "object")
38
42
  return undefined;
39
43
  const repository = event.repository;
@@ -72,7 +76,7 @@ export function paymentEventGate(env, event) {
72
76
  };
73
77
  }
74
78
  const ref = env["GITHUB_REF"] ?? "";
75
- const branch = defaultBranch(event);
79
+ const branch = githubDefaultBranch(event);
76
80
  if (branch === undefined) {
77
81
  // GitHub runs a schedule on the default branch, and its payload may not name
78
82
  // the repository; its ref must still be a branch.
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The rules for a mainnet job in GitHub Actions (spec B17.4).
3
+ *
4
+ * Inside one job, code that ran earlier as the runner's user can reach every
5
+ * later step: it can put a program of its own first on PATH, change files on
6
+ * disk, or leave a process running that reads the environment of the step
7
+ * that holds the key (and a GitHub-hosted runner's user has passwordless sudo).
8
+ * No check inside the job holds against such code, since that code can change
9
+ * the check. So these rules do not look for it: they refuse the workflows in
10
+ * which it would be there. A mainnet run in GitHub Actions is started by hand,
11
+ * on the default branch, on a GitHub-hosted runner (a fresh machine per job);
12
+ * it tests a deployed service, so no code of the service runs in the job; it
13
+ * runs where nothing was installed before Wasit; and the mainnet key is the
14
+ * only key variable set.
15
+ *
16
+ * They stop a wrong workflow, not a person or code that sets out to get past
17
+ * them. What holds against those is GitHub's: the mainnet key kept as the
18
+ * secret of a GitHub environment limited to the default branch, with a
19
+ * required reviewer. Outside GitHub Actions none of these rules applies: on a
20
+ * builder's own machine the CLI may test a local service.
21
+ *
22
+ * The opt-in (`openMainnetOptIn`) calls {@link assertMainnetJob} whenever
23
+ * `GITHUB_ACTIONS` is true, before the lock is taken and anything is sent.
24
+ */
25
+ import { ConfigurationError } from "../errors.js";
26
+ export interface MainnetJob {
27
+ /** The process environment. */
28
+ readonly env: Readonly<Record<string, string | undefined>>;
29
+ /** The repository's default branch, from the event; undefined when it cannot be read. */
30
+ readonly defaultBranch: string | undefined;
31
+ /** The run's environment starts a service in the job (`service.start`). */
32
+ readonly startsService: boolean;
33
+ /** The run's `baseUrl`. */
34
+ readonly baseUrl: string;
35
+ /** Where a `node_modules` would show that something was installed before Wasit, with a label for the message. */
36
+ readonly installDirs: ReadonlyArray<{
37
+ readonly label: string;
38
+ readonly dir: string;
39
+ }>;
40
+ }
41
+ /** A job that may not make a mainnet run, with every rule it breaks. */
42
+ export declare class MainnetJobRefusedError extends ConfigurationError {
43
+ readonly refusals: readonly string[];
44
+ constructor(refusals: readonly string[]);
45
+ }
46
+ /**
47
+ * A host only this machine or its own network reaches, as `URL.hostname`
48
+ * writes it: a loopback, private, link-local or shared address, `localhost`,
49
+ * a single-label name, or a `.local` or `.internal` name.
50
+ */
51
+ export declare function isLocalHost(hostname: string): boolean;
52
+ /**
53
+ * Every rule of a mainnet job that `job` breaks, one clause each; empty when it
54
+ * breaks none, and always empty outside GitHub Actions. No key, and no event
55
+ * name, ref or path in an odd shape, is echoed.
56
+ */
57
+ export declare function mainnetJobRefusals(job: MainnetJob, exists?: (file: string) => boolean): string[];
58
+ /** Throws {@link MainnetJobRefusedError} when `job` breaks any rule of a mainnet job. */
59
+ export declare function assertMainnetJob(job: MainnetJob, exists?: (file: string) => boolean): void;