@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
@@ -0,0 +1,208 @@
1
+ /**
2
+ * L1's rules for a mainnet run (spec B3, B4, B5, B17.2), as pure checks.
3
+ *
4
+ * A mainnet run pays in one asset, Circle's USDC on Stellar mainnet, to the
5
+ * one payee its config pins, with a lifetime short enough to wait out, and
6
+ * only when the token, the RPC's latest ledger and the payer's balance read
7
+ * as expected. Each rule here throws {@link MainnetPlanRefusedError} when it
8
+ * does not hold; nothing was signed at that point.
9
+ *
10
+ * Nothing here says "allowed": the plan of a mainnet run (L1, with the opt-in)
11
+ * and its signatures (L2) call these before anything is signed, and the dry
12
+ * run on `stellar:pubnet` calls them with no key.
13
+ *
14
+ * Pure: no network, no key. The reads they judge are `horizon.ts` and the
15
+ * chain adapter's.
16
+ */
17
+ import { StrKey } from "@stellar/stellar-sdk";
18
+ import { ConfigurationError } from "../errors.js";
19
+ import { shown } from "./budget.js";
20
+ /** The one network these rules are for. */
21
+ const STELLAR_PUBNET = "stellar:pubnet";
22
+ /**
23
+ * Circle's USDC on Stellar mainnet, as a Stellar Asset Contract. Checked three
24
+ * ways on 2026-11-21: the issuer as Circle's page lists it
25
+ * (https://developers.circle.com/stablecoins/usdc-contract-addresses,
26
+ * "USDC-GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN"); the
27
+ * contract derived from that issuer with the SDK
28
+ * (`new Asset("USDC", issuer).contractId(Networks.PUBLIC)`); and
29
+ * `USDC_PUBNET_ADDRESS` of `@x402/stellar` 2.28.0. A test asserts all three.
30
+ */
31
+ export const MAINNET_USDC = {
32
+ network: STELLAR_PUBNET,
33
+ asset: "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75",
34
+ code: "USDC",
35
+ issuer: "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN",
36
+ decimals: 7,
37
+ symbol: "USDC",
38
+ };
39
+ /** The longest lifetime a mainnet payment is signed for, in seconds (B3): the run waits it out. */
40
+ export const MAINNET_MAX_TIMEOUT_SECONDS = 300;
41
+ /** At most this many ledgers between the RPC's latest ledger and public Horizon's (B17.2). */
42
+ export const MAINNET_ANCHOR_MAX_GAP_LEDGERS = 12;
43
+ /** Public Horizon of Stellar mainnet (B5 point 4): the SDK reads the ledger close time there too. */
44
+ export const PUBNET_HORIZON_URL = "https://horizon.stellar.org";
45
+ /**
46
+ * A mainnet run does not start, or stops, because of one of L1's rules. A
47
+ * `ConfigurationError`: it says nothing about the target. Nothing was signed.
48
+ */
49
+ export class MainnetPlanRefusedError extends ConfigurationError {
50
+ reason;
51
+ constructor(reason, message) {
52
+ super(`${message} Nothing was signed.`);
53
+ this.name = "MainnetPlanRefusedError";
54
+ this.reason = reason;
55
+ }
56
+ }
57
+ function isStellarAddress(value) {
58
+ return typeof value === "string" && (StrKey.isValidEd25519PublicKey(value) || StrKey.isValidContract(value));
59
+ }
60
+ /**
61
+ * The pin a mainnet environment must have (B5 point 2): a payee that is a
62
+ * valid Stellar address and not the payer itself, and mainnet USDC as the
63
+ * asset. A transfer to the payer would leave its balance as it was and hide
64
+ * what the run paid. `payer` undefined: the dry run, which reads no key; the
65
+ * paid run holds the payee to the payer's address when it opens.
66
+ */
67
+ export function assertMainnetPin(pin, payer) {
68
+ if (pin === undefined) {
69
+ throw new MainnetPlanRefusedError("pin", "A mainnet environment needs pinned.payTo and pinned.asset in the config: Wasit pays only the payee and the " +
70
+ "asset written there.");
71
+ }
72
+ if (pin.asset !== MAINNET_USDC.asset) {
73
+ throw new MainnetPlanRefusedError("asset", `pinned.asset of a mainnet environment must be ${MAINNET_USDC.asset}, Circle's USDC on Stellar mainnet; ` +
74
+ `the config has ${isStellarAddress(pin.asset) ? pin.asset : "another value"}.`);
75
+ }
76
+ if (!isStellarAddress(pin.payTo)) {
77
+ throw new MainnetPlanRefusedError("pin", "pinned.payTo of a mainnet environment is not a valid Stellar address.");
78
+ }
79
+ if (payer !== undefined && pin.payTo === payer) {
80
+ throw new MainnetPlanRefusedError("pin", "pinned.payTo is the payer's own address: on mainnet the payee must be another account, so the payer's " +
81
+ "balance shows what the run paid.");
82
+ }
83
+ }
84
+ /**
85
+ * Where a URL pays, as a mainnet plan records it and L2 holds each payment to
86
+ * it: origin and path, the query and the fragment left out (a query may hold
87
+ * a key, and the plan is written to the ledger).
88
+ */
89
+ export function paidUrlOf(target) {
90
+ const url = new URL(target);
91
+ return `${url.origin}${url.pathname}`;
92
+ }
93
+ /**
94
+ * The option a mainnet endpoint may be paid by (L1, B3): `exact` on
95
+ * `stellar:pubnet`, in mainnet USDC, valid for at most 300 s. The pin (payee
96
+ * and asset over every option) is `assertPinned`'s; the price is the budget's.
97
+ */
98
+ export function assertMainnetOption(option) {
99
+ if (option.scheme !== "exact" || option.network !== STELLAR_PUBNET) {
100
+ throw new MainnetPlanRefusedError("network", `The option to pay is ${shown(option.scheme)} on ${shown(option.network)}; a mainnet run pays exact on ` +
101
+ `${STELLAR_PUBNET} only.`);
102
+ }
103
+ if (option.asset !== MAINNET_USDC.asset) {
104
+ throw new MainnetPlanRefusedError("asset", `The option to pay asks for ${shown(option.asset)}; a mainnet run pays in ${MAINNET_USDC.asset} ` +
105
+ `(USDC) only.`);
106
+ }
107
+ const lifetime = option.maxTimeoutSeconds;
108
+ if (typeof lifetime !== "number" ||
109
+ !Number.isSafeInteger(lifetime) ||
110
+ lifetime < 1 ||
111
+ lifetime > MAINNET_MAX_TIMEOUT_SECONDS) {
112
+ throw new MainnetPlanRefusedError("lifetime", `The option to pay stays valid for ${shown(lifetime)} s; a mainnet payment is signed for a whole number of ` +
113
+ `seconds from 1 to ${MAINNET_MAX_TIMEOUT_SECONDS}, so the run can wait until every signature it made has ` +
114
+ `expired.`);
115
+ }
116
+ }
117
+ /** The token's decimals, as read on chain (B4): the caps count USDC at 7. */
118
+ export function assertMainnetDecimals(decimals) {
119
+ if (decimals !== MAINNET_USDC.decimals) {
120
+ throw new MainnetPlanRefusedError("decimals", `The asset contract reports ${shown(decimals)} decimals; mainnet USDC has ${MAINNET_USDC.decimals}, and the ` +
121
+ `caps are counted at ${MAINNET_USDC.decimals}.`);
122
+ }
123
+ }
124
+ function isLedger(value) {
125
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
126
+ }
127
+ /**
128
+ * The RPC's latest ledger must be within {@link MAINNET_ANCHOR_MAX_GAP_LEDGERS}
129
+ * of public Horizon's (B17.2): the expiration bound of every signature counts
130
+ * from it, so an RPC that reports a later ledger cannot stretch a signature's
131
+ * life on mainnet.
132
+ */
133
+ export function assertAnchorNearHorizon(rpcLatest, horizonLatest) {
134
+ if (!isLedger(rpcLatest) || !isLedger(horizonLatest)) {
135
+ throw new MainnetPlanRefusedError("anchor", "The latest ledger could not be read as a ledger number from the RPC and Horizon.");
136
+ }
137
+ const gap = Math.abs(rpcLatest - horizonLatest);
138
+ if (gap > MAINNET_ANCHOR_MAX_GAP_LEDGERS) {
139
+ throw new MainnetPlanRefusedError("anchor", `The RPC's latest ledger (${rpcLatest}) is ${gap} ledgers from public Horizon's (${horizonLatest}), more than ` +
140
+ `the ${MAINNET_ANCHOR_MAX_GAP_LEDGERS} a mainnet run allows: the RPC may not serve the current chain.`);
141
+ }
142
+ }
143
+ /** Horizon's amounts: whole units, a point, exactly seven decimals. */
144
+ const HORIZON_AMOUNT = /^(0|[1-9][0-9]{0,18})\.([0-9]{7})$/;
145
+ /** An amount as Horizon writes it ("10.0000000"), in base units at 7 decimals; undefined for anything else. */
146
+ export function parseHorizonAmount(text) {
147
+ if (typeof text !== "string")
148
+ return undefined;
149
+ const match = HORIZON_AMOUNT.exec(text);
150
+ if (match === null)
151
+ return undefined;
152
+ return BigInt(match[1]) * 10000000n + BigInt(match[2]);
153
+ }
154
+ function isRecord(value) {
155
+ return typeof value === "object" && value !== null && !Array.isArray(value);
156
+ }
157
+ /**
158
+ * The USDC and XLM balances of a Horizon account answer, in base units. The
159
+ * trustline is matched by type, code and issuer; a token with the same code
160
+ * from another issuer is not it. Undefined for an answer that cannot be read
161
+ * plainly: no `balances`, no native balance, an amount that does not parse,
162
+ * or the same asset listed twice.
163
+ */
164
+ export function horizonBalances(account, asset) {
165
+ if (!isRecord(account) || !Array.isArray(account["balances"]))
166
+ return undefined;
167
+ const type = asset.code.length <= 4 ? "credit_alphanum4" : "credit_alphanum12";
168
+ let usdc;
169
+ let native;
170
+ for (const entry of account["balances"]) {
171
+ if (!isRecord(entry))
172
+ return undefined;
173
+ if (entry["asset_type"] === "native") {
174
+ if (native !== undefined)
175
+ return undefined;
176
+ native = parseHorizonAmount(entry["balance"]);
177
+ if (native === undefined)
178
+ return undefined;
179
+ }
180
+ else if (entry["asset_type"] === type && entry["asset_code"] === asset.code && entry["asset_issuer"] === asset.issuer) {
181
+ if (usdc !== undefined)
182
+ return undefined;
183
+ usdc = parseHorizonAmount(entry["balance"]);
184
+ if (usdc === undefined)
185
+ return undefined;
186
+ }
187
+ }
188
+ if (native === undefined)
189
+ return undefined;
190
+ return { usdc: usdc ?? 0n, native };
191
+ }
192
+ /**
193
+ * The payer's USDC balance as the RPC reads it must be what Horizon lists
194
+ * (B17.12): the $10 rule reads the RPC's, and an RPC that under-reports it
195
+ * would let a fuller account pay.
196
+ */
197
+ export function assertBalancesAgree(rpcBalance, horizonBalance) {
198
+ if (horizonBalance === undefined) {
199
+ throw new MainnetPlanRefusedError("horizon", "The payer's USDC balance could not be read from public Horizon.");
200
+ }
201
+ if (rpcBalance === undefined) {
202
+ throw new MainnetPlanRefusedError("balance", "The payer's USDC balance could not be read through the RPC.");
203
+ }
204
+ if (rpcBalance !== horizonBalance) {
205
+ throw new MainnetPlanRefusedError("balance", `The RPC reads the payer's USDC balance as ${rpcBalance} base units and public Horizon as ${horizonBalance}: ` +
206
+ `the two must agree before a mainnet run signs anything.`);
207
+ }
208
+ }
@@ -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
+ }
@@ -8,11 +8,12 @@
8
8
  * third party using @wasit-dev/core get the same refusals; a guard in each
9
9
  * front end would be three copies, and one forgotten copy is a hole.
10
10
  *
11
- * `stellar:pubnet` has its own class because a later version may let an x402
12
- * run pay on it behind an explicit opt-in. This version has no such opt-in,
13
- * so this module has no path that allows it.
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
14
  */
15
15
  import { ConfigurationError } from "../errors.js";
16
+ import { type MainnetOptIn } from "./optin.js";
16
17
  /** How the guard treats a network. */
17
18
  export type NetworkClass = "test" | "mainnet-optin" | "unknown";
18
19
  /** The protocol that would sign. MPP has no mainnet path at all. */
@@ -41,10 +42,10 @@ export declare class PaymentNetworkRefusedError extends ConfigurationError {
41
42
  * Throws unless a payment by `protocol` may be made on `network`.
42
43
  *
43
44
  * Call it before any request is sent and before any key or signer is used.
44
- * Only test networks pass. `stellar:pubnet` is refused for every protocol in
45
- * this version: MPP stays on test networks for good, and x402 on mainnet
46
- * needs an opt-in this version does not have.
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.
47
48
  *
48
- * @throws {PaymentNetworkRefusedError} For any network that is not a test network.
49
+ * @throws {PaymentNetworkRefusedError} For any network that is not a test network, but x402 on a live opt-in's.
49
50
  */
50
- export declare function assertPaymentNetworkAllowed(protocol: PaymentProtocol, network: string): void;
51
+ export declare function assertPaymentNetworkAllowed(protocol: PaymentProtocol, network: string, mainnet?: MainnetOptIn): void;
@@ -8,11 +8,12 @@
8
8
  * third party using @wasit-dev/core get the same refusals; a guard in each
9
9
  * front end would be three copies, and one forgotten copy is a hole.
10
10
  *
11
- * `stellar:pubnet` has its own class because a later version may let an x402
12
- * run pay on it behind an explicit opt-in. This version has no such opt-in,
13
- * so this module has no path that allows it.
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
14
  */
15
15
  import { ConfigurationError } from "../errors.js";
16
+ import { isLiveOptIn, whyNotLive } from "./optin.js";
16
17
  /**
17
18
  * Every network the guard knows. Test networks are the four the payment
18
19
  * checks pay on; `stellar:pubnet` is the only mainnet listed. Anything absent
@@ -58,20 +59,30 @@ export class PaymentNetworkRefusedError extends ConfigurationError {
58
59
  * Throws unless a payment by `protocol` may be made on `network`.
59
60
  *
60
61
  * Call it before any request is sent and before any key or signer is used.
61
- * Only test networks pass. `stellar:pubnet` is refused for every protocol in
62
- * this version: MPP stays on test networks for good, and x402 on mainnet
63
- * needs an opt-in this version does not have.
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.
64
65
  *
65
- * @throws {PaymentNetworkRefusedError} For any network that is not a test network.
66
+ * @throws {PaymentNetworkRefusedError} For any network that is not a test network, but x402 on a live opt-in's.
66
67
  */
67
- export function assertPaymentNetworkAllowed(protocol, network) {
68
+ export function assertPaymentNetworkAllowed(protocol, network, mainnet) {
68
69
  const kind = networkClass(network);
69
70
  if (kind === "test")
70
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
+ }
71
80
  if (kind === "mainnet-optin") {
72
81
  throw new PaymentNetworkRefusedError(protocol, network, kind, protocol === "x402"
73
- ? `${network} is Stellar mainnet. This version of Wasit pays on test networks ` +
74
- `only (${testNetworks()}); the mainnet opt-in is not part of this version.`
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()}).`
75
86
  : `${network} is Stellar mainnet, and MPP stays on test networks: the MPP ` +
76
87
  `checks pay on stellar:testnet only.`);
77
88
  }