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

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 (68) hide show
  1. package/README.md +12 -4
  2. package/dist/baseline.d.ts +109 -0
  3. package/dist/baseline.js +351 -0
  4. package/dist/catalogue.d.ts +10 -0
  5. package/dist/catalogue.js +69 -3
  6. package/dist/check.d.ts +78 -2
  7. package/dist/check.js +69 -10
  8. package/dist/ci-report.d.ts +74 -0
  9. package/dist/ci-report.js +391 -0
  10. package/dist/config.d.ts +205 -0
  11. package/dist/config.js +1011 -0
  12. package/dist/denied-env.d.ts +33 -0
  13. package/dist/denied-env.js +86 -0
  14. package/dist/errors.d.ts +44 -1
  15. package/dist/errors.js +151 -2
  16. package/dist/guard/budget.d.ts +135 -0
  17. package/dist/guard/budget.js +199 -0
  18. package/dist/guard/ci-event.d.ts +50 -0
  19. package/dist/guard/ci-event.js +125 -0
  20. package/dist/guard/mainnet-optin.d.ts +58 -0
  21. package/dist/guard/mainnet-optin.js +95 -0
  22. package/dist/guard/networks.d.ts +50 -0
  23. package/dist/guard/networks.js +80 -0
  24. package/dist/guard/rpc-identity.d.ts +45 -0
  25. package/dist/guard/rpc-identity.js +156 -0
  26. package/dist/guard/rpc-in-use.d.ts +48 -0
  27. package/dist/guard/rpc-in-use.js +84 -0
  28. package/dist/index.d.ts +34 -3
  29. package/dist/index.js +31 -2
  30. package/dist/mpp/channel-commitment.d.ts +48 -2
  31. package/dist/mpp/channel-commitment.js +80 -4
  32. package/dist/mpp/channel-credential.js +3 -0
  33. package/dist/mpp/channel.js +29 -0
  34. package/dist/mpp/charge.d.ts +25 -2
  35. package/dist/mpp/charge.js +100 -8
  36. package/dist/mpp/network.js +4 -1
  37. package/dist/mpp/suite.js +10 -2
  38. package/dist/report.d.ts +163 -0
  39. package/dist/report.js +282 -0
  40. package/dist/sanitize.d.ts +52 -0
  41. package/dist/sanitize.js +106 -0
  42. package/dist/settlement.d.ts +14 -0
  43. package/dist/settlement.js +1 -1
  44. package/dist/verdict.d.ts +24 -0
  45. package/dist/verdict.js +46 -0
  46. package/dist/versions.d.ts +50 -0
  47. package/dist/versions.js +123 -0
  48. package/dist/x402/chains/evm.d.ts +65 -0
  49. package/dist/x402/chains/evm.js +237 -0
  50. package/dist/x402/chains/index.d.ts +18 -0
  51. package/dist/x402/chains/index.js +28 -0
  52. package/dist/x402/chains/stellar.d.ts +38 -0
  53. package/dist/x402/chains/stellar.js +277 -0
  54. package/dist/x402/chains/svm.d.ts +69 -0
  55. package/dist/x402/chains/svm.js +333 -0
  56. package/dist/x402/chains/types.d.ts +152 -0
  57. package/dist/x402/chains/types.js +10 -0
  58. package/dist/x402/chains/wait.d.ts +36 -0
  59. package/dist/x402/chains/wait.js +42 -0
  60. package/dist/x402/plan.d.ts +82 -0
  61. package/dist/x402/plan.js +146 -0
  62. package/dist/x402/rejected-request.d.ts +146 -0
  63. package/dist/x402/rejected-request.js +269 -0
  64. package/dist/x402/requirements.d.ts +46 -0
  65. package/dist/x402/requirements.js +359 -0
  66. package/dist/x402/simulator.d.ts +74 -17
  67. package/dist/x402/simulator.js +907 -246
  68. package/package.json +11 -6
@@ -0,0 +1,152 @@
1
+ /**
2
+ * What the x402 payment checks need that differs from chain to chain.
3
+ *
4
+ * X402-01 through X402-05 need none of it: they read the challenge only, and
5
+ * apply to an x402 service on any chain. X402-06 to X402-10 build real
6
+ * payments, so they need a signer, a way to look the settlement up, and a way
7
+ * to forge only the payer's signature. One adapter per chain family supplies
8
+ * those, and the checks themselves stay the same everywhere.
9
+ */
10
+ import type { PaymentRequirements } from "@x402/core/types";
11
+ import type { x402Client } from "@x402/fetch";
12
+ import type { ExpectedSettlement, SettlementVerdict } from "../../settlement.js";
13
+ /**
14
+ * What a negative check signs differently from the honest payment. The
15
+ * payload still claims, in `accepted`, the terms the target advertised, so the
16
+ * only thing wrong with it is what was signed.
17
+ */
18
+ export interface AlteredSigning {
19
+ readonly amount?: string;
20
+ readonly maxTimeoutSeconds?: number;
21
+ readonly extra?: Record<string, unknown>;
22
+ }
23
+ /** How X402-10 builds a payment that has expired by the time it is sent. */
24
+ export interface ExpiredSigning {
25
+ /** The terms to sign the payment for. */
26
+ readonly terms: AlteredSigning;
27
+ /** How long to hold the signed payment before sending it. */
28
+ readonly holdMs: number;
29
+ }
30
+ /**
31
+ * One signed authorization of a payment, as the chain records its use
32
+ * (X402-11, D-032). Decoded from what the payer signed, never computed.
33
+ */
34
+ export interface SignedAuthorization {
35
+ /** The address that signed it. X402-11 holds it to the run's payer. */
36
+ readonly payer: string;
37
+ /** Its single-use id on the chain (on Stellar the auth entry's nonce), as text. */
38
+ readonly nonce: string;
39
+ /** The last ledger (or block) it can be used in, as signed. */
40
+ readonly expiresAt: number;
41
+ }
42
+ /** One read of the chain about some authorizations, all at the same state. */
43
+ export interface AuthorizationRead {
44
+ /** The chain's latest closed ledger when it answered. */
45
+ readonly latest: number;
46
+ /**
47
+ * Per authorization asked for, in order: the ledger its use was recorded in,
48
+ * or undefined when the chain holds no record of a use.
49
+ */
50
+ readonly used: readonly (number | undefined)[];
51
+ }
52
+ /** A transfer the chain recorded, as X402-11's second reading counts it. */
53
+ export interface RecordedTransfer {
54
+ readonly amount: bigint;
55
+ /** The transaction that made it (a hash), for the report. */
56
+ readonly reference: string;
57
+ readonly ledger: number;
58
+ }
59
+ /**
60
+ * How X402-11 reads whether an authorization was used, on chains where that
61
+ * can be read directly. A chain without one does not run X402-11.
62
+ */
63
+ export interface AuthorizationWatch {
64
+ /** What the chain's unit of time is called in a report: "ledger". */
65
+ readonly unit: string;
66
+ /** About how long one unit lasts, in milliseconds: the watch reads once per unit. */
67
+ readonly unitMs: number;
68
+ /**
69
+ * The seconds one unit counts for when a client turns an advertised lifetime
70
+ * into an expiration (the lifetime divided by this, rounded up). X402-11 does
71
+ * not send an authorization that outlives its 300 s by more than that count.
72
+ */
73
+ readonly unitSeconds: number;
74
+ /**
75
+ * The authorization a payment payload's inner `payload` carries. Throws
76
+ * `CheckSetupError` when it carries none that can be read, or more than one.
77
+ */
78
+ decode(payload: Record<string, unknown>): SignedAuthorization;
79
+ /** Whether each authorization was used, read in one call, so all at one state of the chain. */
80
+ read(network: string, rpcUrl: string, authorizations: readonly SignedAuthorization[]): Promise<AuthorizationRead>;
81
+ /**
82
+ * Every successful transfer of `asset` from `from` to `to` recorded from
83
+ * ledger `fromLedger` on. Throws when the chain cannot serve that range in
84
+ * full: a partial answer is never read as "no transfer".
85
+ */
86
+ transfers(network: string, rpcUrl: string, query: {
87
+ readonly asset: string;
88
+ readonly from: string;
89
+ readonly to: string;
90
+ readonly fromLedger: number;
91
+ }): Promise<{
92
+ readonly latest: number;
93
+ readonly transfers: readonly RecordedTransfer[];
94
+ }>;
95
+ }
96
+ export interface PaymentChain {
97
+ /** The chain family's name, for reports. */
98
+ readonly name: string;
99
+ /** The CAIP-2 networks Wasit pays on with this adapter. */
100
+ readonly networks: readonly string[];
101
+ /** The environment variable front ends read the payer key from. */
102
+ readonly payerKeyEnv: string;
103
+ /** What a settlement reference is on this chain, for a report ("a ... hash"). */
104
+ readonly referenceKind: string;
105
+ /**
106
+ * The RPC endpoint X402-06 verifies the settlement on. Throws
107
+ * `ConfigurationError` when there is none, before any payment is made.
108
+ */
109
+ resolveRpcUrl(network: string, override?: string): string;
110
+ /**
111
+ * Registers this chain's `exact` client scheme, signing with `payerKey`.
112
+ * `rpcUrl` is for client schemes that read the chain while building a
113
+ * payment (EVM Permit2 checks the token allowance, Solana fetches the mint
114
+ * and a blockhash); others ignore it.
115
+ */
116
+ registerPayer(client: x402Client, network: string, payerKey: string, rpcUrl: string): void | Promise<void>;
117
+ /**
118
+ * How X402-10 makes a payment that has expired when it arrives, for the
119
+ * option `selected`. Where the client derives the lifetime from
120
+ * `maxTimeoutSeconds`, a one-second lifetime and a hold long enough for the
121
+ * chain to pass it.
122
+ */
123
+ expiredSigning(selected: PaymentRequirements, rpcUrl: string): Promise<ExpiredSigning>;
124
+ /** The payer's address, which the settlement must come from. */
125
+ payerAddress(payerKey: string): string;
126
+ /** A new random payer key, in the form `payerKeyEnv` takes. */
127
+ generatePayerKey(): string;
128
+ /**
129
+ * The payer's balance of `asset`, in base units, as the chain reports it,
130
+ * or at most what the payer can spend from (never more than it holds).
131
+ * Undefined, or a throw, when the chain gives no clear answer: X402-06 then
132
+ * pays as if the balance were enough, so a failed read never becomes a
133
+ * verdict.
134
+ */
135
+ payerBalance(network: string, rpcUrl: string, payer: string, asset: string): Promise<bigint | undefined>;
136
+ /** Whether `reference` has the shape of a settlement on this chain. */
137
+ isSettlementReference(reference: string): boolean;
138
+ /**
139
+ * Looks the settlement up on `network` and holds it to the advertised
140
+ * terms. Returns a verdict about the target; throws when the chain's RPC
141
+ * gives no answer, which says nothing about the target.
142
+ */
143
+ verifySettlement(network: string, rpcUrl: string, reference: string, expected: ExpectedSettlement): Promise<SettlementVerdict>;
144
+ /**
145
+ * The payment payload's inner `payload` with the payer's signature, and
146
+ * nothing else, corrupted. Throws `CheckSetupError` when there is no
147
+ * signature to corrupt.
148
+ */
149
+ corruptPayload(payload: Record<string, unknown>): Record<string, unknown>;
150
+ /** X402-11's chain reads. Absent: X402-11 is skipped on this chain, nothing signed. */
151
+ readonly authorizations?: AuthorizationWatch;
152
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * What the x402 payment checks need that differs from chain to chain.
3
+ *
4
+ * X402-01 through X402-05 need none of it: they read the challenge only, and
5
+ * apply to an x402 service on any chain. X402-06 to X402-10 build real
6
+ * payments, so they need a signer, a way to look the settlement up, and a way
7
+ * to forge only the payer's signature. One adapter per chain family supplies
8
+ * those, and the checks themselves stay the same everywhere.
9
+ */
10
+ export {};
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Waiting for a settled transaction to appear on chains whose RPC reports
3
+ * progress as a block (or slot) number: EVM and Solana.
4
+ */
5
+ /** What looking for a settled transaction established. */
6
+ export type ReceiptLookup<R> = {
7
+ readonly kind: "found";
8
+ readonly receipt: R;
9
+ } | {
10
+ readonly kind: "missing";
11
+ readonly blocksWatched: bigint;
12
+ } | {
13
+ readonly kind: "stalled";
14
+ readonly blocksWatched: bigint;
15
+ readonly waitedMs: number;
16
+ };
17
+ /**
18
+ * Polls for a settled transaction until it appears, until the chain has
19
+ * produced enough blocks (slots, on Solana) without it to call it missing, or
20
+ * until the RPC stops advancing.
21
+ *
22
+ * A fixed wall-clock wait cannot tell a transaction that does not exist from
23
+ * an RPC that is behind, so the wait is counted in the chain's own progress,
24
+ * and an RPC that stops advancing gives no verdict at all.
25
+ *
26
+ * `getReceipt` returns undefined while the transaction is unknown; any other
27
+ * failure is the harness's and propagates. Clock and sleep are parameters so
28
+ * the three outcomes can be exercised without a network.
29
+ */
30
+ export declare function waitForReceipt<R>(getReceipt: () => Promise<R | undefined>, getBlockNumber: () => Promise<bigint>, options: {
31
+ readonly blocks: bigint;
32
+ readonly maxWaitMs?: number;
33
+ readonly delayMs?: number;
34
+ readonly now?: () => number;
35
+ readonly sleep?: (ms: number) => Promise<void>;
36
+ }): Promise<ReceiptLookup<R>>;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Waiting for a settled transaction to appear on chains whose RPC reports
3
+ * progress as a block (or slot) number: EVM and Solana.
4
+ */
5
+ const MAX_WAIT_MS = 120_000;
6
+ const POLL_DELAY_MS = 1_000;
7
+ /**
8
+ * Polls for a settled transaction until it appears, until the chain has
9
+ * produced enough blocks (slots, on Solana) without it to call it missing, or
10
+ * until the RPC stops advancing.
11
+ *
12
+ * A fixed wall-clock wait cannot tell a transaction that does not exist from
13
+ * an RPC that is behind, so the wait is counted in the chain's own progress,
14
+ * and an RPC that stops advancing gives no verdict at all.
15
+ *
16
+ * `getReceipt` returns undefined while the transaction is unknown; any other
17
+ * failure is the harness's and propagates. Clock and sleep are parameters so
18
+ * the three outcomes can be exercised without a network.
19
+ */
20
+ export async function waitForReceipt(getReceipt, getBlockNumber, options) {
21
+ const blocks = options.blocks;
22
+ const maxWaitMs = options.maxWaitMs ?? MAX_WAIT_MS;
23
+ const delayMs = options.delayMs ?? POLL_DELAY_MS;
24
+ const now = options.now ?? Date.now;
25
+ const pause = options.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
26
+ const startedAt = now();
27
+ let firstBlock;
28
+ for (;;) {
29
+ const receipt = await getReceipt();
30
+ if (receipt !== undefined)
31
+ return { kind: "found", receipt };
32
+ const block = await getBlockNumber();
33
+ firstBlock ??= block;
34
+ const blocksWatched = block - firstBlock;
35
+ if (blocksWatched >= blocks)
36
+ return { kind: "missing", blocksWatched };
37
+ const waitedMs = now() - startedAt;
38
+ if (waitedMs >= maxWaitMs)
39
+ return { kind: "stalled", blocksWatched, waitedMs };
40
+ await pause(delayMs);
41
+ }
42
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * L1, the plan (spec B3, B4): before anything is signed, read each endpoint's
3
+ * unpaid challenge and work out what the run's payment checks would sign, and
4
+ * refuse what the caps or the pin do not allow.
5
+ *
6
+ * The plan is what `--dry-run` prints, and what a paying run hands to each
7
+ * endpoint's checks: L2 then refuses any signature the plan did not allow, so
8
+ * a service that raises its price or changes its payee between the plan and
9
+ * the payment gets a refusal, not a signature.
10
+ *
11
+ * It sends no payment, reads no key and signs nothing.
12
+ */
13
+ import { type PinTerms, type PlannedSignature } from "../guard/budget.js";
14
+ import { type RejectCase } from "./rejected-request.js";
15
+ import { type RequestShape } from "./simulator.js";
16
+ export interface PlanEndpointInput extends RequestShape {
17
+ readonly name: string;
18
+ readonly target: string;
19
+ /** The request the service must refuse: X402-11 signs once more, when it can run. */
20
+ readonly reject?: RejectCase;
21
+ }
22
+ export interface X402PlanOptions {
23
+ readonly network: string;
24
+ readonly pin?: PinTerms;
25
+ /** A lower per-run cap in dollars. */
26
+ readonly maxRunUsd?: number;
27
+ readonly endpoints: readonly PlanEndpointInput[];
28
+ }
29
+ /** The option an endpoint's checks would pay, as its challenge stated it. */
30
+ export interface PlannedOption {
31
+ readonly scheme: string;
32
+ readonly network: string;
33
+ readonly payTo: string;
34
+ readonly asset: string;
35
+ /** Base units. */
36
+ readonly amount: bigint;
37
+ readonly maxTimeoutSeconds: number;
38
+ }
39
+ export type EndpointPlanStatus =
40
+ /** Its payment checks would sign `signatures`. */
41
+ "planned"
42
+ /** Its payment checks would not pay at all (no option to pay, an unreadable challenge): `reason`. */
43
+ | "not-paid"
44
+ /** The guard refuses to pay it: `reason`. */
45
+ | "refused";
46
+ export interface EndpointPlan {
47
+ readonly name: string;
48
+ readonly status: EndpointPlanStatus;
49
+ readonly reason?: string;
50
+ readonly option?: PlannedOption;
51
+ readonly signatures: readonly PlannedSignature[];
52
+ /** Base units of `option.asset`. */
53
+ readonly worstCase: bigint;
54
+ /** Dollar units of `guard/budget.ts`; format with `formatUsd`. */
55
+ readonly worstCaseUsd: bigint;
56
+ }
57
+ export interface RunPlan {
58
+ readonly network: string;
59
+ readonly pin?: PinTerms;
60
+ readonly perPaymentCapUsd: bigint;
61
+ readonly capUsd: bigint;
62
+ /** Lowered by maxRunUsd. */
63
+ readonly capLowered: boolean;
64
+ readonly endpoints: readonly EndpointPlan[];
65
+ /** The sum over the planned endpoints. */
66
+ readonly worstCaseUsd: bigint;
67
+ /** Set when the run must not start: its worst case is above its cap. Nothing was signed. */
68
+ readonly refusal?: string;
69
+ }
70
+ /**
71
+ * The plan of a run's x402 payment checks. Throws the guard's refusal for a
72
+ * network that is not a test network (L0), before any request; the mainnet
73
+ * plan (the payer's balance, the token's decimals read on chain, the
74
+ * authorization lifetime) is part of the opt-in, not of this version.
75
+ */
76
+ export declare function planX402Run(options: X402PlanOptions): Promise<RunPlan>;
77
+ /**
78
+ * The plan for a terminal or a log: the network, the caps, and per endpoint
79
+ * the destination, the asset, the amount of each signature and the worst case.
80
+ * Sanitised; no header value and no key (the plan holds neither).
81
+ */
82
+ export declare function describePlan(plan: RunPlan): string[];
@@ -0,0 +1,146 @@
1
+ /**
2
+ * L1, the plan (spec B3, B4): before anything is signed, read each endpoint's
3
+ * unpaid challenge and work out what the run's payment checks would sign, and
4
+ * refuse what the caps or the pin do not allow.
5
+ *
6
+ * The plan is what `--dry-run` prints, and what a paying run hands to each
7
+ * endpoint's checks: L2 then refuses any signature the plan did not allow, so
8
+ * a service that raises its price or changes its payee between the plan and
9
+ * the payment gets a refusal, not a signature.
10
+ *
11
+ * It sends no payment, reads no key and signs nothing.
12
+ */
13
+ import { sanitizeText } from "../sanitize.js";
14
+ import { assertPaymentNetworkAllowed } from "../guard/networks.js";
15
+ import { PER_PAYMENT_CAP_USD, PER_RUN_CAP_USD, PaymentGuardRefusedError, RunBudget, assertPinned, formatUsd, parseAmount, plannedSignatures, shown, usdAsset, usdFromDollars, } from "../guard/budget.js";
16
+ import { paymentChainFor } from "./chains/index.js";
17
+ import { REJECTED_REQUEST_MAX_LIFETIME_SECONDS, REJECTED_REQUEST_MIN_LIFETIME_SECONDS } from "./rejected-request.js";
18
+ import { readPaymentChallenge } from "./simulator.js";
19
+ function message(error) {
20
+ return sanitizeText(error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ");
21
+ }
22
+ const nothing = (name, status, reason, option) => ({
23
+ name,
24
+ status,
25
+ reason,
26
+ ...(option === undefined ? {} : { option }),
27
+ signatures: [],
28
+ worstCase: 0n,
29
+ worstCaseUsd: 0n,
30
+ });
31
+ async function planEndpoint(network, pin, endpoint) {
32
+ let read;
33
+ try {
34
+ read = await readPaymentChallenge({ ...endpoint, network });
35
+ }
36
+ catch (error) {
37
+ // The same reasons the payment checks give when they would not pay.
38
+ return nothing(endpoint.name, "not-paid", message(error));
39
+ }
40
+ const { paymentRequired, selected } = read;
41
+ try {
42
+ assertPinned(network, paymentRequired.accepts, pin);
43
+ const amount = parseAmount(selected.amount);
44
+ const option = {
45
+ scheme: selected.scheme,
46
+ network: selected.network,
47
+ payTo: selected.payTo,
48
+ asset: selected.asset,
49
+ amount,
50
+ maxTimeoutSeconds: selected.maxTimeoutSeconds,
51
+ };
52
+ const asset = usdAsset(network, selected.asset);
53
+ const price = RunBudget.valueOf(network, selected.asset, amount);
54
+ if (asset === undefined || price === undefined) {
55
+ return nothing(endpoint.name, "refused", `it asks to be paid in an asset Wasit does not value in US dollars, so it cannot be held to the ` +
56
+ `$${PER_PAYMENT_CAP_USD}.00 cap. Nothing was signed.`, option);
57
+ }
58
+ const perPayment = usdFromDollars(PER_PAYMENT_CAP_USD);
59
+ if (price > perPayment) {
60
+ return nothing(endpoint.name, "refused", `it is priced at ${amount} base units of ${asset.symbol} (${formatUsd(price)}), above the ` +
61
+ `${formatUsd(perPayment)} per payment fixed in Wasit. Nothing was signed. Test a route ` +
62
+ `priced at ${formatUsd(perPayment)} or less.`, option);
63
+ }
64
+ // X402-11 signs only when it can reach a verdict: a reject case, a chain whose
65
+ // authorizations can be read, a lifetime it waits out (D-032).
66
+ const rejectedRequest = endpoint.reject !== undefined &&
67
+ paymentChainFor(network)?.authorizations !== undefined &&
68
+ selected.maxTimeoutSeconds >= REJECTED_REQUEST_MIN_LIFETIME_SECONDS &&
69
+ selected.maxTimeoutSeconds <= REJECTED_REQUEST_MAX_LIFETIME_SECONDS;
70
+ const signatures = plannedSignatures(amount, { rejectedRequest });
71
+ const worstCase = signatures.reduce((sum, entry) => sum + entry.amount, 0n);
72
+ return {
73
+ name: endpoint.name,
74
+ status: "planned",
75
+ option,
76
+ signatures,
77
+ worstCase,
78
+ worstCaseUsd: RunBudget.valueOf(network, selected.asset, worstCase) ?? 0n,
79
+ };
80
+ }
81
+ catch (error) {
82
+ if (error instanceof PaymentGuardRefusedError)
83
+ return nothing(endpoint.name, "refused", message(error));
84
+ throw error;
85
+ }
86
+ }
87
+ /**
88
+ * The plan of a run's x402 payment checks. Throws the guard's refusal for a
89
+ * network that is not a test network (L0), before any request; the mainnet
90
+ * plan (the payer's balance, the token's decimals read on chain, the
91
+ * authorization lifetime) is part of the opt-in, not of this version.
92
+ */
93
+ export async function planX402Run(options) {
94
+ assertPaymentNetworkAllowed("x402", options.network);
95
+ const budget = new RunBudget(options.maxRunUsd === undefined ? {} : { maxRunUsd: options.maxRunUsd });
96
+ const capLowered = budget.capUsd < usdFromDollars(PER_RUN_CAP_USD);
97
+ const endpoints = [];
98
+ for (const endpoint of options.endpoints) {
99
+ endpoints.push(await planEndpoint(options.network, options.pin, endpoint));
100
+ }
101
+ const planned = endpoints.filter((endpoint) => endpoint.status === "planned");
102
+ const worstCaseUsd = planned.reduce((sum, endpoint) => sum + endpoint.worstCaseUsd, 0n);
103
+ const base = {
104
+ network: options.network,
105
+ ...(options.pin === undefined ? {} : { pin: options.pin }),
106
+ perPaymentCapUsd: usdFromDollars(PER_PAYMENT_CAP_USD),
107
+ capUsd: budget.capUsd,
108
+ capLowered,
109
+ endpoints,
110
+ worstCaseUsd,
111
+ };
112
+ if (worstCaseUsd <= budget.capUsd)
113
+ return base;
114
+ const parts = planned.map((endpoint) => `${sanitizeText(endpoint.name)} ${formatUsd(endpoint.worstCaseUsd)}`);
115
+ return {
116
+ ...base,
117
+ refusal: `This run could spend up to ${formatUsd(worstCaseUsd)} (${parts.join(", ")}), above the ` +
118
+ `${formatUsd(budget.capUsd)} per run${capLowered ? " set by maxRunUsd" : ""}. Nothing was signed. ` +
119
+ `Select fewer endpoints with --endpoint, or test a cheaper route.`,
120
+ };
121
+ }
122
+ /**
123
+ * The plan for a terminal or a log: the network, the caps, and per endpoint
124
+ * the destination, the asset, the amount of each signature and the worst case.
125
+ * Sanitised; no header value and no key (the plan holds neither).
126
+ */
127
+ export function describePlan(plan) {
128
+ const lines = [
129
+ `Plan (dry run): x402 payment checks on ${plan.network}. Nothing is signed or sent.`,
130
+ `Caps: ${formatUsd(plan.perPaymentCapUsd)} a payment, ${formatUsd(plan.capUsd)} this run` +
131
+ `${plan.capLowered ? " (maxRunUsd)" : ""}.`,
132
+ ...(plan.pin === undefined ? [] : [`Pinned: payTo ${plan.pin.payTo}, asset ${plan.pin.asset}.`]),
133
+ ];
134
+ for (const endpoint of plan.endpoints) {
135
+ if (endpoint.status !== "planned" || endpoint.option === undefined) {
136
+ lines.push(` ${endpoint.name}: ${endpoint.status === "refused" ? "refused" : "not paid"}: ${endpoint.reason ?? ""}`);
137
+ continue;
138
+ }
139
+ const { option } = endpoint;
140
+ lines.push(` ${endpoint.name}: pays ${shown(option.payTo)} in ${shown(option.asset)}, up to ${formatUsd(endpoint.worstCaseUsd)}`, ` ${endpoint.signatures.map((entry) => `${entry.check} ${entry.amount}`).join(", ")} (base units)`);
141
+ }
142
+ lines.push(`Worst case: ${formatUsd(plan.worstCaseUsd)} of ${formatUsd(plan.capUsd)}.`);
143
+ if (plan.refusal !== undefined)
144
+ lines.push(`Refused: ${plan.refusal}`);
145
+ return lines.map((line) => sanitizeText(line));
146
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * X402-11, "Rejected Request Not Settled" (spec B7 as D-032 changed it).
3
+ *
4
+ * Wasit sends a valid payment, for the advertised terms exactly, with a request
5
+ * the builder's config declares invalid (`endpoints[].reject`), then reads the
6
+ * chain: the nonce of that payment's authorization must still be unused once
7
+ * its expiration ledger has passed. The verdict comes from one read that asks
8
+ * for that nonce and for X402-06's, which was used and must be found: a read
9
+ * that cannot find X402-06's cannot show that ours is absent. The payer's
10
+ * balance and the transfer events are second readings; when they disagree with
11
+ * the nonce, there is no verdict.
12
+ *
13
+ * The wait (Najmi, 2026-11-16): a payment whose advertised lifetime
14
+ * (`maxTimeoutSeconds`) is at most 300 s is waited out, with a hard stop 360 s
15
+ * after it was sent; a longer one is not signed at all (it is read again on the
16
+ * challenge the payment is signed from), and an authorization the client signs
17
+ * to outlive it is not sent. A lifetime below 30 s is not signed either, and an
18
+ * authorization with fewer than 3 ledgers left is not sent (2026-11-17).
19
+ *
20
+ * This file holds the parts that need no network: the rules, the reject
21
+ * request's shape, the watch loop over a chain's reads, and the verdict. The
22
+ * check itself, which pays, is in `simulator.ts` with the other payment checks.
23
+ */
24
+ import { type CheckResult } from "../check.js";
25
+ import type { AuthorizationWatch, SignedAuthorization } from "./chains/types.js";
26
+ export declare const REJECTED_REQUEST_ID = "X402-11";
27
+ export declare const REJECTED_REQUEST_NAME = "Rejected Request Not Settled";
28
+ /** The longest advertised lifetime X402-11 waits out on a test network. */
29
+ export declare const REJECTED_REQUEST_MAX_LIFETIME_SECONDS = 300;
30
+ /**
31
+ * The shortest advertised lifetime X402-11 signs for (Najmi, 2026-11-17,
32
+ * screening S-1): a payment valid for a few seconds can expire before a service
33
+ * that settles it has it on chain, and its unused authorization would then show
34
+ * nothing about the service.
35
+ */
36
+ export declare const REJECTED_REQUEST_MIN_LIFETIME_SECONDS = 30;
37
+ /** The fewest units of validity a signed authorization must have left when X402-11 sends it. */
38
+ export declare const REJECTED_REQUEST_MIN_UNITS_LEFT = 3;
39
+ /**
40
+ * How long after the payment is sent the watch stops, whatever the lifetime:
41
+ * a 300 s lifetime is 60 ledgers of 5 s, and the verdict needs the ledger
42
+ * after it, so about 305 s; the rest is slack for a slow ledger or RPC.
43
+ */
44
+ export declare const REJECTED_REQUEST_HARD_STOP_MS = 360000;
45
+ /**
46
+ * Tests only: a shorter hard stop, so "still valid when the watch stopped" can
47
+ * be shown without a six-minute test. It can only lower the stop. Not exported
48
+ * from the package index; no flag, setting or tool argument reaches it.
49
+ */
50
+ export declare function setRejectedRequestHardStopForTesting(ms: number | undefined): void;
51
+ export declare function rejectedRequestHardStopMs(): number;
52
+ /** The request the service must refuse, as the config gives it (`ResolvedReject`). */
53
+ export interface RejectCase {
54
+ readonly method?: string;
55
+ readonly headers?: Readonly<Record<string, string>>;
56
+ /** Serialised, as `ResolvedReject` holds it. */
57
+ readonly body?: string;
58
+ readonly note?: string;
59
+ }
60
+ interface Shape {
61
+ readonly method?: string;
62
+ readonly body?: string;
63
+ readonly headers?: Readonly<Record<string, string>>;
64
+ }
65
+ /**
66
+ * The endpoint's own request with the reject case over it: its method when it
67
+ * names one, its headers over the endpoint's (by name, ignoring case), and its
68
+ * body instead of the endpoint's. A method that carries no body drops the
69
+ * endpoint's body; the config already refuses a reject body on such a method.
70
+ */
71
+ export declare function rejectRequestShape(shape: Shape, reject: RejectCase): Shape;
72
+ /** What the watch found, from the chain's reads only. */
73
+ export type WatchOutcome =
74
+ /** The chain records the authorization as used, in `ledger`. */
75
+ {
76
+ readonly kind: "used";
77
+ readonly ledger: number;
78
+ readonly latest: number;
79
+ }
80
+ /** A read at `latest`, past the expiration ledger, found it unused, and found the control. */
81
+ | {
82
+ readonly kind: "unused";
83
+ readonly latest: number;
84
+ }
85
+ /** The hard stop came first: at `latest` it was unused and could still be used. */
86
+ | {
87
+ readonly kind: "still-valid";
88
+ readonly latest: number;
89
+ }
90
+ /** The chain could not be read to the end, or its answer could not be trusted: `why`. */
91
+ | {
92
+ readonly kind: "unread";
93
+ readonly why: string;
94
+ };
95
+ export interface WatchInput {
96
+ readonly watch: AuthorizationWatch;
97
+ readonly network: string;
98
+ readonly rpcUrl: string;
99
+ readonly ours: SignedAuthorization;
100
+ /** X402-06's authorization, which was used: every read must find it. */
101
+ readonly control: SignedAuthorization;
102
+ /** When the payment was sent (ms since the epoch): the hard stop counts from it. */
103
+ readonly sentAt: number;
104
+ readonly now?: () => number;
105
+ readonly sleep?: (ms: number) => Promise<void>;
106
+ }
107
+ /**
108
+ * Reads the chain once a ledger until the authorization is used, or a read
109
+ * past its expiration ledger finds it unused, or the hard stop comes. Every
110
+ * read asks for the control too; one that does not return it ends the watch
111
+ * with no reading. Never throws: a failed read is an `unread` outcome.
112
+ */
113
+ export declare function watchAuthorization(input: WatchInput): Promise<WatchOutcome>;
114
+ export interface RejectedRequestEvidence {
115
+ /** What the service answered the paid invalid request with. */
116
+ readonly status: number;
117
+ readonly reason?: string;
118
+ /** Base units, as signed: the advertised amount. */
119
+ readonly amount: bigint;
120
+ /** The expiration ledger, decoded from the signed authorization. */
121
+ readonly expiresAt: number;
122
+ /** "ledger". */
123
+ readonly unit: string;
124
+ readonly watch: WatchOutcome;
125
+ /** The payer's balance before signing and after the watch. Missing: not read. */
126
+ readonly balance?: {
127
+ readonly before: bigint;
128
+ readonly after: bigint;
129
+ };
130
+ /** Transfers of exactly `amount` from the payer to `payTo` recorded after the payment was sent. Missing: not read. */
131
+ readonly transfers?: readonly {
132
+ readonly reference: string;
133
+ readonly ledger: number;
134
+ }[];
135
+ }
136
+ /**
137
+ * X402-11's verdict from what the service answered and what the chain shows.
138
+ *
139
+ * - served (2xx): FAIL, whatever the chain shows; the chain only adds whether it settled.
140
+ * - refused, used, the second readings agree: FAIL, the payment was taken.
141
+ * - refused, unused past the expiry, the second readings agree: PASS.
142
+ * - refused and still valid at the hard stop: SKIP, "not settled by ledger N; still valid until ledger M".
143
+ * - anything else (a reading that disagrees or is missing, a read that failed): no verdict, never PASS.
144
+ */
145
+ export declare function rejectedRequestVerdict(evidence: RejectedRequestEvidence): CheckResult;
146
+ export {};