@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,87 @@
1
+ /**
2
+ * Opening a mainnet run (spec B5, B18 O1): the one place a {@link MainnetOptIn}
3
+ * is made. A front end calls it only when its own switch is set (`--mainnet`,
4
+ * the Action's `mainnet: true` on workflow_dispatch, the MCP server's start-up
5
+ * setting); every other rule a mainnet x402 run needs before anything is sent
6
+ * is checked here, in core, so each front end gets the same refusals:
7
+ *
8
+ * 1. the config environment is on `stellar:pubnet` and has `operatedByMe: true`;
9
+ * 2. the key is read from `WASIT_MAINNET_PAYER_SECRET` only, is a Stellar
10
+ * secret, and is the value of no other key variable (a dedicated account);
11
+ * 3. the pin pays mainnet USDC to a valid payee that is not the payer;
12
+ * 4. an RPC is given (pubnet has no default), is https, and serves pubnet;
13
+ * 5. in GitHub Actions, the job keeps the mainnet job rules (B17.4);
14
+ * 6. no other mainnet run holds the lock in the ledger's folder.
15
+ *
16
+ * Only then is the opt-in made and the lock held. The key is read to derive
17
+ * the payer's address and is not kept. The plan (L1) comes next, with the
18
+ * opt-in: `planX402Run({ ..., mainnet })`.
19
+ */
20
+ import { RunBudget } from "./budget.js";
21
+ import { type MainnetJob } from "./ci-mainnet.js";
22
+ import { type MainnetFrontEnd, type MainnetOptIn } from "./optin.js";
23
+ import { type LedgerConsistency } from "./run-ledger.js";
24
+ import type { PinTerms } from "./budget.js";
25
+ /** The one variable a mainnet run reads its key from (spec B5 point 3). */
26
+ export declare const MAINNET_PAYER_KEY_ENV = "WASIT_MAINNET_PAYER_SECRET";
27
+ export { MainnetRunRefusedError, type MainnetRunRefusal } from "./optin.js";
28
+ export interface MainnetOptInInput {
29
+ readonly frontEnd: MainnetFrontEnd;
30
+ /** The process environment: the key and, in GitHub Actions, the job's variables. */
31
+ readonly env: Readonly<Record<string, string | undefined>>;
32
+ /** The config environment's name, its network, its `operatedByMe` and its pin. */
33
+ readonly environment: string;
34
+ readonly network: string;
35
+ readonly operatedByMe: boolean;
36
+ readonly pin: PinTerms | undefined;
37
+ /** The RPC the payment is built and the settlement read through. */
38
+ readonly rpcUrl: string | undefined;
39
+ /** Where the lock is taken and the ledger written. */
40
+ readonly ledgerDir: string;
41
+ /** A lower per-run cap. Not with `budget`. */
42
+ readonly maxRunUsd?: number;
43
+ /** The MCP server's budget for the whole process (D-018). Not with `maxRunUsd`. */
44
+ readonly budget?: RunBudget;
45
+ /** In GitHub Actions: what the mainnet job rules read about the job. Required there. */
46
+ readonly job?: Omit<MainnetJob, "env">;
47
+ }
48
+ /**
49
+ * Opens a mainnet x402 run, or refuses it before anything is sent.
50
+ *
51
+ * @throws {MainnetRunRefusedError} network, `operatedByMe`, key, RPC missing, cap, job unknown in GitHub Actions.
52
+ * @throws {MainnetPlanRefusedError} The pin (missing, not USDC, payee not valid or the payer).
53
+ * @throws {RpcIdentityError} An RPC that is not https or does not serve pubnet.
54
+ * @throws {MainnetJobRefusedError} A GitHub Actions job that breaks the mainnet job rules.
55
+ * @throws {MainnetRunLockedError} Another mainnet run holds the lock.
56
+ */
57
+ export declare function openMainnetOptIn(input: MainnetOptInInput): Promise<MainnetOptIn>;
58
+ export interface MainnetCloseOptions {
59
+ /** Waits `ms` between two reads of the latest ledger. Default: a timer. */
60
+ readonly sleep?: (ms: number) => Promise<void>;
61
+ /** One line when the wait starts. It holds nothing from the service. */
62
+ readonly onProgress?: (line: string) => void;
63
+ }
64
+ export interface MainnetCloseResult {
65
+ /** What the ledger says of the balances; undefined when the run opened no ledger. */
66
+ readonly consistency?: LedgerConsistency;
67
+ readonly ledgerPath?: string;
68
+ /** The ledger that had to close before the balances after were read; undefined when nothing may have been signed. */
69
+ readonly waitedUntil?: number;
70
+ /** Why the balances after were not read, or the run was already closed. */
71
+ readonly problem?: string;
72
+ }
73
+ /**
74
+ * L4 of a mainnet run (spec B3, B5): reports, does not prevent. Waits until
75
+ * every authorization the run signed, or may have signed, has expired: the
76
+ * latest expiry its ledger holds and, for a signature whose expiry is not
77
+ * known, the latest one the run's anchor allows a 300 s lifetime. Then waits
78
+ * for public Horizon to have closed that ledger too, reads the payer's
79
+ * balances after there (where the balances before were read), and closes the
80
+ * ledger with them: consistent or not. A wait or a read that fails closes the
81
+ * ledger without them, and `problem` says to wait and compare by hand.
82
+ *
83
+ * Always closes the opt-in, so its lock is released: nothing more is signed.
84
+ *
85
+ * @throws {ConfigurationError} When `optIn` is not an opt-in core made.
86
+ */
87
+ export declare function closeMainnetRun(optIn: MainnetOptIn, options?: MainnetCloseOptions): Promise<MainnetCloseResult>;
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Opening a mainnet run (spec B5, B18 O1): the one place a {@link MainnetOptIn}
3
+ * is made. A front end calls it only when its own switch is set (`--mainnet`,
4
+ * the Action's `mainnet: true` on workflow_dispatch, the MCP server's start-up
5
+ * setting); every other rule a mainnet x402 run needs before anything is sent
6
+ * is checked here, in core, so each front end gets the same refusals:
7
+ *
8
+ * 1. the config environment is on `stellar:pubnet` and has `operatedByMe: true`;
9
+ * 2. the key is read from `WASIT_MAINNET_PAYER_SECRET` only, is a Stellar
10
+ * secret, and is the value of no other key variable (a dedicated account);
11
+ * 3. the pin pays mainnet USDC to a valid payee that is not the payer;
12
+ * 4. an RPC is given (pubnet has no default), is https, and serves pubnet;
13
+ * 5. in GitHub Actions, the job keeps the mainnet job rules (B17.4);
14
+ * 6. no other mainnet run holds the lock in the ledger's folder.
15
+ *
16
+ * Only then is the opt-in made and the lock held. The key is read to derive
17
+ * the payer's address and is not kept. The plan (L1) comes next, with the
18
+ * opt-in: `planX402Run({ ..., mainnet })`.
19
+ */
20
+ import { basename } from "node:path";
21
+ import { Keypair, StrKey } from "@stellar/stellar-sdk";
22
+ import { DENIED_ENV_NAMES } from "../denied-env.js";
23
+ import { ConfigurationError } from "../errors.js";
24
+ import { paymentChainFor } from "../x402/chains/index.js";
25
+ import { assertX402PaymentRpc } from "../x402/simulator.js";
26
+ import { RunBudget } from "./budget.js";
27
+ import { inGithubActions } from "./ci-event.js";
28
+ import { assertMainnetJob } from "./ci-mainnet.js";
29
+ import { readHorizonAccount, readHorizonLatestLedger } from "./horizon.js";
30
+ import { MAINNET_MAX_TIMEOUT_SECONDS, assertMainnetPin } from "./mainnet-plan.js";
31
+ import { MainnetRunRefusedError, anchorOfOptIn, isMainnetOptIn, issueMainnetOptIn, } from "./optin.js";
32
+ import { openAuthorizationsUntil } from "./run-ledger.js";
33
+ import { acquireMainnetRunLock } from "./run-lock.js";
34
+ /** The one variable a mainnet run reads its key from (spec B5 point 3). */
35
+ export const MAINNET_PAYER_KEY_ENV = "WASIT_MAINNET_PAYER_SECRET";
36
+ const STELLAR_PUBNET = "stellar:pubnet";
37
+ export { MainnetRunRefusedError } from "./optin.js";
38
+ function nonEmpty(value) {
39
+ return typeof value === "string" && value.trim() !== "";
40
+ }
41
+ /** The mainnet key: set, a Stellar secret, and no other key variable's value. */
42
+ function readMainnetKey(env) {
43
+ const value = env[MAINNET_PAYER_KEY_ENV];
44
+ if (!nonEmpty(value)) {
45
+ throw new MainnetRunRefusedError("key", `${MAINNET_PAYER_KEY_ENV} is not set: a mainnet run reads its key from that variable only, never from ` +
46
+ `STELLAR_PRIVATE_KEY or --payer-key.`);
47
+ }
48
+ const key = value.trim();
49
+ if (!StrKey.isValidEd25519SecretSeed(key)) {
50
+ throw new MainnetRunRefusedError("key", `${MAINNET_PAYER_KEY_ENV} does not hold a Stellar secret key.`);
51
+ }
52
+ for (const [name, other] of Object.entries(env)) {
53
+ const upper = name.toUpperCase();
54
+ if (upper === MAINNET_PAYER_KEY_ENV || !DENIED_ENV_NAMES.includes(upper) || !nonEmpty(other))
55
+ continue;
56
+ if (other.trim() === key) {
57
+ throw new MainnetRunRefusedError("key", `${MAINNET_PAYER_KEY_ENV} holds the same key as ${upper}: a mainnet run pays from a dedicated account, whose ` +
58
+ `key is in no other variable.`);
59
+ }
60
+ }
61
+ return key;
62
+ }
63
+ /**
64
+ * Opens a mainnet x402 run, or refuses it before anything is sent.
65
+ *
66
+ * @throws {MainnetRunRefusedError} network, `operatedByMe`, key, RPC missing, cap, job unknown in GitHub Actions.
67
+ * @throws {MainnetPlanRefusedError} The pin (missing, not USDC, payee not valid or the payer).
68
+ * @throws {RpcIdentityError} An RPC that is not https or does not serve pubnet.
69
+ * @throws {MainnetJobRefusedError} A GitHub Actions job that breaks the mainnet job rules.
70
+ * @throws {MainnetRunLockedError} Another mainnet run holds the lock.
71
+ */
72
+ export async function openMainnetOptIn(input) {
73
+ if (input.network !== STELLAR_PUBNET) {
74
+ throw new MainnetRunRefusedError("network", `A mainnet run is on ${STELLAR_PUBNET} only, and this environment's network is another.`);
75
+ }
76
+ if (input.operatedByMe !== true) {
77
+ throw new MainnetRunRefusedError("operated-by-me", `operatedByMe is not true for environment ${input.environment}: Wasit pays only a service its operator runs.`);
78
+ }
79
+ const key = readMainnetKey(input.env);
80
+ const payer = Keypair.fromSecret(key).publicKey();
81
+ assertMainnetPin(input.pin, payer);
82
+ const pin = input.pin;
83
+ if (input.budget !== undefined && input.maxRunUsd !== undefined) {
84
+ throw new MainnetRunRefusedError("cap", "A mainnet run takes its cap from one place: a shared budget or maxRunUsd, not both.");
85
+ }
86
+ // A shared budget must be Wasit's own: a subclass could charge nothing.
87
+ if (input.budget !== undefined && Object.getPrototypeOf(input.budget) !== RunBudget.prototype) {
88
+ throw new MainnetRunRefusedError("cap", "A mainnet run's shared budget is a RunBudget of Wasit's own.");
89
+ }
90
+ const budget = input.budget ?? new RunBudget(input.maxRunUsd === undefined ? {} : { maxRunUsd: input.maxRunUsd });
91
+ if (inGithubActions(input.env)) {
92
+ if (input.job === undefined) {
93
+ throw new MainnetRunRefusedError("job", "This run is in GitHub Actions, and the job could not be checked against the mainnet job rules.");
94
+ }
95
+ assertMainnetJob({ ...input.job, env: input.env });
96
+ }
97
+ if (!nonEmpty(input.rpcUrl)) {
98
+ throw new MainnetRunRefusedError("rpc", `A mainnet run needs an RPC for ${STELLAR_PUBNET} (rpcUrl in the config, or WASIT_RPC_URL): there is no default one.`);
99
+ }
100
+ const rpcUrl = input.rpcUrl;
101
+ await assertX402PaymentRpc(STELLAR_PUBNET, rpcUrl);
102
+ const lock = acquireMainnetRunLock(input.ledgerDir);
103
+ return issueMainnetOptIn({
104
+ frontEnd: input.frontEnd,
105
+ environment: input.environment,
106
+ payer,
107
+ pin,
108
+ rpcUrl,
109
+ budget,
110
+ ledgerDir: input.ledgerDir,
111
+ lock,
112
+ });
113
+ }
114
+ /** Reads of the latest ledger that may fail in a row before the wait gives up. */
115
+ const MAX_FAILED_READS = 5;
116
+ /** Reads beyond the ledgers left to close, for a chain slower than its shortest unit. */
117
+ const SLACK_READS = 60;
118
+ /** The most reads in one wait, whatever is left to close. */
119
+ const MAX_READS = 400;
120
+ function defaultSleep(ms) {
121
+ return new Promise((resolve) => setTimeout(resolve, ms));
122
+ }
123
+ /**
124
+ * Reads `latest` until it is past `target`, sleeping `step` between reads. A
125
+ * reading that is not a positive whole number counts as a failed read.
126
+ * Returns false when it gives up: too many failed reads in a row, or the
127
+ * ledger stopped moving for longer than the ledgers left to close allow.
128
+ */
129
+ async function waitPast(latest, target, sleep, step) {
130
+ let failures = 0;
131
+ let allowed;
132
+ for (let reads = 0; allowed === undefined || reads < allowed; reads += 1) {
133
+ let reading;
134
+ try {
135
+ reading = await latest();
136
+ }
137
+ catch {
138
+ reading = undefined;
139
+ }
140
+ if (typeof reading === "number" && Number.isSafeInteger(reading) && reading > 0) {
141
+ failures = 0;
142
+ if (reading > target)
143
+ return true;
144
+ allowed ??= Math.min(MAX_READS, target - reading + SLACK_READS);
145
+ }
146
+ else {
147
+ failures += 1;
148
+ if (failures >= MAX_FAILED_READS)
149
+ return false;
150
+ allowed ??= MAX_READS;
151
+ }
152
+ await sleep(step);
153
+ }
154
+ return false;
155
+ }
156
+ /**
157
+ * L4 of a mainnet run (spec B3, B5): reports, does not prevent. Waits until
158
+ * every authorization the run signed, or may have signed, has expired: the
159
+ * latest expiry its ledger holds and, for a signature whose expiry is not
160
+ * known, the latest one the run's anchor allows a 300 s lifetime. Then waits
161
+ * for public Horizon to have closed that ledger too, reads the payer's
162
+ * balances after there (where the balances before were read), and closes the
163
+ * ledger with them: consistent or not. A wait or a read that fails closes the
164
+ * ledger without them, and `problem` says to wait and compare by hand.
165
+ *
166
+ * Always closes the opt-in, so its lock is released: nothing more is signed.
167
+ *
168
+ * @throws {ConfigurationError} When `optIn` is not an opt-in core made.
169
+ */
170
+ export async function closeMainnetRun(optIn, options = {}) {
171
+ if (!isMainnetOptIn(optIn))
172
+ throw new ConfigurationError("Not a mainnet opt-in.");
173
+ if (optIn.closed)
174
+ return { problem: "The mainnet run is already closed: its ledger was closed with it." };
175
+ try {
176
+ const ledger = optIn.ledger;
177
+ const horizon = optIn.plan?.mainnet?.horizon;
178
+ if (ledger === undefined || horizon === undefined)
179
+ return {};
180
+ const sleep = options.sleep ?? defaultSleep;
181
+ const terms = paymentChainFor(optIn.network)?.signedTerms;
182
+ const { latest, unknown } = openAuthorizationsUntil(ledger.entries);
183
+ let target = latest;
184
+ if (unknown > 0 && terms !== undefined) {
185
+ const bound = anchorOfOptIn(optIn).maxExpiration(terms.unitSeconds, MAINNET_MAX_TIMEOUT_SECONDS);
186
+ target = Math.max(target ?? 0, bound);
187
+ }
188
+ const unread = (what) => ({
189
+ consistency: ledger.close(),
190
+ ledgerPath: ledger.path,
191
+ ...(target === undefined ? {} : { waitedUntil: target }),
192
+ problem: `The payer's balances after this run were not read: ${what} could not be confirmed. Read the ledger ` +
193
+ `${basename(ledger.path)}, ${target === undefined ? "" : `wait until ledger ${target} has closed, `}then ` +
194
+ `compare the payer's balances with it by hand.`,
195
+ });
196
+ if (unknown > 0 && terms === undefined)
197
+ return unread("how long its signatures stay valid");
198
+ if (target !== undefined) {
199
+ if (terms === undefined)
200
+ return unread("how long its signatures stay valid");
201
+ const step = terms.unitSeconds * 1000;
202
+ options.onProgress?.(`Waiting until ledger ${target} has closed: every authorization this run signed has expired by then. ` +
203
+ `Then the payer's balances after are read on public Horizon.`);
204
+ const rpcUrl = optIn.rpcUrl;
205
+ if (!(await waitPast(() => terms.latestUnit(optIn.network, rpcUrl), target, sleep, step))) {
206
+ return unread(`that the RPC has closed ledger ${target}`);
207
+ }
208
+ if (!(await waitPast(() => readHorizonLatestLedger(horizon), target, sleep, step))) {
209
+ return unread(`that public Horizon has closed ledger ${target}`);
210
+ }
211
+ }
212
+ let after;
213
+ try {
214
+ after = await readHorizonAccount(horizon, optIn.payer);
215
+ }
216
+ catch {
217
+ return unread("the payer's account on public Horizon");
218
+ }
219
+ const consistency = ledger.close({ after: { usdc: after.usdc, native: after.native }, source: `public Horizon (${horizon})` });
220
+ return { consistency, ledgerPath: ledger.path, ...(target === undefined ? {} : { waitedUntil: target }) };
221
+ }
222
+ finally {
223
+ optIn.close();
224
+ }
225
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * L0, the network guard: which networks a payment may be made on.
3
+ *
4
+ * A fixed table, not a pattern. A network is paid on only after someone adds
5
+ * it here, so a new chain, a new mainnet or a typo is refused rather than
6
+ * paid on (fail closed). The guard is called from inside every core entry
7
+ * point that can sign, so the CLI, the MCP server, the dashboard and any
8
+ * third party using @wasit-dev/core get the same refusals; a guard in each
9
+ * front end would be three copies, and one forgotten copy is a hole.
10
+ *
11
+ * `stellar:pubnet` has its own class: an x402 run pays on it only with a live
12
+ * mainnet opt-in (spec B5), which only core makes (`openMainnetOptIn`). MPP
13
+ * never pays on it.
14
+ */
15
+ import { ConfigurationError } from "../errors.js";
16
+ import { type MainnetOptIn } from "./optin.js";
17
+ /** How the guard treats a network. */
18
+ export type NetworkClass = "test" | "mainnet-optin" | "unknown";
19
+ /** The protocol that would sign. MPP has no mainnet path at all. */
20
+ export type PaymentProtocol = "x402" | "mpp-charge" | "mpp-channel";
21
+ /**
22
+ * Every network the guard knows. Test networks are the four the payment
23
+ * checks pay on; `stellar:pubnet` is the only mainnet listed. Anything absent
24
+ * is `unknown`, and refused.
25
+ */
26
+ export declare const NETWORK_CLASSES: ReadonlyMap<string, Exclude<NetworkClass, "unknown">>;
27
+ /** The class of `network`; anything not in the table, or not a string, is `unknown`. */
28
+ export declare function networkClass(network: unknown): NetworkClass;
29
+ /**
30
+ * A payment was refused because of the network it would be made on.
31
+ *
32
+ * A `ConfigurationError`: it says nothing about the target, only that this run
33
+ * asked for something Wasit will not do. Nothing was sent when it is thrown.
34
+ */
35
+ export declare class PaymentNetworkRefusedError extends ConfigurationError {
36
+ readonly network: string;
37
+ readonly networkClass: NetworkClass;
38
+ readonly protocol: PaymentProtocol;
39
+ constructor(protocol: PaymentProtocol, network: unknown, kind: NetworkClass, message: string);
40
+ }
41
+ /**
42
+ * Throws unless a payment by `protocol` may be made on `network`.
43
+ *
44
+ * Call it before any request is sent and before any key or signer is used.
45
+ * Test networks pass. `stellar:pubnet` passes for x402 only with `mainnet`, a
46
+ * live opt-in for it (made by core, neither stopped nor closed); MPP stays on
47
+ * test networks for good. Anything else is refused.
48
+ *
49
+ * @throws {PaymentNetworkRefusedError} For any network that is not a test network, but x402 on a live opt-in's.
50
+ */
51
+ export declare function assertPaymentNetworkAllowed(protocol: PaymentProtocol, network: string, mainnet?: MainnetOptIn): void;
@@ -0,0 +1,91 @@
1
+ /**
2
+ * L0, the network guard: which networks a payment may be made on.
3
+ *
4
+ * A fixed table, not a pattern. A network is paid on only after someone adds
5
+ * it here, so a new chain, a new mainnet or a typo is refused rather than
6
+ * paid on (fail closed). The guard is called from inside every core entry
7
+ * point that can sign, so the CLI, the MCP server, the dashboard and any
8
+ * third party using @wasit-dev/core get the same refusals; a guard in each
9
+ * front end would be three copies, and one forgotten copy is a hole.
10
+ *
11
+ * `stellar:pubnet` has its own class: an x402 run pays on it only with a live
12
+ * mainnet opt-in (spec B5), which only core makes (`openMainnetOptIn`). MPP
13
+ * never pays on it.
14
+ */
15
+ import { ConfigurationError } from "../errors.js";
16
+ import { isLiveOptIn, whyNotLive } from "./optin.js";
17
+ /**
18
+ * Every network the guard knows. Test networks are the four the payment
19
+ * checks pay on; `stellar:pubnet` is the only mainnet listed. Anything absent
20
+ * is `unknown`, and refused.
21
+ */
22
+ export const NETWORK_CLASSES = new Map([
23
+ ["stellar:testnet", "test"],
24
+ ["eip155:84532", "test"], // Base Sepolia
25
+ ["eip155:11155111", "test"], // Ethereum Sepolia
26
+ ["solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", "test"], // Solana devnet
27
+ ["stellar:pubnet", "mainnet-optin"],
28
+ ]);
29
+ /** The class of `network`; anything not in the table, or not a string, is `unknown`. */
30
+ export function networkClass(network) {
31
+ return (typeof network === "string" && NETWORK_CLASSES.get(network)) || "unknown";
32
+ }
33
+ /** The test networks, in table order, for messages. */
34
+ function testNetworks() {
35
+ return [...NETWORK_CLASSES]
36
+ .filter(([, kind]) => kind === "test")
37
+ .map(([network]) => network)
38
+ .join(", ");
39
+ }
40
+ /**
41
+ * A payment was refused because of the network it would be made on.
42
+ *
43
+ * A `ConfigurationError`: it says nothing about the target, only that this run
44
+ * asked for something Wasit will not do. Nothing was sent when it is thrown.
45
+ */
46
+ export class PaymentNetworkRefusedError extends ConfigurationError {
47
+ network;
48
+ networkClass;
49
+ protocol;
50
+ constructor(protocol, network, kind, message) {
51
+ super(`${message} Nothing was sent and nothing was signed.`);
52
+ this.name = "PaymentNetworkRefusedError";
53
+ this.network = String(network);
54
+ this.networkClass = kind;
55
+ this.protocol = protocol;
56
+ }
57
+ }
58
+ /**
59
+ * Throws unless a payment by `protocol` may be made on `network`.
60
+ *
61
+ * Call it before any request is sent and before any key or signer is used.
62
+ * Test networks pass. `stellar:pubnet` passes for x402 only with `mainnet`, a
63
+ * live opt-in for it (made by core, neither stopped nor closed); MPP stays on
64
+ * test networks for good. Anything else is refused.
65
+ *
66
+ * @throws {PaymentNetworkRefusedError} For any network that is not a test network, but x402 on a live opt-in's.
67
+ */
68
+ export function assertPaymentNetworkAllowed(protocol, network, mainnet) {
69
+ const kind = networkClass(network);
70
+ if (kind === "test")
71
+ return;
72
+ if (kind === "mainnet-optin" && protocol === "x402") {
73
+ if (isLiveOptIn(mainnet, network))
74
+ return;
75
+ // An opt-in core made, that is no longer live: say why, not that there is none.
76
+ const why = whyNotLive(mainnet, network);
77
+ if (why !== undefined)
78
+ throw new PaymentNetworkRefusedError(protocol, network, kind, `${network} is Stellar mainnet, and ${why}.`);
79
+ }
80
+ if (kind === "mainnet-optin") {
81
+ throw new PaymentNetworkRefusedError(protocol, network, kind, protocol === "x402"
82
+ ? `${network} is Stellar mainnet, and this run has no mainnet opt-in: Wasit pays there only through ` +
83
+ `wasit run --mainnet, the Action's mainnet: true on workflow_dispatch, or the MCP server's ` +
84
+ `wasit_x402_mainnet_test, each with every rule of the opt-in. Without it Wasit pays on test ` +
85
+ `networks only (${testNetworks()}).`
86
+ : `${network} is Stellar mainnet, and MPP stays on test networks: the MPP ` +
87
+ `checks pay on stellar:testnet only.`);
88
+ }
89
+ throw new PaymentNetworkRefusedError(protocol, network, kind, `${JSON.stringify(network) ?? String(network)} is not on Wasit's list of test networks ` +
90
+ `(${testNetworks()}), so no payment is made on it.`);
91
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The mainnet opt-in (spec B5), as one object: made by core only
3
+ * (`openMainnetOptIn`, guard/mainnet-run.ts), for one run.
4
+ *
5
+ * An x402 payment on `stellar:pubnet` is made only with a live opt-in: L0
6
+ * passes that network with one and with nothing else. It holds what the run
7
+ * pays by (the payer's public address, the pin, the RPC, the budget) and what
8
+ * the run has done so far (its plan, its ledger, whether it was stopped or
9
+ * closed). It never holds the key.
10
+ *
11
+ * Its constructor takes a symbol only this module has, and every opt-in it
12
+ * makes is kept in a set only this module reads, so an object that only looks
13
+ * like one (a literal, a copy, `Object.create` of its prototype) is never taken
14
+ * for one. The object and its prototype are frozen, and whether it is live is
15
+ * read from its private state, never from a property: no caller can reassign
16
+ * its RPC, payer, budget or methods, or make a stopped one read as live. That
17
+ * stops a mistake or a forged object; code that reaches into the package's
18
+ * files holds the key itself and is outside every rule of Wasit.
19
+ */
20
+ import { ConfigurationError } from "../errors.js";
21
+ import { type PinTerms, type RunBudget } from "./budget.js";
22
+ import { RunLedger } from "./run-ledger.js";
23
+ import type { MainnetRunLock } from "./run-lock.js";
24
+ import { SigningAnchor } from "./signed-terms.js";
25
+ import type { RunPlan } from "../x402/plan.js";
26
+ /** The front end whose switch asked for this run: `--mainnet`, the Action's input, the MCP server's start-up setting. */
27
+ export type MainnetFrontEnd = "cli" | "action" | "mcp";
28
+ export interface MainnetOptInFields {
29
+ readonly frontEnd: MainnetFrontEnd;
30
+ readonly environment: string;
31
+ readonly payer: string;
32
+ readonly pin: PinTerms;
33
+ readonly rpcUrl: string;
34
+ readonly budget: RunBudget;
35
+ readonly ledgerDir: string;
36
+ readonly lock: MainnetRunLock;
37
+ }
38
+ /** Which rule refused or stopped the mainnet run. */
39
+ export type MainnetRunRefusal = "network" | "operated-by-me" | "key" | "rpc" | "cap" | "job" | "run";
40
+ /**
41
+ * A mainnet run does not open, or a step of it is refused. A
42
+ * `ConfigurationError`: it says nothing about the target. Nothing was started,
43
+ * sent or signed by the step that threw it. A stop of a run that is open
44
+ * (`during`) says that nothing more is signed in it: an earlier endpoint of
45
+ * the run may have paid.
46
+ */
47
+ export declare class MainnetRunRefusedError extends ConfigurationError {
48
+ readonly reason: MainnetRunRefusal;
49
+ constructor(reason: MainnetRunRefusal, message: string, options?: {
50
+ readonly during?: boolean;
51
+ });
52
+ }
53
+ export declare class MainnetOptIn {
54
+ #private;
55
+ readonly network = "stellar:pubnet";
56
+ readonly frontEnd: MainnetFrontEnd;
57
+ readonly environment: string;
58
+ /** The payer's public address, derived from the key when the opt-in was made. */
59
+ readonly payer: string;
60
+ readonly pin: PinTerms;
61
+ readonly rpcUrl: string;
62
+ /** The run's budget: its own $5, or the MCP server's for the whole process (D-018). */
63
+ readonly budget: RunBudget;
64
+ /** Where the lock is, and where the ledger is written. */
65
+ readonly ledgerDir: string;
66
+ /** Core only: `openMainnetOptIn`. */
67
+ constructor(key: symbol, fields: MainnetOptInFields);
68
+ /** The plan L1 made for this run, once it passed. */
69
+ get plan(): RunPlan | undefined;
70
+ get ledger(): RunLedger | undefined;
71
+ /** Why the run stopped (the first reason), if it did. Nothing is signed after it. */
72
+ get stopped(): string | undefined;
73
+ get closed(): boolean;
74
+ /** Stops the whole run (spec B3): nothing more is signed with this opt-in. The first reason is kept. */
75
+ stop(reason: string): void;
76
+ /**
77
+ * Opens the run ledger (spec B5) in the ledger folder: the header from this
78
+ * opt-in and its plan, the RPC by its origin only, and the balances before
79
+ * as L1 read them on public Horizon. Only after a plan that passed, once,
80
+ * and before the first signature: a payment on mainnet without it is refused.
81
+ */
82
+ openLedger(versions: Readonly<Record<string, string>>, options?: {
83
+ readonly now?: () => Date;
84
+ }): RunLedger;
85
+ /** Ends the run: nothing more is signed with it, and its lock is released. */
86
+ close(): void;
87
+ }
88
+ /** Core only: L1 records the plan that passed, once. Not a method, so no caller reaches it through an opt-in. */
89
+ export declare function recordMainnetPlan(optIn: MainnetOptIn, plan: RunPlan): void;
90
+ /** Core only: the one way to make an opt-in, used by `openMainnetOptIn`. */
91
+ export declare function issueMainnetOptIn(fields: MainnetOptInFields): MainnetOptIn;
92
+ /**
93
+ * The run's anchor (spec B17.2): read in L1 beside public Horizon's latest
94
+ * ledger, never at the first signature. Core only: not on the opt-in, so no
95
+ * caller can set it first.
96
+ */
97
+ export declare function anchorOfOptIn(optIn: MainnetOptIn): SigningAnchor;
98
+ /** True for an opt-in core made, live, stopped or closed alike. */
99
+ export declare function isMainnetOptIn(value: unknown): value is MainnetOptIn;
100
+ /** True only for an opt-in core made, for `network`, neither stopped nor closed. */
101
+ export declare function isLiveOptIn(value: unknown, network: string): value is MainnetOptIn;
102
+ /**
103
+ * Why `value`, an opt-in core made, is not live for `network`, as a clause;
104
+ * undefined when it is live or is not an opt-in at all.
105
+ */
106
+ export declare function whyNotLive(value: unknown, network: string): string | undefined;