@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,149 @@
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 { existsSync } from "node:fs";
26
+ import path from "node:path";
27
+ import { DENIED_ENV_NAMES } from "../denied-env.js";
28
+ import { ConfigurationError } from "../errors.js";
29
+ import { inGithubActions } from "./ci-event.js";
30
+ /** The variable a mainnet run reads its key from (spec B5). */
31
+ const MAINNET_KEY = "WASIT_MAINNET_PAYER_SECRET";
32
+ /** An event name as GitHub writes them; anything else is never echoed. */
33
+ const EVENT_NAME = /^[a-z_]{1,64}$/;
34
+ /** A branch or tag ref, and a branch name, in a shape that is safe to echo. */
35
+ const REF = /^refs\/(heads|tags)\/[A-Za-z0-9._/-]{1,200}$/;
36
+ const BRANCH = /^[A-Za-z0-9._/-]{1,200}$/;
37
+ /** A job that may not make a mainnet run, with every rule it breaks. */
38
+ export class MainnetJobRefusedError extends ConfigurationError {
39
+ refusals;
40
+ constructor(refusals) {
41
+ super(`This job may not make a mainnet run: ${refusals.join("; ")}. Nothing was started, sent or signed. These ` +
42
+ `rules stop a wrong workflow, not code that already ran in this job: keep the mainnet key as the secret of ` +
43
+ `a GitHub environment limited to the default branch, with a required reviewer.`);
44
+ this.name = "MainnetJobRefusedError";
45
+ this.refusals = refusals;
46
+ }
47
+ }
48
+ function nonEmpty(value) {
49
+ return typeof value === "string" && value.trim() !== "";
50
+ }
51
+ function listed(names) {
52
+ return names.length === 1 ? names[0] : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
53
+ }
54
+ function isLocalIpv4(a, b) {
55
+ return (a === 127 || // loopback
56
+ a === 0 ||
57
+ a === 10 ||
58
+ (a === 172 && b >= 16 && b <= 31) ||
59
+ (a === 192 && b === 168) ||
60
+ (a === 169 && b === 254) || // link-local
61
+ (a === 100 && b >= 64 && b <= 127) // shared address space
62
+ );
63
+ }
64
+ function isLocalIpv6(address) {
65
+ if (address === "::1" || address === "::")
66
+ return true;
67
+ const mappedHex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(address);
68
+ if (mappedHex !== null) {
69
+ const high = Number.parseInt(mappedHex[1], 16);
70
+ return isLocalIpv4(high >> 8, high & 0xff);
71
+ }
72
+ const mappedDotted = /^::ffff:(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/.exec(address);
73
+ if (mappedDotted !== null)
74
+ return isLocalIpv4(Number(mappedDotted[1]), Number(mappedDotted[2]));
75
+ const first = Number.parseInt(address.split(":")[0] || "0", 16);
76
+ return (first & 0xfe00) === 0xfc00 || (first & 0xffc0) === 0xfe80; // unique local, link-local
77
+ }
78
+ /**
79
+ * A host only this machine or its own network reaches, as `URL.hostname`
80
+ * writes it: a loopback, private, link-local or shared address, `localhost`,
81
+ * a single-label name, or a `.local` or `.internal` name.
82
+ */
83
+ export function isLocalHost(hostname) {
84
+ const host = hostname.toLowerCase().replace(/\.$/, "");
85
+ if (host.startsWith("[") && host.endsWith("]"))
86
+ return isLocalIpv6(host.slice(1, -1));
87
+ const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
88
+ if (v4 !== null)
89
+ return isLocalIpv4(Number(v4[1]), Number(v4[2]));
90
+ if (!host.includes("."))
91
+ return true;
92
+ return host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal");
93
+ }
94
+ /**
95
+ * Every rule of a mainnet job that `job` breaks, one clause each; empty when it
96
+ * breaks none, and always empty outside GitHub Actions. No key, and no event
97
+ * name, ref or path in an odd shape, is echoed.
98
+ */
99
+ export function mainnetJobRefusals(job, exists = existsSync) {
100
+ if (!inGithubActions(job.env))
101
+ return [];
102
+ const refusals = [];
103
+ const event = job.env["GITHUB_EVENT_NAME"] ?? "";
104
+ if (event !== "workflow_dispatch") {
105
+ refusals.push(`a mainnet run is started by hand (workflow_dispatch), and this run's event is ${EVENT_NAME.test(event) ? event : "another event"}`);
106
+ }
107
+ if (job.env["RUNNER_ENVIRONMENT"] !== "github-hosted") {
108
+ refusals.push("a mainnet run needs a GitHub-hosted runner (RUNNER_ENVIRONMENT github-hosted): a self-hosted runner keeps " +
109
+ "files and processes between jobs");
110
+ }
111
+ const ref = job.env["GITHUB_REF"] ?? "";
112
+ if (job.defaultBranch === undefined || !BRANCH.test(job.defaultBranch)) {
113
+ refusals.push("the repository's default branch could not be read from the event, so this run cannot be shown to be on it");
114
+ }
115
+ else if (ref !== `refs/heads/${job.defaultBranch}`) {
116
+ refusals.push(`a mainnet run runs on the default branch (${job.defaultBranch}), and this run's ref is ${REF.test(ref) ? ref : "another ref"}`);
117
+ }
118
+ if (job.startsService) {
119
+ refusals.push("the environment starts a service in the job (service.start): a mainnet run tests a deployed service, so that " +
120
+ "no code of the service runs in the job that holds the key");
121
+ }
122
+ let host;
123
+ try {
124
+ host = new URL(job.baseUrl).hostname;
125
+ }
126
+ catch {
127
+ host = undefined;
128
+ }
129
+ if (host === undefined || isLocalHost(host)) {
130
+ refusals.push("baseUrl is a local address (a loopback, private or single-label host): a mainnet run tests a deployed service");
131
+ }
132
+ for (const { label, dir } of job.installDirs) {
133
+ if (exists(path.join(dir, "node_modules"))) {
134
+ refusals.push(`a node_modules directory is in ${label}: code was installed in this job before Wasit, and a mainnet job ` +
135
+ `holds only checkout, setup-node and Wasit`);
136
+ }
137
+ }
138
+ const others = DENIED_ENV_NAMES.filter((name) => name !== MAINNET_KEY && nonEmpty(job.env[name]));
139
+ if (others.length > 0) {
140
+ refusals.push(`only ${MAINNET_KEY} may be set on a mainnet run, and ${listed(others)} ${others.length === 1 ? "is" : "are"} set too`);
141
+ }
142
+ return refusals;
143
+ }
144
+ /** Throws {@link MainnetJobRefusedError} when `job` breaks any rule of a mainnet job. */
145
+ export function assertMainnetJob(job, exists = existsSync) {
146
+ const refusals = mainnetJobRefusals(job, exists);
147
+ if (refusals.length > 0)
148
+ throw new MainnetJobRefusedError(refusals);
149
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The two reads a mainnet run makes on public Horizon (spec B5 point 4,
3
+ * B17.2, B17.12), each a second source beside the run's RPC:
4
+ *
5
+ * - the latest ledger, which the RPC's latest ledger (the anchor of every
6
+ * signature's expiration bound) must be near;
7
+ * - the payer's balances, which the RPC's USDC balance must equal, and which
8
+ * the run ledger records before and after the run (USDC and XLM).
9
+ *
10
+ * Both fail closed: an error status, a redirect (never followed), a body that
11
+ * is not JSON or is too large, a Horizon of another network, or an answer that
12
+ * cannot be read plainly is a {@link MainnetPlanRefusedError}. A message names
13
+ * Horizon by its origin only.
14
+ *
15
+ * Read-only: no key, nothing signed or sent but two GET requests. The plan of a
16
+ * mainnet run (L1) and its close (L4) call them.
17
+ */
18
+ import { type HorizonBalances } from "./mainnet-plan.js";
19
+ /**
20
+ * The latest ledger Horizon at `base` has ingested, from its root, when it
21
+ * says it serves Stellar mainnet.
22
+ */
23
+ export declare function readHorizonLatestLedger(base: string): Promise<number>;
24
+ /**
25
+ * The USDC (mainnet USDC's trustline; 0 without one) and XLM balances of the
26
+ * account `payer` on Horizon at `base`, in base units. An address that is not
27
+ * a Stellar account is refused before any request; so is an account Horizon
28
+ * does not have.
29
+ */
30
+ export declare function readHorizonAccount(base: string, payer: string): Promise<HorizonBalances>;
@@ -0,0 +1,107 @@
1
+ /**
2
+ * The two reads a mainnet run makes on public Horizon (spec B5 point 4,
3
+ * B17.2, B17.12), each a second source beside the run's RPC:
4
+ *
5
+ * - the latest ledger, which the RPC's latest ledger (the anchor of every
6
+ * signature's expiration bound) must be near;
7
+ * - the payer's balances, which the RPC's USDC balance must equal, and which
8
+ * the run ledger records before and after the run (USDC and XLM).
9
+ *
10
+ * Both fail closed: an error status, a redirect (never followed), a body that
11
+ * is not JSON or is too large, a Horizon of another network, or an answer that
12
+ * cannot be read plainly is a {@link MainnetPlanRefusedError}. A message names
13
+ * Horizon by its origin only.
14
+ *
15
+ * Read-only: no key, nothing signed or sent but two GET requests. The plan of a
16
+ * mainnet run (L1) and its close (L4) call them.
17
+ */
18
+ import { Networks, StrKey } from "@stellar/stellar-sdk";
19
+ import { MAINNET_USDC, MainnetPlanRefusedError, horizonBalances } from "./mainnet-plan.js";
20
+ const TIMEOUT_MS = 10_000;
21
+ /** A Horizon answer larger than this is not read. The root and one account are a few KiB. */
22
+ const MAX_BODY_BYTES = 1024 * 1024;
23
+ function originOf(base) {
24
+ try {
25
+ const url = new URL(base);
26
+ return url.protocol === "http:" || url.protocol === "https:" ? url.origin : "Horizon";
27
+ }
28
+ catch {
29
+ return "Horizon";
30
+ }
31
+ }
32
+ function refuse(base, what) {
33
+ return new MainnetPlanRefusedError("horizon", `${what} could not be read from public Horizon (${originOf(base)}).`);
34
+ }
35
+ /** GET `path` on Horizon at `base`, as JSON; throws the refusal on anything but a plain 200 JSON answer. */
36
+ async function getJson(base, path, what) {
37
+ let response;
38
+ try {
39
+ response = await fetch(`${base.replace(/\/+$/, "")}${path}`, {
40
+ headers: { accept: "application/json" },
41
+ redirect: "manual",
42
+ signal: AbortSignal.timeout(TIMEOUT_MS),
43
+ });
44
+ }
45
+ catch {
46
+ throw refuse(base, what);
47
+ }
48
+ if (response.status !== 200 || response.body === null) {
49
+ await response.body?.cancel().catch(() => undefined);
50
+ throw refuse(base, what);
51
+ }
52
+ const chunks = [];
53
+ let size = 0;
54
+ try {
55
+ for await (const chunk of response.body) {
56
+ size += chunk.byteLength;
57
+ if (size > MAX_BODY_BYTES) {
58
+ await response.body.cancel().catch(() => undefined);
59
+ throw refuse(base, what);
60
+ }
61
+ chunks.push(chunk);
62
+ }
63
+ return JSON.parse(Buffer.concat(chunks).toString("utf-8"));
64
+ }
65
+ catch (error) {
66
+ if (error instanceof MainnetPlanRefusedError)
67
+ throw error;
68
+ throw refuse(base, what);
69
+ }
70
+ }
71
+ function isRecord(value) {
72
+ return typeof value === "object" && value !== null && !Array.isArray(value);
73
+ }
74
+ /**
75
+ * The latest ledger Horizon at `base` has ingested, from its root, when it
76
+ * says it serves Stellar mainnet.
77
+ */
78
+ export async function readHorizonLatestLedger(base) {
79
+ const what = "The latest ledger";
80
+ const root = await getJson(base, "/", what);
81
+ if (!isRecord(root) || root["network_passphrase"] !== Networks.PUBLIC) {
82
+ throw new MainnetPlanRefusedError("horizon", `Public Horizon (${originOf(base)}) does not say it serves Stellar mainnet, so its latest ledger is not used.`);
83
+ }
84
+ const ledger = root["history_latest_ledger"];
85
+ if (typeof ledger !== "number" || !Number.isSafeInteger(ledger) || ledger <= 0)
86
+ throw refuse(base, what);
87
+ return ledger;
88
+ }
89
+ /**
90
+ * The USDC (mainnet USDC's trustline; 0 without one) and XLM balances of the
91
+ * account `payer` on Horizon at `base`, in base units. An address that is not
92
+ * a Stellar account is refused before any request; so is an account Horizon
93
+ * does not have.
94
+ */
95
+ export async function readHorizonAccount(base, payer) {
96
+ const what = "The payer's balances";
97
+ if (typeof payer !== "string" || !StrKey.isValidEd25519PublicKey(payer)) {
98
+ throw new MainnetPlanRefusedError("horizon", "The payer is not a Stellar account address, so Horizon was not asked for its balances.");
99
+ }
100
+ const account = await getJson(base, `/accounts/${payer}`, what);
101
+ if (!isRecord(account) || account["account_id"] !== payer)
102
+ throw refuse(base, what);
103
+ const balances = horizonBalances(account, MAINNET_USDC);
104
+ if (balances === undefined)
105
+ throw refuse(base, what);
106
+ return balances;
107
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * L1's rule on the mainnet payer's account (spec B3, B4, B17.5).
3
+ *
4
+ * The caps hold one run to $5 (`budget.ts`). They do not hold two runs at once
5
+ * on the same account, nor a server that is restarted: each gets its own $5.
6
+ * What bounds those is the account. So before a mainnet run signs anything, it
7
+ * reads its payer's USDC balance and does not start when the account holds
8
+ * more than $10, or when the balance cannot be read. With $10 or less in it,
9
+ * runs at once on that account can together sign no more than it holds.
10
+ *
11
+ * The balance is the RPC's answer. It is read through the run's RPC, the one
12
+ * whose network was checked; a reader the caller hands in, so the rule itself
13
+ * is pure.
14
+ *
15
+ * Nothing here says "allowed" for `stellar:pubnet`: the plan of a mainnet run
16
+ * (`planX402Run` with the opt-in) calls {@link assertMainnetPayerBalance} in
17
+ * L1, after the opt-in took the run's lock (`run-lock.ts`) and before anything
18
+ * is signed.
19
+ */
20
+ import { ConfigurationError } from "../errors.js";
21
+ /** At most this many dollars of USDC in the account a mainnet run pays from. */
22
+ export declare const MAINNET_PAYER_MAX_USD = 10;
23
+ /** {@link MAINNET_PAYER_MAX_USD} in base units of USDC on Stellar. */
24
+ export declare const MAINNET_PAYER_MAX_BASE_UNITS: bigint;
25
+ /** Why the payer's account stops the run. */
26
+ export type MainnetPayerRefusal =
27
+ /** It holds more than $10 of USDC. */
28
+ "above-max"
29
+ /** Its balance could not be read. */
30
+ | "unreadable"
31
+ /** The run's network has no rule here (fail closed). */
32
+ | "network";
33
+ /**
34
+ * A mainnet run does not start because of its payer's account. A
35
+ * `ConfigurationError`: it says nothing about the target. Nothing was signed.
36
+ */
37
+ export declare class MainnetPayerRefusedError extends ConfigurationError {
38
+ readonly reason: MainnetPayerRefusal;
39
+ constructor(reason: MainnetPayerRefusal, message: string);
40
+ }
41
+ export interface MainnetPayerAccount {
42
+ /** The run's network. */
43
+ readonly network: string;
44
+ /** The payer's public address. */
45
+ readonly payer: string;
46
+ /**
47
+ * Reads the payer's balance of the run's USDC in base units, through the
48
+ * run's RPC; undefined when it cannot.
49
+ */
50
+ readonly readBalance: () => Promise<bigint | undefined>;
51
+ }
52
+ /**
53
+ * Holds the payer's account to {@link MAINNET_PAYER_MAX_USD}.
54
+ *
55
+ * On a test network nothing is read and undefined is returned: the rule is for
56
+ * real funds. On `stellar:pubnet` the balance is read once and returned when
57
+ * it is $10 or less, for the plan to print. Any other network has no rule here
58
+ * and is refused without a read.
59
+ *
60
+ * @throws {MainnetPayerRefusedError} On `stellar:pubnet` when the balance is
61
+ * above $10 or cannot be read (no answer, an answer that is not a whole
62
+ * number of base units, or a read that threw: what it threw is not echoed,
63
+ * since an RPC URL may carry a key); and on any network that is neither a
64
+ * test network nor `stellar:pubnet`.
65
+ */
66
+ export declare function assertMainnetPayerBalance(account: MainnetPayerAccount): Promise<bigint | undefined>;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * L1's rule on the mainnet payer's account (spec B3, B4, B17.5).
3
+ *
4
+ * The caps hold one run to $5 (`budget.ts`). They do not hold two runs at once
5
+ * on the same account, nor a server that is restarted: each gets its own $5.
6
+ * What bounds those is the account. So before a mainnet run signs anything, it
7
+ * reads its payer's USDC balance and does not start when the account holds
8
+ * more than $10, or when the balance cannot be read. With $10 or less in it,
9
+ * runs at once on that account can together sign no more than it holds.
10
+ *
11
+ * The balance is the RPC's answer. It is read through the run's RPC, the one
12
+ * whose network was checked; a reader the caller hands in, so the rule itself
13
+ * is pure.
14
+ *
15
+ * Nothing here says "allowed" for `stellar:pubnet`: the plan of a mainnet run
16
+ * (`planX402Run` with the opt-in) calls {@link assertMainnetPayerBalance} in
17
+ * L1, after the opt-in took the run's lock (`run-lock.ts`) and before anything
18
+ * is signed.
19
+ */
20
+ import { ConfigurationError } from "../errors.js";
21
+ import { PER_RUN_CAP_USD, formatUsd, usdFromBaseUnits, usdFromDollars } from "./budget.js";
22
+ import { networkClass } from "./networks.js";
23
+ /** At most this many dollars of USDC in the account a mainnet run pays from. */
24
+ export const MAINNET_PAYER_MAX_USD = 10;
25
+ /** USDC on Stellar has 7 decimals, as every Stellar Asset Contract has. */
26
+ const STELLAR_USDC_DECIMALS = 7;
27
+ /** {@link MAINNET_PAYER_MAX_USD} in base units of USDC on Stellar. */
28
+ export const MAINNET_PAYER_MAX_BASE_UNITS = BigInt(MAINNET_PAYER_MAX_USD) * 10n ** BigInt(STELLAR_USDC_DECIMALS);
29
+ /** The one mainnet a payer's balance is held to the rule on. */
30
+ const STELLAR_PUBNET = "stellar:pubnet";
31
+ /** A Stellar account address; anything else is never echoed. */
32
+ const STELLAR_ADDRESS = /^G[A-Z2-7]{55}$/;
33
+ /**
34
+ * A mainnet run does not start because of its payer's account. A
35
+ * `ConfigurationError`: it says nothing about the target. Nothing was signed.
36
+ */
37
+ export class MainnetPayerRefusedError extends ConfigurationError {
38
+ reason;
39
+ constructor(reason, message) {
40
+ super(`${message} Nothing was signed.`);
41
+ this.name = "MainnetPayerRefusedError";
42
+ this.reason = reason;
43
+ }
44
+ }
45
+ function payerShown(payer) {
46
+ return typeof payer === "string" && STELLAR_ADDRESS.test(payer) ? `the mainnet payer ${payer}` : "the mainnet payer";
47
+ }
48
+ /**
49
+ * Holds the payer's account to {@link MAINNET_PAYER_MAX_USD}.
50
+ *
51
+ * On a test network nothing is read and undefined is returned: the rule is for
52
+ * real funds. On `stellar:pubnet` the balance is read once and returned when
53
+ * it is $10 or less, for the plan to print. Any other network has no rule here
54
+ * and is refused without a read.
55
+ *
56
+ * @throws {MainnetPayerRefusedError} On `stellar:pubnet` when the balance is
57
+ * above $10 or cannot be read (no answer, an answer that is not a whole
58
+ * number of base units, or a read that threw: what it threw is not echoed,
59
+ * since an RPC URL may carry a key); and on any network that is neither a
60
+ * test network nor `stellar:pubnet`.
61
+ */
62
+ export async function assertMainnetPayerBalance(account) {
63
+ const { network } = account;
64
+ if (networkClass(network) === "test")
65
+ return undefined;
66
+ if (network !== STELLAR_PUBNET) {
67
+ throw new MainnetPayerRefusedError("network", "The run's network is not one whose payer's balance Wasit can hold to a limit, so no payment is made on it.");
68
+ }
69
+ const max = usdFromDollars(MAINNET_PAYER_MAX_USD);
70
+ let balance;
71
+ try {
72
+ balance = await account.readBalance();
73
+ }
74
+ catch {
75
+ balance = undefined;
76
+ }
77
+ if (typeof balance !== "bigint" || balance < 0n) {
78
+ throw new MainnetPayerRefusedError("unreadable", `The USDC balance of ${payerShown(account.payer)} could not be read on ${STELLAR_PUBNET}, so this run cannot ` +
79
+ `show that the account holds ${formatUsd(max)} or less.`);
80
+ }
81
+ if (balance > MAINNET_PAYER_MAX_BASE_UNITS) {
82
+ throw new MainnetPayerRefusedError("above-max", `${capitalised(payerShown(account.payer))} holds ${formatUsd(usdFromBaseUnits(balance, STELLAR_USDC_DECIMALS))} ` +
83
+ `in USDC (${balance} base units), above the ${formatUsd(max)} a mainnet payer may hold. The ` +
84
+ `${formatUsd(usdFromDollars(PER_RUN_CAP_USD))} cap holds one run, not two at once on one account: with ` +
85
+ `${formatUsd(max)} or less in it, the account is the limit. Move the rest out of this account, or pay from ` +
86
+ `a dedicated account that holds ${formatUsd(max)} or less.`);
87
+ }
88
+ return balance;
89
+ }
90
+ function capitalised(text) {
91
+ return text.charAt(0).toUpperCase() + text.slice(1);
92
+ }
@@ -0,0 +1,133 @@
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 { ConfigurationError } from "../errors.js";
18
+ import { type PinTerms } from "./budget.js";
19
+ /**
20
+ * Circle's USDC on Stellar mainnet, as a Stellar Asset Contract. Checked three
21
+ * ways on 2026-11-21: the issuer as Circle's page lists it
22
+ * (https://developers.circle.com/stablecoins/usdc-contract-addresses,
23
+ * "USDC-GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN"); the
24
+ * contract derived from that issuer with the SDK
25
+ * (`new Asset("USDC", issuer).contractId(Networks.PUBLIC)`); and
26
+ * `USDC_PUBNET_ADDRESS` of `@x402/stellar` 2.28.0. A test asserts all three.
27
+ */
28
+ export declare const MAINNET_USDC: {
29
+ readonly network: "stellar:pubnet";
30
+ readonly asset: "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75";
31
+ readonly code: "USDC";
32
+ readonly issuer: "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN";
33
+ readonly decimals: 7;
34
+ readonly symbol: "USDC";
35
+ };
36
+ /** The classic asset a Stellar Asset Contract wraps, as Horizon names it. */
37
+ export interface ClassicAsset {
38
+ readonly code: string;
39
+ readonly issuer: string;
40
+ }
41
+ /** The longest lifetime a mainnet payment is signed for, in seconds (B3): the run waits it out. */
42
+ export declare const MAINNET_MAX_TIMEOUT_SECONDS = 300;
43
+ /** At most this many ledgers between the RPC's latest ledger and public Horizon's (B17.2). */
44
+ export declare const MAINNET_ANCHOR_MAX_GAP_LEDGERS = 12;
45
+ /** Public Horizon of Stellar mainnet (B5 point 4): the SDK reads the ledger close time there too. */
46
+ export declare const PUBNET_HORIZON_URL = "https://horizon.stellar.org";
47
+ /** Which rule stopped the run. */
48
+ export type MainnetPlanRefusal =
49
+ /** The config's pin is missing, or its payee is not a valid address other than the payer. */
50
+ "pin"
51
+ /** An asset other than mainnet USDC. */
52
+ | "asset"
53
+ /** An option on another scheme or network. */
54
+ | "network"
55
+ /** A lifetime above 300 s, or not a positive whole number of seconds. */
56
+ | "lifetime"
57
+ /** The token's decimals are not 7. */
58
+ | "decimals"
59
+ /** The RPC's latest ledger is too far from Horizon's, or not a ledger number. */
60
+ | "anchor"
61
+ /** The RPC's USDC balance of the payer differs from Horizon's, or has no reading. */
62
+ | "balance"
63
+ /** Horizon could not be read, or its answer cannot be trusted. */
64
+ | "horizon"
65
+ /** The endpoint's URL: not https (and not on this machine), credentials in it, or a redirect elsewhere. */
66
+ | "endpoint";
67
+ /**
68
+ * A mainnet run does not start, or stops, because of one of L1's rules. A
69
+ * `ConfigurationError`: it says nothing about the target. Nothing was signed.
70
+ */
71
+ export declare class MainnetPlanRefusedError extends ConfigurationError {
72
+ readonly reason: MainnetPlanRefusal;
73
+ constructor(reason: MainnetPlanRefusal, message: string);
74
+ }
75
+ /**
76
+ * The pin a mainnet environment must have (B5 point 2): a payee that is a
77
+ * valid Stellar address and not the payer itself, and mainnet USDC as the
78
+ * asset. A transfer to the payer would leave its balance as it was and hide
79
+ * what the run paid. `payer` undefined: the dry run, which reads no key; the
80
+ * paid run holds the payee to the payer's address when it opens.
81
+ */
82
+ export declare function assertMainnetPin(pin: PinTerms | undefined, payer: string | undefined): void;
83
+ /**
84
+ * Where a URL pays, as a mainnet plan records it and L2 holds each payment to
85
+ * it: origin and path, the query and the fragment left out (a query may hold
86
+ * a key, and the plan is written to the ledger).
87
+ */
88
+ export declare function paidUrlOf(target: string): string;
89
+ /** The fields of a challenge's option these rules judge. */
90
+ export interface MainnetOption {
91
+ readonly scheme: string;
92
+ readonly network: string;
93
+ readonly asset: string;
94
+ readonly maxTimeoutSeconds: number;
95
+ }
96
+ /**
97
+ * The option a mainnet endpoint may be paid by (L1, B3): `exact` on
98
+ * `stellar:pubnet`, in mainnet USDC, valid for at most 300 s. The pin (payee
99
+ * and asset over every option) is `assertPinned`'s; the price is the budget's.
100
+ */
101
+ export declare function assertMainnetOption(option: MainnetOption): void;
102
+ /** The token's decimals, as read on chain (B4): the caps count USDC at 7. */
103
+ export declare function assertMainnetDecimals(decimals: unknown): void;
104
+ /**
105
+ * The RPC's latest ledger must be within {@link MAINNET_ANCHOR_MAX_GAP_LEDGERS}
106
+ * of public Horizon's (B17.2): the expiration bound of every signature counts
107
+ * from it, so an RPC that reports a later ledger cannot stretch a signature's
108
+ * life on mainnet.
109
+ */
110
+ export declare function assertAnchorNearHorizon(rpcLatest: number, horizonLatest: number): void;
111
+ /** An amount as Horizon writes it ("10.0000000"), in base units at 7 decimals; undefined for anything else. */
112
+ export declare function parseHorizonAmount(text: unknown): bigint | undefined;
113
+ /** An account's balances as Horizon lists them, in base units. */
114
+ export interface HorizonBalances {
115
+ /** The trustline of the asset; 0 when the account has none. */
116
+ readonly usdc: bigint;
117
+ /** Lumens (XLM). */
118
+ readonly native: bigint;
119
+ }
120
+ /**
121
+ * The USDC and XLM balances of a Horizon account answer, in base units. The
122
+ * trustline is matched by type, code and issuer; a token with the same code
123
+ * from another issuer is not it. Undefined for an answer that cannot be read
124
+ * plainly: no `balances`, no native balance, an amount that does not parse,
125
+ * or the same asset listed twice.
126
+ */
127
+ export declare function horizonBalances(account: unknown, asset: ClassicAsset): HorizonBalances | undefined;
128
+ /**
129
+ * The payer's USDC balance as the RPC reads it must be what Horizon lists
130
+ * (B17.12): the $10 rule reads the RPC's, and an RPC that under-reports it
131
+ * would let a fuller account pay.
132
+ */
133
+ export declare function assertBalancesAgree(rpcBalance: bigint | undefined, horizonBalance: bigint | undefined): void;