@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,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;
@@ -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
+ }