@wasit-dev/core 0.6.0 → 0.7.0

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.
package/README.md CHANGED
@@ -16,6 +16,12 @@ npm install @wasit-dev/core
16
16
 
17
17
  Requires Node.js `>=22`. Ships ESM only (`"type": "module"`), with TypeScript types included (`dist/index.d.ts`).
18
18
 
19
+ In a project on TypeScript 6 or 7, npm prints `ERESOLVE overriding peer dependency`
20
+ warnings while installing: they come from `@solana/kit` 5, which the Solana support
21
+ depends on through `@x402/svm`, and which declares an optional peer `typescript ^5`.
22
+ The install succeeds and core runs; measured with TypeScript 5.8, 6.0 and 7.0
23
+ ([evidence](https://github.com/wasit-dev/wasit/blob/main/docs/evidence/2026-10-05-0.7.0-verification-runs.md#installing-alongside-typescript)).
24
+
19
25
  ## Usage
20
26
 
21
27
  ```ts
@@ -51,7 +57,7 @@ Every check function returns `Promise<CheckResult[]>` and never rejects for a ta
51
57
  | Function | Checks | Cost |
52
58
  |---|---|---|
53
59
  | `runX402ReadChecks({ target, method?, body?, headers? })` | `X402-01`–`05` | Free |
54
- | `runX402PaymentChecks({ target, network, payerSecretKey, rpcUrl?, method?, body?, headers? })` | `X402-06`, `07` | **Settles a real payment every call** |
60
+ | `runX402PaymentChecks({ target, network, payerSecretKey, rpcUrl?, method?, body?, headers? })` | `X402-06`–`10` | **Settles a real payment every call** |
55
61
 
56
62
  ### MPP — charge mode
57
63
 
@@ -84,9 +90,11 @@ The full check catalogue — every check's exact pass criteria and spec referenc
84
90
 
85
91
  | Export | What it is |
86
92
  |---|---|
87
- | `CHECK_CATALOGUE` | `readonly CheckCatalogueEntry[]` — every check the suite can run: `id`, `name`, `protocol`, `specRef`, a one-line `summary`, and the optional flags `negative`, `destructive`, `costsFunds`. This is what `wasit checks` prints. |
93
+ | `CHECK_CATALOGUE` | `readonly CheckCatalogueEntry[]` — every check the suite can run: `id`, `name`, `protocol`, `specRef`, a one-line `summary`, a `fix` saying what to change when it fails, and the optional flags `negative`, `destructive`, `costsFunds`. This is what `wasit checks` prints. |
94
+ | `fixFor(result)` | → `FailureGuidance \| undefined` — for a FAIL, `{ fix, docs }`: the result's own `hint` when it has one, else the catalogue `fix`, and the check's docs page. Undefined for anything that is not a FAIL. |
95
+ | `catalogueEntry(id)`, `docsUrlFor(id)` | Look up a check's catalogue entry, or its docs page on usewasit.dev |
88
96
  | `PROTOCOL_IDS` | `readonly ProtocolId[]` — `"x402"`, `"mpp-charge"`, `"mpp-channel"` |
89
- | `toStructuredRun(results)` | → `StructuredRun` — the machine-readable reshape of a run: `outcome`, per-status counts, and a `results` array of `StructuredCheckResult`. The CLI's `--json` and the MCP server's `structuredContent` are both this function's output verbatim, so the three surfaces cannot describe the same run differently. |
97
+ | `toStructuredRun(results)` | → `StructuredRun` — the machine-readable reshape of a run: `outcome`, per-status counts, and a `results` array of `StructuredCheckResult` (a FAIL also carries `fix` and `docs`). The CLI's `--json` and the MCP server's `structuredContent` are both this function's output verbatim, so the three surfaces cannot describe the same run differently. |
90
98
 
91
99
  `outcome` is a name — `"conformant"`, `"non-conformant"`, `"no-verdict"` — not an exit code. `no-verdict` must never be read as `conformant`.
92
100
 
@@ -23,6 +23,12 @@ export interface CheckCatalogueEntry {
23
23
  readonly specRef: string;
24
24
  /** One-line summary of what the check verifies. Full pass criteria: docs/CHECKS.md. */
25
25
  readonly summary: string;
26
+ /**
27
+ * What to change when the check fails, in one or two sentences. A result
28
+ * may carry a more specific `hint` for the cause it found; this is the
29
+ * fallback, so every failure comes with something to act on.
30
+ */
31
+ readonly fix: string;
26
32
  /** True for a check that only passes because the target correctly REJECTED something. */
27
33
  readonly negative?: true;
28
34
  /** True for a check that permanently alters the target's state (see SECURITY.md). */
@@ -31,3 +37,7 @@ export interface CheckCatalogueEntry {
31
37
  readonly costsFunds?: true;
32
38
  }
33
39
  export declare const CHECK_CATALOGUE: readonly CheckCatalogueEntry[];
40
+ /** The catalogue entry for a check id, if there is one (PREFLIGHT has none). */
41
+ export declare function catalogueEntry(id: string): CheckCatalogueEntry | undefined;
42
+ /** The docs page for a check id, if it is in the catalogue. */
43
+ export declare function docsUrlFor(id: string): string | undefined;
package/dist/catalogue.js CHANGED
@@ -20,6 +20,7 @@ export const CHECK_CATALOGUE = [
20
20
  protocol: "x402",
21
21
  specRef: "x402 spec, HTTP semantics",
22
22
  summary: "An unpaid request must be answered with status code 402.",
23
+ fix: "Answer an unpaid request with 402 Payment Required and the challenge in a PAYMENT-REQUIRED header. A 200 means the route serves without payment; a 404 often means the wrong path or method (try --method POST).",
23
24
  },
24
25
  {
25
26
  id: "X402-02",
@@ -27,6 +28,7 @@ export const CHECK_CATALOGUE = [
27
28
  protocol: "x402",
28
29
  specRef: "x402 built-on-stellar guide",
29
30
  summary: "The 402 response must include a payment header.",
31
+ fix: "Send the challenge as base64-encoded JSON in a PAYMENT-REQUIRED response header, as the x402 v2 HTTP transport defines.",
30
32
  },
31
33
  {
32
34
  id: "X402-03",
@@ -34,20 +36,23 @@ export const CHECK_CATALOGUE = [
34
36
  protocol: "x402",
35
37
  specRef: "x402 spec §payment-required-object",
36
38
  summary: "The header value must be valid base64 that decodes to JSON.",
39
+ fix: "Base64-encode the JSON PaymentRequired object for the PAYMENT-REQUIRED header; the value must decode to valid JSON.",
37
40
  },
38
41
  {
39
42
  id: "X402-04",
40
43
  name: "Required Fields Present",
41
44
  protocol: "x402",
42
45
  specRef: "x402 spec §payment-required-object",
43
- summary: "The payload must include the core payment terms, under the field names its advertised version requires.",
46
+ summary: "Every payment option must carry each field its advertised version requires, with the right types.",
47
+ fix: "Give every option in `accepts` the fields its x402Version requires (v2: scheme, network, amount, asset, payTo, maxTimeoutSeconds).",
44
48
  },
45
49
  {
46
50
  id: "X402-05",
47
51
  name: "Network Identifier Valid",
48
52
  protocol: "x402",
49
- specRef: "x402 built-on-stellar guide",
50
- summary: "The network identifier must follow CAIP-2 (stellar:testnet or stellar:pubnet).",
53
+ specRef: "x402 v2 spec §11.1; CAIP-2",
54
+ summary: "Every advertised network identifier must be CAIP-2, and follow its namespace's rules where Wasit knows them (stellar, eip155, solana).",
55
+ fix: "Name each network with its CAIP-2 id, such as stellar:testnet or eip155:84532.",
51
56
  },
52
57
  {
53
58
  id: "X402-06",
@@ -56,6 +61,7 @@ export const CHECK_CATALOGUE = [
56
61
  specRef: "x402 spec §payment-flow",
57
62
  summary: "A resubmitted request carrying a valid signature must be accepted.",
58
63
  costsFunds: true,
64
+ fix: "After a valid payment, settle it, serve the resource with a 2xx, and return a PAYMENT-RESPONSE header naming the transaction that moved exactly the advertised amount of the asset to payTo.",
59
65
  },
60
66
  {
61
67
  id: "X402-07",
@@ -65,6 +71,35 @@ export const CHECK_CATALOGUE = [
65
71
  summary: "A deliberately corrupted signature must be rejected, not accepted.",
66
72
  negative: true,
67
73
  costsFunds: true,
74
+ fix: "Verify every payment before serving: pass it to the facilitator's verify step and refuse it when verification fails. Never serve on a payload that was only decoded.",
75
+ },
76
+ {
77
+ id: "X402-08",
78
+ name: "Payment Replay Rejected",
79
+ protocol: "x402",
80
+ specRef: "x402 v2 spec §10.1 (replay protection); exact scheme, one-time use",
81
+ summary: "A payment that was already accepted must not be accepted again.",
82
+ negative: true,
83
+ fix: "Treat every payment as single-use: verify it with the facilitator before serving, which refuses an authorization whose nonce is already spent, and never serve the same payload twice.",
84
+ },
85
+ {
86
+ id: "X402-09",
87
+ name: "Underpayment Rejected",
88
+ protocol: "x402",
89
+ specRef: "exact scheme verification: amount (Stellar: exactly requirements.amount; EVM: step 3)",
90
+ summary: "A validly signed payment for less than the advertised amount must be rejected.",
91
+ negative: true,
92
+ costsFunds: true,
93
+ fix: "Hold the signed payment to the advertised amount before serving. The facilitator's verify does; a server that skips it, or checks only the signature, sells for less than its price.",
94
+ },
95
+ {
96
+ id: "X402-10",
97
+ name: "Expired Authorization Rejected",
98
+ protocol: "x402",
99
+ specRef: "x402 v2 spec §10.1 (time constraints); exact scheme verification: validity window",
100
+ summary: "A payment whose authorization has expired must be rejected.",
101
+ negative: true,
102
+ fix: "Verify each payment with the facilitator before serving: it refuses an authorization past its window (validBefore on EVM, the auth entry's expiration ledger on Stellar).",
68
103
  },
69
104
  {
70
105
  id: "MPP-01",
@@ -73,6 +108,7 @@ export const CHECK_CATALOGUE = [
73
108
  specRef: "MPP Charge Guide; CAP-46 transfer events",
74
109
  summary: "The charge settles on-chain for exactly what the target advertised.",
75
110
  costsFunds: true,
111
+ fix: "Settle each charge on-chain for exactly the advertised amount, currency and recipient, from the paying account, and reference that transaction in the Payment-Receipt header.",
76
112
  },
77
113
  {
78
114
  id: "MPP-10",
@@ -80,6 +116,7 @@ export const CHECK_CATALOGUE = [
80
116
  protocol: "mpp-channel",
81
117
  specRef: "MPP Channel Guide",
82
118
  summary: "The channel contract deploys correctly and is the same channel the target bills through.",
119
+ fix: "Bill through the channel advertised in the 402 challenge, opened with the token, funder, recipient and refund waiting period you expect.",
83
120
  },
84
121
  {
85
122
  id: "MPP-11",
@@ -87,6 +124,7 @@ export const CHECK_CATALOGUE = [
87
124
  protocol: "mpp-channel",
88
125
  specRef: "MPP Channel Guide §closing-the-channel; @stellar/mpp channel server",
89
126
  summary: "A commitment must exceed the stored cumulative and cover the price of the current request.",
127
+ fix: "Refuse with 402 any commitment that does not exceed the stored cumulative amount, or that does not cover the price of the current request.",
90
128
  },
91
129
  {
92
130
  id: "MPP-12",
@@ -95,6 +133,7 @@ export const CHECK_CATALOGUE = [
95
133
  specRef: "MPP Channel Guide §closing-the-channel; @stellar/mpp channel server",
96
134
  summary: "A byte-identical credential resubmitted against the same challenge must be rejected.",
97
135
  negative: true,
136
+ fix: "Record each challenge id when a credential for it is accepted, and refuse a second credential for the same challenge with 402.",
98
137
  },
99
138
  {
100
139
  id: "MPP-13",
@@ -104,6 +143,7 @@ export const CHECK_CATALOGUE = [
104
143
  summary: "Closing with the highest commitment settles on-chain. Permanently ends the channel.",
105
144
  destructive: true,
106
145
  costsFunds: true,
146
+ fix: "On close, settle the highest commitment on-chain: `withdrawn` must equal the committed amount and `closeEffectiveAtLedger` must be set.",
107
147
  },
108
148
  {
109
149
  id: "MPP-14",
@@ -112,5 +152,21 @@ export const CHECK_CATALOGUE = [
112
152
  specRef: "MPP Channel Guide §closing-the-channel; @stellar/mpp channel server",
113
153
  summary: "A captured (amount, signature) pair must not be redeemable against a new challenge.",
114
154
  negative: true,
155
+ fix: "Refuse with 402 a previously accepted commitment presented under a new challenge: the cumulative amount must strictly increase.",
115
156
  },
116
157
  ];
158
+ /** Where each protocol's checks are documented on the site. */
159
+ const DOCS_URLS = {
160
+ x402: "https://usewasit.dev/docs/checks/x402",
161
+ "mpp-charge": "https://usewasit.dev/docs/checks/mpp-charge-mode",
162
+ "mpp-channel": "https://usewasit.dev/docs/checks/mpp-channel-mode",
163
+ };
164
+ /** The catalogue entry for a check id, if there is one (PREFLIGHT has none). */
165
+ export function catalogueEntry(id) {
166
+ return CHECK_CATALOGUE.find((entry) => entry.id === id);
167
+ }
168
+ /** The docs page for a check id, if it is in the catalogue. */
169
+ export function docsUrlFor(id) {
170
+ const entry = catalogueEntry(id);
171
+ return entry === undefined ? undefined : DOCS_URLS[entry.protocol];
172
+ }
package/dist/check.d.ts CHANGED
@@ -9,6 +9,12 @@ export interface CheckResult {
9
9
  /** False when the check ran and the target did not conform. */
10
10
  pass: boolean;
11
11
  detail: string;
12
+ /**
13
+ * What to change, for the specific cause this failure found. Optional:
14
+ * a failure without one falls back to its catalogue entry's `fix` (see
15
+ * {@link fixFor}). Meaningful only on a FAIL.
16
+ */
17
+ hint?: string;
12
18
  /**
13
19
  * True when the check did not run. A skipped check is neither a pass nor a
14
20
  * failure: `pass` is false so it can never be counted as conformance, and
@@ -68,6 +74,17 @@ export declare function skippedDestructive(id: string, name: string, reason: str
68
74
  export declare function errored(id: string, name: string, error: unknown): CheckResult;
69
75
  /** Builds the result for a check that was not run, for a non-destructive reason. */
70
76
  export declare function skipped(id: string, name: string, reason: string): CheckResult;
77
+ /** What to do about a failure, and where it is documented. */
78
+ export interface FailureGuidance {
79
+ readonly fix: string;
80
+ readonly docs?: string;
81
+ }
82
+ /**
83
+ * The guidance a front end shows under a FAIL: the result's own hint when it
84
+ * has one, else the check's catalogue fix. Undefined for anything that is not
85
+ * a FAIL, so a pass, a skip or a no-verdict never reads as a defect to fix.
86
+ */
87
+ export declare function fixFor(result: CheckResult): FailureGuidance | undefined;
71
88
  /** One check's result, reshaped for a machine-readable front end (CLI --json, MCP). */
72
89
  export interface StructuredCheckResult {
73
90
  readonly id: string;
@@ -80,6 +97,10 @@ export interface StructuredCheckResult {
80
97
  * unreachable | configuration | harness | setup.
81
98
  */
82
99
  readonly errorKind?: string;
100
+ /** Present only when `status` is "FAIL": what to change (see {@link fixFor}). */
101
+ readonly fix?: string;
102
+ /** Present only when `status` is "FAIL": the check's docs page. */
103
+ readonly docs?: string;
83
104
  }
84
105
  /** A full run, reshaped for a machine-readable front end (CLI --json, MCP). */
85
106
  export interface StructuredRun {
package/dist/check.js CHANGED
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * The result shape shared by every conformance check, across protocols.
3
3
  */
4
+ import { catalogueEntry, docsUrlFor } from "./catalogue.js";
4
5
  import { classifyCheckError } from "./errors.js";
5
6
  /**
6
7
  * Classifies one result.
@@ -94,6 +95,20 @@ export function skipped(id, name, reason) {
94
95
  detail: `Skipped: ${reason}`,
95
96
  };
96
97
  }
98
+ /**
99
+ * The guidance a front end shows under a FAIL: the result's own hint when it
100
+ * has one, else the check's catalogue fix. Undefined for anything that is not
101
+ * a FAIL, so a pass, a skip or a no-verdict never reads as a defect to fix.
102
+ */
103
+ export function fixFor(result) {
104
+ if (checkStatus(result) !== "FAIL")
105
+ return undefined;
106
+ const fix = result.hint ?? catalogueEntry(result.id)?.fix;
107
+ if (fix === undefined)
108
+ return undefined;
109
+ const docs = docsUrlFor(result.id);
110
+ return docs === undefined ? { fix } : { fix, docs };
111
+ }
97
112
  /**
98
113
  * Reshapes a run into the one JSON shape every machine-readable front end
99
114
  * uses — the CLI's `--json` output and the MCP server's `structuredContent`
@@ -113,13 +128,17 @@ export function toStructuredRun(results) {
113
128
  failed: counts.failed,
114
129
  errored: counts.errored,
115
130
  skipped: counts.skipped,
116
- results: results.map((result) => ({
117
- id: result.id,
118
- name: result.name,
119
- status: checkStatus(result),
120
- detail: result.detail,
121
- destructive: result.destructive === true,
122
- ...(result.error ? { errorKind: result.error.kind } : {}),
123
- })),
131
+ results: results.map((result) => {
132
+ const guidance = fixFor(result);
133
+ return {
134
+ id: result.id,
135
+ name: result.name,
136
+ status: checkStatus(result),
137
+ detail: result.detail,
138
+ destructive: result.destructive === true,
139
+ ...(result.error ? { errorKind: result.error.kind } : {}),
140
+ ...(guidance ?? {}),
141
+ };
142
+ }),
124
143
  };
125
144
  }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export { checkStatus, errored, skipped, skippedDestructive, summarize, toStructuredRun, } from "./check.js";
2
- export type { CheckResult, CheckStatus, RunSummary, StructuredCheckResult, StructuredRun, } from "./check.js";
3
- export { CHECK_CATALOGUE, PROTOCOL_IDS } from "./catalogue.js";
1
+ export { checkStatus, errored, fixFor, skipped, skippedDestructive, summarize, toStructuredRun, } from "./check.js";
2
+ export type { CheckResult, CheckStatus, FailureGuidance, RunSummary, StructuredCheckResult, StructuredRun, } from "./check.js";
3
+ export { CHECK_CATALOGUE, PROTOCOL_IDS, catalogueEntry, docsUrlFor } from "./catalogue.js";
4
4
  export type { CheckCatalogueEntry, ProtocolId } from "./catalogue.js";
5
5
  export * from "./errors.js";
6
6
  export * from "./x402/simulator.js";
@@ -10,3 +10,5 @@ export * from "./mpp/charge-suite.js";
10
10
  export * from "./mpp/suite.js";
11
11
  export { createUsdcTrustline, describeTransactionError, fundWithFriendbot, generateCommitmentKey, generateTestnetWallet, getTestnetWalletStatus, publicKeyFromSecret, sendUsdcFromDistributor, testnetUsdcAsset, TESTNET_USDC_ISSUER, } from "./wallet.js";
12
12
  export type { AssetBalance, FriendbotOutcome, GeneratedCommitmentKey, GeneratedWallet, WalletStatus, } from "./wallet.js";
13
+ export { paymentChainFor, paymentNetworks } from "./x402/chains/index.js";
14
+ export type { PaymentChain } from "./x402/chains/index.js";
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- export { checkStatus, errored, skipped, skippedDestructive, summarize, toStructuredRun, } from "./check.js";
2
- export { CHECK_CATALOGUE, PROTOCOL_IDS } from "./catalogue.js";
1
+ export { checkStatus, errored, fixFor, skipped, skippedDestructive, summarize, toStructuredRun, } from "./check.js";
2
+ export { CHECK_CATALOGUE, PROTOCOL_IDS, catalogueEntry, docsUrlFor } from "./catalogue.js";
3
3
  export * from "./errors.js";
4
4
  export * from "./x402/simulator.js";
5
5
  export * from "./mpp/channel.js";
@@ -11,3 +11,6 @@ export * from "./mpp/suite.js";
11
11
  // surface, and naming each entry keeps the rest of wallet.ts free to change
12
12
  // without that being a breaking change to @wasit-dev/core.
13
13
  export { createUsdcTrustline, describeTransactionError, fundWithFriendbot, generateCommitmentKey, generateTestnetWallet, getTestnetWalletStatus, publicKeyFromSecret, sendUsdcFromDistributor, testnetUsdcAsset, TESTNET_USDC_ISSUER, } from "./wallet.js";
14
+ // Which networks the x402 payment checks pay on, and which payer key each
15
+ // reads: front ends pick the key by the run's network.
16
+ export { paymentChainFor, paymentNetworks } from "./x402/chains/index.js";
@@ -4,7 +4,10 @@
4
4
  * The target's own 402 challenge is the source of truth for what should be
5
5
  * paid. Verifying against it rather than against this run's configuration is
6
6
  * what makes the check meaningful against a third-party service: it asks
7
- * whether the service settled what it advertised, not what we assumed.
7
+ * whether the service settled what it advertised, not what we assumed. The
8
+ * one term it does not get to choose is the network: Wasit signs only for the
9
+ * network the run names, so a target cannot redirect the payer's key to
10
+ * mainnet by asking for it.
8
11
  *
9
12
  * Settlement is verified from the CAP-46 `transfer` contract event rather than
10
13
  * the transaction envelope, because those can disagree. The envelope records
@@ -14,8 +17,10 @@
14
17
  * @stellar/mpp's own client guards against when it refuses to sign a
15
18
  * non-transfer authorization.
16
19
  */
20
+ import { charge } from "@stellar/mpp/charge/client";
17
21
  import { Challenge } from "mppx";
18
22
  import { type CheckResult } from "../check.js";
23
+ import { type MppNetwork } from "./network.js";
19
24
  export interface MppChargeCheckOptions {
20
25
  readonly target: string;
21
26
  readonly network: string;
@@ -27,7 +32,11 @@ export interface ChargeChallenge {
27
32
  readonly amount: bigint;
28
33
  readonly currency: string;
29
34
  readonly recipient: string;
35
+ /** The network the SDK's charge client would sign this challenge for. */
36
+ readonly network: MppNetwork;
30
37
  }
38
+ /** The SDK's charge client, as `charge()` from @stellar/mpp builds it. */
39
+ type ChargeClient = ReturnType<typeof charge>;
31
40
  /**
32
41
  * Reads the advertised charge terms out of an already-decoded challenge.
33
42
  *
@@ -38,15 +47,27 @@ export interface ChargeChallenge {
38
47
  * about the target rather than as a harness failure.
39
48
  */
40
49
  export declare function parseChargeChallenge(challenge: Challenge.Challenge): ChargeChallenge;
50
+ /**
51
+ * Pays `target` through `method` once at most, and only a challenge for
52
+ * `network`.
53
+ *
54
+ * mppx answers a 402 that follows a payment by paying the new challenge, up to
55
+ * `maxPaymentRetries` attempts (3 by default, dist/client/internal/Fetch.js in
56
+ * 0.8.14). MPP-01 judges one payment: a target that answers 402 after being
57
+ * paid has that 402 reported, rather than being paid twice more.
58
+ */
59
+ export declare function payCharge(target: string, network: MppNetwork, method: ChargeClient): Promise<Response>;
41
60
  /**
42
61
  * MPP-01: the charge must settle on-chain for exactly the advertised amount.
43
62
  *
44
63
  * Runs a real payment against the target every time it is called. See
45
64
  * docs/CHECKS.md — this check spends funds by design.
46
65
  *
47
- * @throws {ConfigurationError} Invalid target URL, network, or missing key.
66
+ * @throws {ConfigurationError} Invalid target URL, network, or missing key, or
67
+ * a challenge for another network than the run's (nothing is signed).
48
68
  * @throws {TargetUnreachableError} The target never answered.
49
69
  * @throws {MalformedResponseError} The target answered, non-conformantly.
50
70
  * @throws {Error} RPC failure — reported as `harness`, never as a target defect.
51
71
  */
52
72
  export declare function runMppChargeChecks(options: MppChargeCheckOptions): Promise<CheckResult[]>;
73
+ export {};
@@ -4,7 +4,10 @@
4
4
  * The target's own 402 challenge is the source of truth for what should be
5
5
  * paid. Verifying against it rather than against this run's configuration is
6
6
  * what makes the check meaningful against a third-party service: it asks
7
- * whether the service settled what it advertised, not what we assumed.
7
+ * whether the service settled what it advertised, not what we assumed. The
8
+ * one term it does not get to choose is the network: Wasit signs only for the
9
+ * network the run names, so a target cannot redirect the payer's key to
10
+ * mainnet by asking for it.
8
11
  *
9
12
  * Settlement is verified from the CAP-46 `transfer` contract event rather than
10
13
  * the transaction envelope, because those can disagree. The envelope records
@@ -18,7 +21,7 @@ import { Mppx, charge } from "@stellar/mpp/charge/client";
18
21
  import { Challenge, Receipt } from "mppx";
19
22
  import { Keypair } from "@stellar/stellar-sdk";
20
23
  import { ConfigurationError, MalformedResponseError, assertHttpUrl, fetchTarget, } from "../errors.js";
21
- import { assertMppNetwork, resolveRpcUrl } from "./network.js";
24
+ import { assertMppNetwork, isMppNetwork, resolveRpcUrl } from "./network.js";
22
25
  import { verifySettlement } from "../settlement.js";
23
26
  const CHECK_ID = "MPP-01";
24
27
  const CHECK_NAME = "Charge Settlement On-Chain";
@@ -87,7 +90,66 @@ export function parseChargeChallenge(challenge) {
87
90
  throw new MalformedResponseError(`Challenge advertises a non-numeric amount ("${amountRaw}"). The spec ` +
88
91
  `requires base units, e.g. "10000" for 0.001 of a 7-decimal token.`);
89
92
  }
90
- return { amount, currency, recipient };
93
+ return { amount, currency, recipient, network: chargeNetwork(request) };
94
+ }
95
+ /**
96
+ * The network @stellar/mpp's charge client signs a challenge for.
97
+ *
98
+ * The client takes it from the challenge, `methodDetails.network`, and signs a
99
+ * challenge that names none for testnet (`resolveNetworkId`,
100
+ * dist/shared/validation.js in 0.7.1). This reads it the same way, because
101
+ * what matters is the network the signature will be valid on.
102
+ */
103
+ function chargeNetwork(request) {
104
+ const network = asRecord(request["methodDetails"])?.["network"];
105
+ if (network === undefined || network === null)
106
+ return "stellar:testnet";
107
+ if (typeof network === "string" && isMppNetwork(network))
108
+ return network;
109
+ throw new MalformedResponseError(`Charge challenge names network ${JSON.stringify(network)}. A Stellar ` +
110
+ `network is "stellar:testnet" or "stellar:pubnet" (CAIP-2).`);
111
+ }
112
+ /** Refuses a challenge for any network but the run's, before anything is signed. */
113
+ function assertRunNetwork(asked, network) {
114
+ if (asked !== network) {
115
+ throw new ConfigurationError(`The target asks to be paid on ${asked}, and this run pays on ${network} ` +
116
+ `only, so nothing was signed.`);
117
+ }
118
+ }
119
+ /**
120
+ * `method`, refusing to sign a challenge for any network but `network`.
121
+ *
122
+ * Checking the unpaid challenge is not enough on its own: mppx requests the
123
+ * target again and pays the challenge in that answer, which the target is
124
+ * free to change. So the check also sits here, on the exact challenge about to
125
+ * be signed. Without it a target asking for `stellar:pubnet` gets a mainnet
126
+ * transfer signed, sent through the SDK's own default pubnet RPC endpoint.
127
+ */
128
+ function onNetwork(method, network) {
129
+ return {
130
+ ...method,
131
+ createCredential: async (parameters) => {
132
+ assertRunNetwork(chargeNetwork(asRecord(parameters.challenge.request) ?? {}), network);
133
+ return method.createCredential(parameters);
134
+ },
135
+ };
136
+ }
137
+ /**
138
+ * Pays `target` through `method` once at most, and only a challenge for
139
+ * `network`.
140
+ *
141
+ * mppx answers a 402 that follows a payment by paying the new challenge, up to
142
+ * `maxPaymentRetries` attempts (3 by default, dist/client/internal/Fetch.js in
143
+ * 0.8.14). MPP-01 judges one payment: a target that answers 402 after being
144
+ * paid has that 402 reported, rather than being paid twice more.
145
+ */
146
+ export async function payCharge(target, network, method) {
147
+ const mppx = Mppx.create({
148
+ methods: [onNetwork(method, network)],
149
+ polyfill: false,
150
+ maxPaymentRetries: 1,
151
+ });
152
+ return mppx.fetch(target);
91
153
  }
92
154
  function fail(detail) {
93
155
  return [{ id: CHECK_ID, name: CHECK_NAME, pass: false, detail }];
@@ -101,7 +163,8 @@ function pass(detail) {
101
163
  * Runs a real payment against the target every time it is called. See
102
164
  * docs/CHECKS.md — this check spends funds by design.
103
165
  *
104
- * @throws {ConfigurationError} Invalid target URL, network, or missing key.
166
+ * @throws {ConfigurationError} Invalid target URL, network, or missing key, or
167
+ * a challenge for another network than the run's (nothing is signed).
105
168
  * @throws {TargetUnreachableError} The target never answered.
106
169
  * @throws {MalformedResponseError} The target answered, non-conformantly.
107
170
  * @throws {Error} RPC failure — reported as `harness`, never as a target defect.
@@ -109,7 +172,7 @@ function pass(detail) {
109
172
  export async function runMppChargeChecks(options) {
110
173
  const { target, network, payerSecretKey, rpcUrl } = options;
111
174
  assertHttpUrl(target);
112
- assertMppNetwork(network);
175
+ const runNetwork = assertMppNetwork(network);
113
176
  if (!payerSecretKey) {
114
177
  throw new ConfigurationError("No payer secret key. MPP-01 settles a real payment and cannot run without one.");
115
178
  }
@@ -123,13 +186,26 @@ export async function runMppChargeChecks(options) {
123
186
  // Resolve the endpoint before spending anything: a bad RPC URL discovered
124
187
  // after settlement would leave money moved and no verdict to show for it.
125
188
  const endpoint = resolveRpcUrl(network, rpcUrl);
189
+ // The SDK's charge client builds its RPC client without `allowHttp`, so it
190
+ // cannot pay through an http endpoint, though settlement could be read from
191
+ // one. Say so before paying, instead of reporting the SDK's refusal as the
192
+ // target's failure.
193
+ if (endpoint.startsWith("http://")) {
194
+ throw new ConfigurationError(`MPP-01 pays through @stellar/mpp's charge client, which accepts only an ` +
195
+ `https RPC endpoint, and ${endpoint} is http. Nothing was sent.`);
196
+ }
126
197
  const advertised = await fetchChargeChallenge(target);
127
- const mppx = Mppx.create({ methods: [charge({ secretKey: payerSecretKey })], polyfill: false });
198
+ assertRunNetwork(advertised.network, runNetwork);
128
199
  let paid;
129
200
  try {
130
- paid = await mppx.fetch(target);
201
+ // The payment goes through the run's endpoint too. Left to itself the SDK
202
+ // picks its own per network, so `--rpc-url` would cover only the
203
+ // settlement read, and pubnet would get a default endpoint after all.
204
+ paid = await payCharge(target, runNetwork, charge({ secretKey: payerSecretKey, rpcUrl: endpoint }));
131
205
  }
132
206
  catch (error) {
207
+ if (error instanceof ConfigurationError)
208
+ throw error;
133
209
  // The target was reachable moments ago, so this is the payment path
134
210
  // failing, not the network. Report it as a conformance failure.
135
211
  throw new MalformedResponseError(`Payment attempt failed: ${error.message}`);
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The `exact` scheme on EVM, with the EIP-3009 transfer method (USDC's
3
+ * `transferWithAuthorization`): the payer signs an authorization off-chain,
4
+ * the facilitator submits it and pays the gas (`scheme_exact_evm.md`). So a
5
+ * payer needs the token and nothing else. A target that advertises the
6
+ * Permit2 method instead is paid through Permit2; with the
7
+ * `eip2612GasSponsoring` extension its one-time approval is a signed permit
8
+ * the facilitator submits, so that path needs no gas either.
9
+ *
10
+ * Settlement is read from the transaction receipt: the token contract's own
11
+ * ERC-20 `Transfer` log is held to the advertised terms, as the Stellar
12
+ * adapter holds the `transfer` event. Base Sepolia, where the official SDK
13
+ * ships its USDC and the public facilitator settles, and Ethereum
14
+ * Sepolia, which Circle's USDC with EIP-3009 also serves but no public
15
+ * facilitator settles.
16
+ */
17
+ import type { ExpectedSettlement, SettlementVerdict } from "../../settlement.js";
18
+ import type { PaymentChain } from "./types.js";
19
+ /**
20
+ * Circle's USDC on Ethereum Sepolia: EIP-3009, EIP-712 domain "USDC" version
21
+ * "2", 6 decimals (read from the contract, 2026-10-05). Not an SDK default.
22
+ */
23
+ export declare const ETHEREUM_SEPOLIA_USDC = "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238";
24
+ /** One ERC-20 `Transfer`, as the token contract logged it. */
25
+ export interface EvmTransfer {
26
+ readonly token: string;
27
+ readonly from: string;
28
+ readonly to: string;
29
+ readonly value: bigint;
30
+ }
31
+ /** A log as RPC returns it, reduced to what a transfer is read from. */
32
+ export interface EvmLog {
33
+ readonly address: string;
34
+ readonly topics: readonly string[];
35
+ readonly data: string;
36
+ }
37
+ /**
38
+ * The ERC-20 `Transfer` logs in a receipt. ERC-721 shares the event
39
+ * signature but indexes the token id as a fourth topic, so only logs with
40
+ * exactly three topics and a 32-byte value are read as token transfers.
41
+ */
42
+ export declare function evmTransfers(logs: readonly EvmLog[]): EvmTransfer[];
43
+ /**
44
+ * Holds a settled transaction's receipt to what the target advertised.
45
+ *
46
+ * The same rules as on Stellar: the transaction succeeded, it moved exactly
47
+ * one token transfer, and that transfer is the advertised amount of the
48
+ * advertised token, to the advertised recipient, from this run's own payer,
49
+ * so a target cannot cite some other transaction that happens to match.
50
+ */
51
+ export declare function verifyEvmReceipt(receipt: {
52
+ readonly status: string;
53
+ readonly logs: readonly EvmLog[];
54
+ }, reference: string, expected: ExpectedSettlement): SettlementVerdict;
55
+ /**
56
+ * Corrupts the payer's signature, and nothing else.
57
+ *
58
+ * The EIP-3009 payload is `{ signature, authorization }`; Permit2's carries a
59
+ * `signature` too. Flipping the first byte of `r` leaves a signature of the
60
+ * same length whose recovered signer is no longer `authorization.from`, while
61
+ * the amount, recipient and validity window stay intact. A target can refuse
62
+ * it only by verifying the signature (spec, verification step 1).
63
+ */
64
+ export declare function corruptEvmSignature(payload: Record<string, unknown>): Record<string, unknown>;
65
+ export declare const evmChain: PaymentChain;