@wasit-dev/core 0.2.0 → 0.4.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
@@ -80,6 +80,49 @@ Every check function returns `Promise<CheckResult[]>` and never rejects for a ta
80
80
 
81
81
  The full check catalogue — every check's exact pass criteria and spec reference — is in [`docs/CHECKS.md`](https://github.com/wasit-dev/wasit/blob/main/docs/CHECKS.md).
82
82
 
83
+ ### Catalogue and structured output
84
+
85
+ | Export | What it is |
86
+ |---|---|
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. |
88
+ | `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. |
90
+
91
+ `outcome` is a name — `"conformant"`, `"non-conformant"`, `"no-verdict"` — not an exit code. `no-verdict` must never be read as `conformant`.
92
+
93
+ The catalogue is a short-form companion to [`docs/CHECKS.md`](https://github.com/wasit-dev/wasit/blob/main/docs/CHECKS.md), which stays the source of truth for pass criteria and spec citations.
94
+
95
+ ### Errors
96
+
97
+ | Export | What it is |
98
+ |---|---|
99
+ | `ConfigurationError` | Something was wrong before any request went out — a malformed key, an invalid URL, an out-of-range argument |
100
+ | `TargetUnreachableError` | The request itself failed or timed out; no verdict about the target can be drawn from it |
101
+ | `MalformedResponseError` | The target answered, but not in a shape the check could read |
102
+ | `classifyCheckError(error)` | → `ClassifiedError` — maps an unknown throw to the `errorKind` (`"unreachable"`, `"configuration"`, `"harness"`) that appears in structured output |
103
+ | `assertHttpUrl(target)`, `fetchTarget(...)` | The URL guard and bounded fetch the checks themselves use |
104
+
105
+ ### Testnet wallet helpers
106
+
107
+ A convenience layer for setting up the keys the check functions read. It is not part of the check surface, and it is exported by name rather than with `export *` so `wallet.ts` stays free to change without that being a breaking change to this package.
108
+
109
+ | Export | Signature |
110
+ |---|---|
111
+ | `publicKeyFromSecret(secretKey, source?)` | → `string`. `source` names the offending variable in the error message |
112
+ | `getTestnetWalletStatus(publicKey)` | → `Promise<WalletStatus>` — `{ publicKey, exists, balances }`; `exists` is false for an account never created on-chain |
113
+ | `generateTestnetWallet()` | → `GeneratedWallet` — a fresh keypair, unfunded |
114
+ | `generateCommitmentKey()` | → `GeneratedCommitmentKey` — a raw ed25519 seed for `COMMITMENT_SECRET_HEX`, which has no on-chain account and is not an `S...` key |
115
+ | `fundWithFriendbot(publicKey, attempts?)` | → `Promise<FriendbotOutcome>` — `"funded"` or `"already-funded"`. Two different claims: an account that already exists is a success, but no transfer happened |
116
+ | `createUsdcTrustline(secretKey, source?)` | → `Promise<void>` — opens the Circle testnet USDC trustline. A trustline is not a balance |
117
+ | `sendUsdcFromDistributor(distributorSecretKey, destinationPublicKey, amount)` | → `Promise<void>` — `amount` is a positive decimal string, at most 7 places |
118
+ | `testnetUsdcAsset()` / `TESTNET_USDC_ISSUER` | The Circle testnet USDC `Asset` and its issuer address |
119
+ | `describeTransactionError(error)` | → `string` — Horizon result codes formatted for a human |
120
+
121
+ **These throw; the check functions do not.** Every function above raises `ConfigurationError` or `TargetUnreachableError` rather than leaking a Stellar SDK error, with Horizon's result codes (`op_underfunded`, `op_no_trust`) folded into the message — so a caller renders `error.message` and never inspects an SDK error type. Horizon and Friendbot requests are bounded by a 15s timeout. A rejected secret key is never echoed back in the message.
122
+
123
+ There is deliberately no network parameter anywhere in this layer. Friendbot, the printed USDC issuer, and the whole idea of a disposable generated key only make sense on testnet.
124
+
125
+
83
126
  ## Design
84
127
 
85
128
  - **`FAIL`, `ERROR`, and `SKIP` are different claims.** `FAIL` means the target answered and didn't conform. `ERROR` means no verdict was produced at all (unreachable, misconfigured, harness failure). `SKIP` is neither. Conflating "your service is broken" with "we never reached your service" would make a tool worse than no tool.
package/dist/check.d.ts CHANGED
@@ -75,7 +75,10 @@ export interface StructuredCheckResult {
75
75
  readonly status: CheckStatus;
76
76
  readonly detail: string;
77
77
  readonly destructive: boolean;
78
- /** Present only when `status` is "ERROR": unreachable | configuration | harness. */
78
+ /**
79
+ * Present only when `status` is "ERROR":
80
+ * unreachable | configuration | harness | setup.
81
+ */
79
82
  readonly errorKind?: string;
80
83
  }
81
84
  /** A full run, reshaped for a machine-readable front end (CLI --json, MCP). */
package/dist/errors.d.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  * the call site knows what it was doing and wraps accordingly.
15
15
  */
16
16
  /** Why a check could not produce a verdict about the target. */
17
- export type CheckErrorKind = "unreachable" | "configuration" | "harness";
17
+ export type CheckErrorKind = "unreachable" | "configuration" | "harness" | "setup";
18
18
  /** A check that did not run. Never a statement about the target's conformance. */
19
19
  export interface CheckError {
20
20
  readonly kind: CheckErrorKind;
@@ -39,6 +39,21 @@ export declare class MalformedResponseError extends Error {
39
39
  export declare class ConfigurationError extends Error {
40
40
  constructor(message: string);
41
41
  }
42
+ /**
43
+ * A precondition the check needed could not be established, so the check never
44
+ * reached the rule it exists to test.
45
+ *
46
+ * Kept apart from a conformance failure deliberately. MPP channel checks must
47
+ * first get one correctly advancing commitment accepted before they can probe
48
+ * anything, and two very different worlds refuse that submission identically: a
49
+ * target that wrongly rejects valid vouchers, and a channel whose cumulative
50
+ * moved between the challenge being issued and the credential being submitted,
51
+ * because something else is paying through it. Reporting the second as a defect
52
+ * tells an operator their service is broken on the evidence of a busy channel.
53
+ */
54
+ export declare class CheckSetupError extends Error {
55
+ constructor(message: string);
56
+ }
42
57
  /** No HTTP conversation took place: the connection never succeeded. */
43
58
  export declare class TargetUnreachableError extends Error {
44
59
  readonly target: string;
@@ -55,11 +70,6 @@ export declare class TargetUnreachableError extends Error {
55
70
  * under N identical copies.
56
71
  */
57
72
  export declare function assertHttpUrl(target: string): void;
58
- /**
59
- * Performs a request against the target, distinguishing "never connected"
60
- * from every other failure. Use this instead of bare `fetch` for anything
61
- * addressed at the service under test.
62
- */
63
73
  export declare function fetchTarget(target: string, init?: Parameters<typeof fetch>[1]): Promise<Awaited<ReturnType<typeof fetch>>>;
64
74
  /** Maps a thrown value onto the taxonomy. */
65
75
  export declare function classifyCheckError(error: unknown): ClassifiedError;
package/dist/errors.js CHANGED
@@ -30,6 +30,24 @@ export class ConfigurationError extends Error {
30
30
  this.name = "ConfigurationError";
31
31
  }
32
32
  }
33
+ /**
34
+ * A precondition the check needed could not be established, so the check never
35
+ * reached the rule it exists to test.
36
+ *
37
+ * Kept apart from a conformance failure deliberately. MPP channel checks must
38
+ * first get one correctly advancing commitment accepted before they can probe
39
+ * anything, and two very different worlds refuse that submission identically: a
40
+ * target that wrongly rejects valid vouchers, and a channel whose cumulative
41
+ * moved between the challenge being issued and the credential being submitted,
42
+ * because something else is paying through it. Reporting the second as a defect
43
+ * tells an operator their service is broken on the evidence of a busy channel.
44
+ */
45
+ export class CheckSetupError extends Error {
46
+ constructor(message) {
47
+ super(message);
48
+ this.name = "CheckSetupError";
49
+ }
50
+ }
33
51
  /** No HTTP conversation took place: the connection never succeeded. */
34
52
  export class TargetUnreachableError extends Error {
35
53
  target;
@@ -96,10 +114,36 @@ export function assertHttpUrl(target) {
96
114
  * from every other failure. Use this instead of bare `fetch` for anything
97
115
  * addressed at the service under test.
98
116
  */
117
+ /**
118
+ * The global symbol mppx tags its fetch wrappers with, so a wrapper can be
119
+ * recognised across module instances and bundles.
120
+ * See mppx/dist/client/internal/Fetch.js.
121
+ */
122
+ const MPPX_FETCH_WRAPPER = Symbol.for("mppx.fetch.wrapper");
123
+ /**
124
+ * Resolves the underlying fetch, stepping past any mppx payment wrapper
125
+ * installed on `globalThis`.
126
+ *
127
+ * `Mppx.create` replaces `globalThis.fetch` with a wrapper bound to one
128
+ * payment method unless `polyfill: false` is passed. A charge-mode client
129
+ * created earlier in the process therefore makes every later 402 carrying a
130
+ * different intent fail with "No method found for challenges", even though the
131
+ * target is conformant. Checks must observe the target, never a payment client
132
+ * some other check left behind, so this unwraps rather than trusting the global.
133
+ */
134
+ function baseFetch() {
135
+ let current = globalThis.fetch;
136
+ const seen = new Set();
137
+ while (current[MPPX_FETCH_WRAPPER] && !seen.has(current)) {
138
+ seen.add(current);
139
+ current = current[MPPX_FETCH_WRAPPER];
140
+ }
141
+ return current;
142
+ }
99
143
  export async function fetchTarget(target, init) {
100
144
  assertHttpUrl(target);
101
145
  try {
102
- return await fetch(target, init);
146
+ return await baseFetch()(target, init);
103
147
  }
104
148
  catch (error) {
105
149
  throw new TargetUnreachableError(target, error);
@@ -120,6 +164,9 @@ export function classifyCheckError(error) {
120
164
  if (error instanceof ConfigurationError) {
121
165
  return { kind: "configuration", message: error.message };
122
166
  }
167
+ if (error instanceof CheckSetupError) {
168
+ return { kind: "setup", message: error.message };
169
+ }
123
170
  return {
124
171
  kind: "harness",
125
172
  message: error instanceof Error ? error.message : String(error),
package/dist/index.d.ts CHANGED
@@ -8,3 +8,5 @@ export * from "./mpp/channel.js";
8
8
  export * from "./mpp/charge.js";
9
9
  export * from "./mpp/charge-suite.js";
10
10
  export * from "./mpp/suite.js";
11
+ export { createUsdcTrustline, describeTransactionError, fundWithFriendbot, generateCommitmentKey, generateTestnetWallet, getTestnetWalletStatus, publicKeyFromSecret, sendUsdcFromDistributor, testnetUsdcAsset, TESTNET_USDC_ISSUER, } from "./wallet.js";
12
+ export type { AssetBalance, FriendbotOutcome, GeneratedCommitmentKey, GeneratedWallet, WalletStatus, } from "./wallet.js";
package/dist/index.js CHANGED
@@ -6,3 +6,8 @@ export * from "./mpp/channel.js";
6
6
  export * from "./mpp/charge.js";
7
7
  export * from "./mpp/charge-suite.js";
8
8
  export * from "./mpp/suite.js";
9
+ // Wallet tooling is exported by name rather than with `export *`: it is a
10
+ // convenience layer for setting up testnet keys, not part of the check
11
+ // surface, and naming each entry keeps the rest of wallet.ts free to change
12
+ // without that being a breaking change to @wasit-dev/core.
13
+ export { createUsdcTrustline, describeTransactionError, fundWithFriendbot, generateCommitmentKey, generateTestnetWallet, getTestnetWalletStatus, publicKeyFromSecret, sendUsdcFromDistributor, testnetUsdcAsset, TESTNET_USDC_ISSUER, } from "./wallet.js";
@@ -11,6 +11,7 @@
11
11
  * with the raw ed25519 commitment key. No transaction is submitted, no fee paid.
12
12
  */
13
13
  import { Keypair } from "@stellar/stellar-sdk";
14
+ export declare const COMMITMENT_SEED_BYTES = 32;
14
15
  export declare class CommitmentSimulationError extends Error {
15
16
  readonly cause?: unknown;
16
17
  constructor(message: string, cause?: unknown);
@@ -20,7 +20,9 @@ const SIMULATION_SOURCE_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
20
20
  /** Base fee in stroops. Never charged — the transaction is only simulated. */
21
21
  const SIMULATION_FEE = "100";
22
22
  const DEFAULT_SIMULATION_TIMEOUT_MS = 10_000;
23
- const COMMITMENT_SEED_BYTES = 32;
23
+ // Exported so wallet.ts can generate a correctly-sized seed without
24
+ // restating this number and risking it drifting out of sync.
25
+ export const COMMITMENT_SEED_BYTES = 32;
24
26
  const ED25519_SIGNATURE_BYTES = 64;
25
27
  export class CommitmentSimulationError extends Error {
26
28
  cause;
@@ -38,6 +38,16 @@ export interface ChannelChallenge {
38
38
  * rule a check is trying to exercise.
39
39
  */
40
40
  export declare function fetchChannelChallenge(target: string): Promise<ChannelChallenge>;
41
+ /**
42
+ * Reads the channel-specific fields out of an already-decoded challenge.
43
+ *
44
+ * Separated from the request that produced it so these rules can be exercised
45
+ * directly, including against the malformed challenges a conforming service
46
+ * will not produce on demand. Everything it throws is a
47
+ * {@link ChannelChallengeError}, so a bad challenge is reported as a verdict
48
+ * about the target rather than as a harness failure.
49
+ */
50
+ export declare function parseChannelChallenge(challenge: Challenge.Challenge): ChannelChallenge;
41
51
  /**
42
52
  * Serialises an already-signed commitment into an Authorization header value.
43
53
  *
@@ -48,6 +48,18 @@ export async function fetchChannelChallenge(target) {
48
48
  throw new ChannelChallengeError(`Challenge could not be parsed from the WWW-Authenticate header: ` +
49
49
  `${error.message}`);
50
50
  }
51
+ return parseChannelChallenge(challenge);
52
+ }
53
+ /**
54
+ * Reads the channel-specific fields out of an already-decoded challenge.
55
+ *
56
+ * Separated from the request that produced it so these rules can be exercised
57
+ * directly, including against the malformed challenges a conforming service
58
+ * will not produce on demand. Everything it throws is a
59
+ * {@link ChannelChallengeError}, so a bad challenge is reported as a verdict
60
+ * about the target rather than as a harness failure.
61
+ */
62
+ export function parseChannelChallenge(challenge) {
51
63
  const request = asRecord(challenge.request);
52
64
  if (!request) {
53
65
  throw new ChannelChallengeError("Challenge carries no request object.");
@@ -1,6 +1,7 @@
1
1
  import { getChannelState } from "@stellar/mpp/channel/server";
2
2
  import { errored, skippedDestructive } from "../check.js";
3
- import { readChannelWithdrawn, signChannelCommitment } from "./channel-commitment.js";
3
+ import { CheckSetupError } from "../errors.js";
4
+ import { readChannelWithdrawn } from "./channel-commitment.js";
4
5
  import { buildChannelCredential, fetchChannelChallenge, serializeChannelCredential, submitCredential, } from "./channel-credential.js";
5
6
  import { assertMppNetwork, networkPassphrase, resolveRpcUrl } from "./network.js";
6
7
  /**
@@ -48,6 +49,55 @@ export async function runMppChannelDeployChecks(options) {
48
49
  function failure(id, name, detail) {
49
50
  return [{ id, name, pass: false, detail }];
50
51
  }
52
+ /**
53
+ * Attempts allowed when establishing the accepted commitment a check needs.
54
+ *
55
+ * One attempt is what turned a busy channel into a reported defect. Many
56
+ * attempts would hide a target that always refuses valid vouchers. Three is
57
+ * enough that ordinary contention clears, because every attempt re-reads the
58
+ * cumulative from a freshly issued challenge, while a real refusal reproduces
59
+ * on all of them.
60
+ */
61
+ const SETUP_ATTEMPTS = 3;
62
+ /**
63
+ * Advances the channel's cumulative by exactly one request price.
64
+ *
65
+ * Every ordering and replay check needs this first: a commitment the target has
66
+ * just accepted, so the probe that follows differs from it in exactly the one
67
+ * respect the check is about. Reading the cumulative from a freshly issued
68
+ * challenge on every attempt is what makes these checks re-runnable against a
69
+ * channel with any prior history, and what lets a retry recover when another
70
+ * payer advanced the cumulative mid-run.
71
+ *
72
+ * @throws {CheckSetupError} No attempt was accepted, so the check has no verdict.
73
+ */
74
+ async function advanceCumulative(options) {
75
+ const { target, commitmentSecretHex, network, rpcUrl } = options;
76
+ const refusals = [];
77
+ for (let attempt = 1; attempt <= SETUP_ATTEMPTS; attempt += 1) {
78
+ const challenge = await fetchChannelChallenge(target);
79
+ const amount = challenge.cumulativeAmount + challenge.requestedAmount;
80
+ const { credential, signature } = await buildChannelCredential({
81
+ challenge,
82
+ amount,
83
+ commitmentSecretHex,
84
+ network,
85
+ rpcUrl,
86
+ });
87
+ const submission = await submitCredential(target, credential);
88
+ if (submission.status === 200)
89
+ return { amount, credential, signature };
90
+ refusals.push(`attempt ${attempt}: ${amount} refused with HTTP ${submission.status}: ` +
91
+ `${submission.body}`);
92
+ }
93
+ throw new CheckSetupError(`A correctly advancing commitment was refused ${SETUP_ATTEMPTS} times, each ` +
94
+ `one signed against a freshly issued challenge, so this check never ` +
95
+ `reached the rule it tests (${refusals.join("; ")}). Either the target ` +
96
+ `refuses valid vouchers, which is a defect in its own right, or the ` +
97
+ `channel's cumulative is being advanced by something else while this run ` +
98
+ `is in progress. Re-run against a channel nothing else is paying through ` +
99
+ `to tell the two apart.`);
100
+ }
51
101
  /**
52
102
  * MPP-11: A commitment that does not advance the cumulative must be rejected.
53
103
  *
@@ -66,20 +116,7 @@ export async function runMppChannelOrderingCheck(options) {
66
116
  const name = "Cumulative Commitment Ordering";
67
117
  const { target, commitmentSecretHex, network, rpcUrl } = options;
68
118
  try {
69
- const opening = await fetchChannelChallenge(target);
70
- const baseline = opening.cumulativeAmount + opening.requestedAmount;
71
- const { credential } = await buildChannelCredential({
72
- challenge: opening,
73
- amount: baseline,
74
- commitmentSecretHex,
75
- network,
76
- rpcUrl,
77
- });
78
- const accepted = await submitCredential(target, credential);
79
- if (accepted.status !== 200) {
80
- return failure(id, name, `Setup failed: a correctly advancing commitment (${baseline}) was not accepted — ` +
81
- `HTTP ${accepted.status}: ${accepted.body}`);
82
- }
119
+ const { amount: baseline } = await advanceCumulative(options);
83
120
  // (a) Exactly equal to the cumulative the server now holds.
84
121
  const equalChallenge = await fetchChannelChallenge(target);
85
122
  const equal = await submitCredential(target, (await buildChannelCredential({
@@ -147,22 +184,9 @@ export async function runMppChannelOrderingCheck(options) {
147
184
  export async function runMppChannelReplayCheck(options) {
148
185
  const id = "MPP-12";
149
186
  const name = "Challenge Replay Rejection";
150
- const { target, commitmentSecretHex, network, rpcUrl } = options;
187
+ const { target } = options;
151
188
  try {
152
- const opening = await fetchChannelChallenge(target);
153
- const amount = opening.cumulativeAmount + opening.requestedAmount;
154
- const { credential } = await buildChannelCredential({
155
- challenge: opening,
156
- amount,
157
- commitmentSecretHex,
158
- network,
159
- rpcUrl,
160
- });
161
- const first = await submitCredential(target, credential);
162
- if (first.status !== 200) {
163
- return failure(id, name, `Setup failed: a valid commitment (${amount}) was not accepted — ` +
164
- `HTTP ${first.status}: ${first.body}`);
165
- }
189
+ const { credential } = await advanceCumulative(options);
166
190
  const replay = await submitCredential(target, credential);
167
191
  if (replay.status !== 402) {
168
192
  return failure(id, name, `An identical credential was accepted twice — expected HTTP 402 on replay, ` +
@@ -194,22 +218,9 @@ export async function runMppChannelReplayCheck(options) {
194
218
  export async function runMppChannelCommitmentReplayCheck(options) {
195
219
  const id = "MPP-14";
196
220
  const name = "Commitment Replay Rejection";
197
- const { target, commitmentSecretHex, network, rpcUrl } = options;
221
+ const { target } = options;
198
222
  try {
199
- const opening = await fetchChannelChallenge(target);
200
- const amount = opening.cumulativeAmount + opening.requestedAmount;
201
- const signature = await signChannelCommitment({
202
- channelContract: opening.channelContract,
203
- amount,
204
- commitmentSecretHex,
205
- networkPassphrase: networkPassphrase(network),
206
- rpcUrl: resolveRpcUrl(network, rpcUrl),
207
- });
208
- const first = await submitCredential(target, serializeChannelCredential({ challenge: opening, amount, signature }));
209
- if (first.status !== 200) {
210
- return failure(id, name, `Setup failed: a valid commitment (${amount}) was not accepted — ` +
211
- `HTTP ${first.status}: ${first.body}`);
212
- }
223
+ const { amount, signature } = await advanceCumulative(options);
213
224
  // Fresh challenge, same commitment. The signature is still cryptographically
214
225
  // valid; only the cumulative rule can reject it.
215
226
  const fresh = await fetchChannelChallenge(target);
@@ -8,5 +8,15 @@
8
8
  */
9
9
  import { type CheckResult } from "../check.js";
10
10
  import { type MppChargeCheckOptions } from "./charge.js";
11
- export type MppChargeSuiteOptions = MppChargeCheckOptions;
11
+ export interface MppChargeSuiteOptions extends MppChargeCheckOptions {
12
+ /**
13
+ * Called once per check as soon as its result is known, in addition to it
14
+ * being included in the returned array — lets a caller render progress
15
+ * live instead of waiting for the whole suite to finish. Optional and has
16
+ * no effect on what is returned. MPP-01 is a single check, so this fires
17
+ * exactly once, but the contract matches the other suites so a caller can
18
+ * treat all of them the same way.
19
+ */
20
+ readonly onResult?: (result: CheckResult) => void;
21
+ }
12
22
  export declare function runMppChargeSuite(options: MppChargeSuiteOptions): Promise<CheckResult[]>;
@@ -9,10 +9,14 @@
9
9
  import { errored } from "../check.js";
10
10
  import { runMppChargeChecks } from "./charge.js";
11
11
  export async function runMppChargeSuite(options) {
12
+ let results;
12
13
  try {
13
- return await runMppChargeChecks(options);
14
+ results = await runMppChargeChecks(options);
14
15
  }
15
16
  catch (error) {
16
- return [errored("MPP-01", "Charge Settlement On-Chain", error)];
17
+ results = [errored("MPP-01", "Charge Settlement On-Chain", error)];
17
18
  }
19
+ for (const result of results)
20
+ options.onResult?.(result);
21
+ return results;
18
22
  }
@@ -14,6 +14,7 @@
14
14
  * @stellar/mpp's own client guards against when it refuses to sign a
15
15
  * non-transfer authorization.
16
16
  */
17
+ import { Challenge } from "mppx";
17
18
  import { type CheckResult } from "../check.js";
18
19
  export interface MppChargeCheckOptions {
19
20
  readonly target: string;
@@ -21,6 +22,22 @@ export interface MppChargeCheckOptions {
21
22
  readonly payerSecretKey: string;
22
23
  readonly rpcUrl?: string;
23
24
  }
25
+ /** What the target advertised it wants paid, read from its own 402 challenge. */
26
+ export interface ChargeChallenge {
27
+ readonly amount: bigint;
28
+ readonly currency: string;
29
+ readonly recipient: string;
30
+ }
31
+ /**
32
+ * Reads the advertised charge terms out of an already-decoded challenge.
33
+ *
34
+ * Separated from the request that produced it so these rules can be exercised
35
+ * directly, including against the malformed challenges a conforming service
36
+ * will not produce on demand. Everything it throws is a
37
+ * {@link MalformedResponseError}, so a bad challenge is reported as a verdict
38
+ * about the target rather than as a harness failure.
39
+ */
40
+ export declare function parseChargeChallenge(challenge: Challenge.Challenge): ChargeChallenge;
24
41
  /**
25
42
  * MPP-01: the charge must settle on-chain for exactly the advertised amount.
26
43
  *
@@ -55,6 +55,18 @@ async function fetchChargeChallenge(target) {
55
55
  throw new MalformedResponseError(`Challenge could not be parsed from the WWW-Authenticate header: ` +
56
56
  `${error.message}`);
57
57
  }
58
+ return parseChargeChallenge(challenge);
59
+ }
60
+ /**
61
+ * Reads the advertised charge terms out of an already-decoded challenge.
62
+ *
63
+ * Separated from the request that produced it so these rules can be exercised
64
+ * directly, including against the malformed challenges a conforming service
65
+ * will not produce on demand. Everything it throws is a
66
+ * {@link MalformedResponseError}, so a bad challenge is reported as a verdict
67
+ * about the target rather than as a harness failure.
68
+ */
69
+ export function parseChargeChallenge(challenge) {
58
70
  const request = asRecord(challenge.request);
59
71
  if (!request) {
60
72
  throw new MalformedResponseError("Challenge carries no request object.");
@@ -154,7 +166,7 @@ export async function runMppChargeChecks(options) {
154
166
  // after settlement would leave money moved and no verdict to show for it.
155
167
  const endpoint = resolveRpcUrl(network, rpcUrl);
156
168
  const advertised = await fetchChargeChallenge(target);
157
- const mppx = Mppx.create({ methods: [charge({ secretKey: payerSecretKey })] });
169
+ const mppx = Mppx.create({ methods: [charge({ secretKey: payerSecretKey })], polyfill: false });
158
170
  let paid;
159
171
  try {
160
172
  paid = await mppx.fetch(target);
@@ -27,6 +27,13 @@ export interface MppChannelSuiteOptions {
27
27
  readonly expected?: Partial<ChannelDeployExpectations>;
28
28
  readonly allowDestructive?: boolean;
29
29
  readonly destructiveChannel?: string;
30
+ /**
31
+ * Called once per check as soon as its result is known, in addition to it
32
+ * being included in the returned array — lets a caller render progress
33
+ * live instead of waiting for the whole suite to finish. Optional and has
34
+ * no effect on what is returned.
35
+ */
36
+ readonly onResult?: (result: CheckResult) => void;
30
37
  }
31
38
  /**
32
39
  * Runs MPP-10 through MPP-14 against a target.
package/dist/mpp/suite.js CHANGED
@@ -90,7 +90,9 @@ export async function runMppChannelSuite(options) {
90
90
  assertMppNetwork(network);
91
91
  }
92
92
  catch (error) {
93
- return [errored("PREFLIGHT", "Run Preflight", error)];
93
+ const preflight = errored("PREFLIGHT", "Run Preflight", error);
94
+ options.onResult?.(preflight);
95
+ return [preflight];
94
96
  }
95
97
  const shared = {
96
98
  target,
@@ -109,22 +111,29 @@ export async function runMppChannelSuite(options) {
109
111
  advertisedFailure = classifyCheckError(error).message;
110
112
  }
111
113
  const results = [];
112
- results.push(...(await runDeployCheck({
114
+ // Pushes a batch into the run's results and reports each one to the
115
+ // caller's live-progress hook, if any, in the same order.
116
+ const record = (batch) => {
117
+ results.push(...batch);
118
+ for (const result of batch)
119
+ options.onResult?.(result);
120
+ };
121
+ record(await runDeployCheck({
113
122
  network,
114
123
  ...(rpcUrl ? { rpcUrl } : {}),
115
124
  ...(advertised ? { advertised } : {}),
116
125
  ...(advertisedFailure ? { advertisedFailure } : {}),
117
126
  ...(channelOverride ? { channelOverride } : {}),
118
127
  ...(expected ? { expected } : {}),
119
- })));
120
- results.push(...(await runMppChannelOrderingCheck(shared)));
121
- results.push(...(await runMppChannelReplayCheck(shared)));
122
- results.push(...(await runMppChannelCommitmentReplayCheck(shared)));
128
+ }));
129
+ record(await runMppChannelOrderingCheck(shared));
130
+ record(await runMppChannelReplayCheck(shared));
131
+ record(await runMppChannelCommitmentReplayCheck(shared));
123
132
  // Last: a close is terminal, so nothing may run against the channel after it.
124
- results.push(...(await runMppChannelCloseCheck({
133
+ record(await runMppChannelCloseCheck({
125
134
  ...shared,
126
135
  allowDestructive,
127
136
  ...(destructiveChannel ? { expectedChannel: destructiveChannel } : {}),
128
- })));
137
+ }));
129
138
  return results;
130
139
  }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Testnet wallet helpers: generate a keypair, fund it with XLM via Friendbot,
3
+ * establish a USDC trustline, and read balances back. Every function here is
4
+ * scoped to Stellar testnet on purpose — Friendbot, the USDC issuer address
5
+ * below, and the whole idea of a disposable throwaway wallet only make sense
6
+ * there. None of this accepts a network parameter; there is nothing here
7
+ * that could be pointed at pubnet by mistake.
8
+ *
9
+ * USDC funding is split into two steps because only one half can actually be
10
+ * automated: a trustline is just a local signature away, but there is no
11
+ * scriptable, unauthenticated faucet for testnet USDC. Circle's own faucet
12
+ * (faucet.circle.com) is a captcha-gated web form with no public API for
13
+ * Stellar. `sendUsdcFromDistributor` covers the case where the operator has
14
+ * already completed that manual step once, on an account of their own.
15
+ *
16
+ * **Error contract.** Every exported function that can fail throws one of
17
+ * `errors.ts`'s types and never a raw Stellar SDK error: a bad key or a
18
+ * rejected transaction is a `ConfigurationError`, an unreachable Horizon or
19
+ * Friendbot is a `TargetUnreachableError`. Callers render `error.message`
20
+ * directly and never need to know which SDK produced it, which is what keeps
21
+ * the CLI and the dashboard from drifting apart in how they report the same
22
+ * failure. `describeTransactionError` is the internal formatter that puts
23
+ * Horizon's result codes into those messages; it stays exported only because
24
+ * the CLI's own `--json` surface reuses it for non-wallet errors.
25
+ */
26
+ import { Asset } from "@stellar/stellar-sdk";
27
+ export declare const TESTNET_HORIZON_URL = "https://horizon-testnet.stellar.org";
28
+ /** Circle's official USDC issuer on Stellar testnet — not a pubnet address. */
29
+ export declare const TESTNET_USDC_ISSUER = "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5";
30
+ /** The testnet USDC asset, ready to use in a changeTrust or payment operation. */
31
+ export declare function testnetUsdcAsset(): Asset;
32
+ export interface GeneratedWallet {
33
+ readonly publicKey: string;
34
+ readonly secretKey: string;
35
+ }
36
+ /** A fresh testnet Stellar keypair. Never touches the network. */
37
+ export declare function generateTestnetWallet(): GeneratedWallet;
38
+ /**
39
+ * Derives the public key for a secret key, without doing anything else with it.
40
+ *
41
+ * A malformed key is the single most likely thing to be wrong in someone's
42
+ * `.env` — a truncated paste, a `G...` public key in a secret's slot, or a
43
+ * raw hex commitment seed where a Stellar `S...` string belongs. The SDK
44
+ * reports all three as `invalid encoded string`, which names neither the
45
+ * problem nor where to fix it, so it is translated here into a
46
+ * `ConfigurationError` that says which variable to look at.
47
+ *
48
+ * `source` is that variable's name (e.g. "MPP_PAYER_SECRET"). The secret
49
+ * itself is never included in the message: this string reaches logs, saved
50
+ * JSON runs and terminal recordings.
51
+ */
52
+ export declare function publicKeyFromSecret(secretKey: string, source?: string): string;
53
+ export interface GeneratedCommitmentKey {
54
+ readonly secretHex: string;
55
+ readonly publicKeyHex: string;
56
+ }
57
+ /**
58
+ * A fresh MPP channel commitment key — a raw ed25519 seed, not a funded
59
+ * Stellar account. It only ever signs commitment bytes off-chain (see
60
+ * `commitmentKeypairFromHex` in mpp/channel-commitment.ts), so unlike the
61
+ * wallets above it never needs XLM or a balance of its own.
62
+ */
63
+ export declare function generateCommitmentKey(): GeneratedCommitmentKey;
64
+ export interface AssetBalance {
65
+ /** "XLM" for the native asset, otherwise the asset code (e.g. "USDC"). */
66
+ readonly code: string;
67
+ readonly issuer?: string;
68
+ /** Decimal string straight from Horizon — never parsed to a float here. */
69
+ readonly balance: string;
70
+ }
71
+ export interface WalletStatus {
72
+ readonly publicKey: string;
73
+ /** False when the account has never been created on-chain. */
74
+ readonly exists: boolean;
75
+ readonly balances: readonly AssetBalance[];
76
+ }
77
+ /**
78
+ * Formats a TransactionFailedError with the actual Horizon result codes
79
+ * (e.g. "op_underfunded") instead of just its generic top-level message,
80
+ * which by itself is rarely enough to tell a user what to fix.
81
+ */
82
+ export declare function describeTransactionError(error: unknown): string;
83
+ /**
84
+ * Reads an account's balances from testnet Horizon.
85
+ *
86
+ * An account that has never been funded is not an error — it's the expected
87
+ * starting state for a freshly generated wallet — so it comes back as
88
+ * `{ exists: false, balances: [] }` rather than a thrown NotFoundError.
89
+ */
90
+ export declare function getTestnetWalletStatus(publicKey: string): Promise<WalletStatus>;
91
+ /**
92
+ * What `fundWithFriendbot` actually did.
93
+ *
94
+ * Both outcomes mean the caller got what it asked for — a funded account —
95
+ * but only one of them moved any XLM, and a UI that reports "Funded: 10,000
96
+ * XLM" for an account that already had a balance is simply telling the user
97
+ * something untrue.
98
+ */
99
+ export type FriendbotOutcome = "funded" | "already-funded";
100
+ /**
101
+ * Funds a testnet account via Friendbot (10,000 XLM per request). Friendbot
102
+ * is a shared public resource with no documented uptime guarantee, so
103
+ * transient failures are retried with a short backoff before giving up, and
104
+ * every attempt is bounded by its own timeout. A 400 reporting the account
105
+ * already exists is not a failure — the thing the caller actually wanted is
106
+ * already true — and comes back as `"already-funded"` so the caller can say
107
+ * so rather than claiming a transfer that never happened.
108
+ */
109
+ export declare function fundWithFriendbot(publicKey: string, attempts?: number): Promise<FriendbotOutcome>;
110
+ /**
111
+ * Establishes a trustline from `secretKey`'s own account to testnet USDC.
112
+ *
113
+ * This only opens the door — it does not put anything in it. The account
114
+ * needs a small amount of existing XLM first (the transaction fee, plus the
115
+ * reserve a trustline adds); callers should ensure that before calling this.
116
+ */
117
+ export declare function createUsdcTrustline(secretKey: string, source?: string): Promise<void>;
118
+ /**
119
+ * Sends testnet USDC from an already-funded distributor account to
120
+ * `destinationPublicKey`. There is no way to acquire the first unit of
121
+ * testnet USDC without a human completing Circle's faucet form
122
+ * (faucet.circle.com) once — this only helps once that has happened for the
123
+ * distributor account. The destination must already hold a USDC trustline;
124
+ * Stellar rejects a payment in an asset the receiver has not opted into.
125
+ */
126
+ export declare function sendUsdcFromDistributor(distributorSecretKey: string, destinationPublicKey: string, amount: string): Promise<void>;
package/dist/wallet.js ADDED
@@ -0,0 +1,255 @@
1
+ /**
2
+ * Testnet wallet helpers: generate a keypair, fund it with XLM via Friendbot,
3
+ * establish a USDC trustline, and read balances back. Every function here is
4
+ * scoped to Stellar testnet on purpose — Friendbot, the USDC issuer address
5
+ * below, and the whole idea of a disposable throwaway wallet only make sense
6
+ * there. None of this accepts a network parameter; there is nothing here
7
+ * that could be pointed at pubnet by mistake.
8
+ *
9
+ * USDC funding is split into two steps because only one half can actually be
10
+ * automated: a trustline is just a local signature away, but there is no
11
+ * scriptable, unauthenticated faucet for testnet USDC. Circle's own faucet
12
+ * (faucet.circle.com) is a captcha-gated web form with no public API for
13
+ * Stellar. `sendUsdcFromDistributor` covers the case where the operator has
14
+ * already completed that manual step once, on an account of their own.
15
+ *
16
+ * **Error contract.** Every exported function that can fail throws one of
17
+ * `errors.ts`'s types and never a raw Stellar SDK error: a bad key or a
18
+ * rejected transaction is a `ConfigurationError`, an unreachable Horizon or
19
+ * Friendbot is a `TargetUnreachableError`. Callers render `error.message`
20
+ * directly and never need to know which SDK produced it, which is what keeps
21
+ * the CLI and the dashboard from drifting apart in how they report the same
22
+ * failure. `describeTransactionError` is the internal formatter that puts
23
+ * Horizon's result codes into those messages; it stays exported only because
24
+ * the CLI's own `--json` surface reuses it for non-wallet errors.
25
+ */
26
+ import { randomBytes } from "node:crypto";
27
+ import { Asset, BASE_FEE, Horizon, Keypair, Networks, NotFoundError, Operation, TransactionBuilder, TransactionFailedError, } from "@stellar/stellar-sdk";
28
+ import { COMMITMENT_SEED_BYTES } from "./mpp/channel-commitment.js";
29
+ import { ConfigurationError, TargetUnreachableError } from "./errors.js";
30
+ export const TESTNET_HORIZON_URL = "https://horizon-testnet.stellar.org";
31
+ const FRIENDBOT_URL = "https://friendbot.stellar.org";
32
+ /**
33
+ * Ceiling on any single Horizon or Friendbot request. Both are shared public
34
+ * services with no uptime guarantee: without this a stalled connection hangs
35
+ * the CLI (or pins the dashboard on its spinner) with no way back, since a
36
+ * retry loop cannot help a request that never returns at all.
37
+ */
38
+ const NETWORK_TIMEOUT_MS = 15_000;
39
+ /** Circle's official USDC issuer on Stellar testnet — not a pubnet address. */
40
+ export const TESTNET_USDC_ISSUER = "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5";
41
+ /** The testnet USDC asset, ready to use in a changeTrust or payment operation. */
42
+ export function testnetUsdcAsset() {
43
+ return new Asset("USDC", TESTNET_USDC_ISSUER);
44
+ }
45
+ /** A fresh testnet Stellar keypair. Never touches the network. */
46
+ export function generateTestnetWallet() {
47
+ const keypair = Keypair.random();
48
+ return { publicKey: keypair.publicKey(), secretKey: keypair.secret() };
49
+ }
50
+ /**
51
+ * Derives the public key for a secret key, without doing anything else with it.
52
+ *
53
+ * A malformed key is the single most likely thing to be wrong in someone's
54
+ * `.env` — a truncated paste, a `G...` public key in a secret's slot, or a
55
+ * raw hex commitment seed where a Stellar `S...` string belongs. The SDK
56
+ * reports all three as `invalid encoded string`, which names neither the
57
+ * problem nor where to fix it, so it is translated here into a
58
+ * `ConfigurationError` that says which variable to look at.
59
+ *
60
+ * `source` is that variable's name (e.g. "MPP_PAYER_SECRET"). The secret
61
+ * itself is never included in the message: this string reaches logs, saved
62
+ * JSON runs and terminal recordings.
63
+ */
64
+ export function publicKeyFromSecret(secretKey, source) {
65
+ try {
66
+ return Keypair.fromSecret(secretKey).publicKey();
67
+ }
68
+ catch {
69
+ const where = source === undefined ? "The secret key provided" : source;
70
+ throw new ConfigurationError(`${where} is not a valid Stellar secret key. It must be a 56-character ` +
71
+ `string starting with "S" — not a "G..." public key, and not a raw hex ` +
72
+ `seed (COMMITMENT_SECRET_HEX is hex and belongs to a different role; ` +
73
+ `see docs/guides/configuration.md).`);
74
+ }
75
+ }
76
+ /**
77
+ * A fresh MPP channel commitment key — a raw ed25519 seed, not a funded
78
+ * Stellar account. It only ever signs commitment bytes off-chain (see
79
+ * `commitmentKeypairFromHex` in mpp/channel-commitment.ts), so unlike the
80
+ * wallets above it never needs XLM or a balance of its own.
81
+ */
82
+ export function generateCommitmentKey() {
83
+ const seed = randomBytes(COMMITMENT_SEED_BYTES);
84
+ const keypair = Keypair.fromRawEd25519Seed(seed);
85
+ return {
86
+ secretHex: seed.toString("hex"),
87
+ publicKeyHex: keypair.rawPublicKey().toString("hex"),
88
+ };
89
+ }
90
+ function horizonServer() {
91
+ return new Horizon.Server(TESTNET_HORIZON_URL);
92
+ }
93
+ /**
94
+ * Formats a TransactionFailedError with the actual Horizon result codes
95
+ * (e.g. "op_underfunded") instead of just its generic top-level message,
96
+ * which by itself is rarely enough to tell a user what to fix.
97
+ */
98
+ export function describeTransactionError(error) {
99
+ if (error instanceof TransactionFailedError) {
100
+ const codes = error.getResultCodes();
101
+ const detail = [codes.transaction, ...codes.operations].filter(Boolean).join(", ");
102
+ return detail ? `${error.message} (${detail})` : error.message;
103
+ }
104
+ return error instanceof Error ? error.message : String(error);
105
+ }
106
+ /**
107
+ * Maps a thrown Horizon failure onto the taxonomy in errors.ts.
108
+ *
109
+ * The split that matters: a transaction Horizon *rejected* is a statement
110
+ * about this run's own configuration or funding (`op_underfunded`,
111
+ * `op_no_trust`) and is actionable, while a transaction that never reached
112
+ * Horizon at all says nothing about the account and belongs with every other
113
+ * connectivity failure. Anything already classified is passed through
114
+ * untouched so a wrapped error is never wrapped twice.
115
+ */
116
+ function asWalletError(error, action) {
117
+ if (error instanceof ConfigurationError || error instanceof TargetUnreachableError) {
118
+ return error;
119
+ }
120
+ if (error instanceof TransactionFailedError) {
121
+ return new ConfigurationError(`Could not ${action}: ${describeTransactionError(error)}`);
122
+ }
123
+ if (error instanceof NotFoundError) {
124
+ return new ConfigurationError(`Could not ${action}: the account does not exist on testnet yet. ` +
125
+ `Fund it first with \`wasit wallet fund\`.`);
126
+ }
127
+ return new TargetUnreachableError(TESTNET_HORIZON_URL, error);
128
+ }
129
+ /**
130
+ * Reads an account's balances from testnet Horizon.
131
+ *
132
+ * An account that has never been funded is not an error — it's the expected
133
+ * starting state for a freshly generated wallet — so it comes back as
134
+ * `{ exists: false, balances: [] }` rather than a thrown NotFoundError.
135
+ */
136
+ export async function getTestnetWalletStatus(publicKey) {
137
+ const server = horizonServer();
138
+ try {
139
+ const account = await server.loadAccount(publicKey);
140
+ const balances = account.balances.map((entry) => {
141
+ if (entry.asset_type === "native") {
142
+ return { code: "XLM", balance: entry.balance };
143
+ }
144
+ if (entry.asset_type === "liquidity_pool_shares") {
145
+ return { code: "LP_SHARE", balance: entry.balance };
146
+ }
147
+ return { code: entry.asset_code, issuer: entry.asset_issuer, balance: entry.balance };
148
+ });
149
+ return { publicKey, exists: true, balances };
150
+ }
151
+ catch (error) {
152
+ if (error instanceof NotFoundError) {
153
+ return { publicKey, exists: false, balances: [] };
154
+ }
155
+ throw new TargetUnreachableError(TESTNET_HORIZON_URL, error);
156
+ }
157
+ }
158
+ function sleep(ms) {
159
+ return new Promise((resolve) => setTimeout(resolve, ms));
160
+ }
161
+ /**
162
+ * Funds a testnet account via Friendbot (10,000 XLM per request). Friendbot
163
+ * is a shared public resource with no documented uptime guarantee, so
164
+ * transient failures are retried with a short backoff before giving up, and
165
+ * every attempt is bounded by its own timeout. A 400 reporting the account
166
+ * already exists is not a failure — the thing the caller actually wanted is
167
+ * already true — and comes back as `"already-funded"` so the caller can say
168
+ * so rather than claiming a transfer that never happened.
169
+ */
170
+ export async function fundWithFriendbot(publicKey, attempts = 3) {
171
+ let lastError;
172
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
173
+ try {
174
+ const response = await fetch(`${FRIENDBOT_URL}/?addr=${encodeURIComponent(publicKey)}`, {
175
+ signal: AbortSignal.timeout(NETWORK_TIMEOUT_MS),
176
+ });
177
+ if (response.ok)
178
+ return "funded";
179
+ const body = await response.text();
180
+ if (response.status === 400 &&
181
+ /already (funded|exists)|createAccountAlreadyExist/i.test(body)) {
182
+ return "already-funded";
183
+ }
184
+ lastError = new Error(`Friendbot responded ${response.status}: ${body}`);
185
+ }
186
+ catch (error) {
187
+ lastError = error;
188
+ }
189
+ if (attempt < attempts)
190
+ await sleep(500 * attempt);
191
+ }
192
+ throw new ConfigurationError(`Could not fund ${publicKey} via Friendbot after ${attempts} attempt${attempts === 1 ? "" : "s"}: ` +
193
+ (lastError instanceof Error ? lastError.message : String(lastError)));
194
+ }
195
+ /**
196
+ * Establishes a trustline from `secretKey`'s own account to testnet USDC.
197
+ *
198
+ * This only opens the door — it does not put anything in it. The account
199
+ * needs a small amount of existing XLM first (the transaction fee, plus the
200
+ * reserve a trustline adds); callers should ensure that before calling this.
201
+ */
202
+ export async function createUsdcTrustline(secretKey, source) {
203
+ // Validates first, so a malformed key is reported as the named .env
204
+ // variable rather than as the SDK's bare "invalid encoded string".
205
+ publicKeyFromSecret(secretKey, source);
206
+ const keypair = Keypair.fromSecret(secretKey);
207
+ const server = horizonServer();
208
+ try {
209
+ const account = await server.loadAccount(keypair.publicKey());
210
+ const transaction = new TransactionBuilder(account, {
211
+ fee: BASE_FEE,
212
+ networkPassphrase: Networks.TESTNET,
213
+ })
214
+ .addOperation(Operation.changeTrust({ asset: testnetUsdcAsset() }))
215
+ .setTimeout(30)
216
+ .build();
217
+ transaction.sign(keypair);
218
+ await server.submitTransaction(transaction);
219
+ }
220
+ catch (error) {
221
+ throw asWalletError(error, "create the USDC trustline");
222
+ }
223
+ }
224
+ /**
225
+ * Sends testnet USDC from an already-funded distributor account to
226
+ * `destinationPublicKey`. There is no way to acquire the first unit of
227
+ * testnet USDC without a human completing Circle's faucet form
228
+ * (faucet.circle.com) once — this only helps once that has happened for the
229
+ * distributor account. The destination must already hold a USDC trustline;
230
+ * Stellar rejects a payment in an asset the receiver has not opted into.
231
+ */
232
+ export async function sendUsdcFromDistributor(distributorSecretKey, destinationPublicKey, amount) {
233
+ publicKeyFromSecret(distributorSecretKey, "WASIT_USDC_DISTRIBUTOR_SECRET");
234
+ if (!/^\d+(\.\d{1,7})?$/.test(amount) || Number(amount) <= 0) {
235
+ throw new ConfigurationError(`"${amount}" is not a valid USDC amount. Use a positive decimal with at ` +
236
+ `most 7 decimal places, e.g. 50 or 12.5.`);
237
+ }
238
+ const keypair = Keypair.fromSecret(distributorSecretKey);
239
+ const server = horizonServer();
240
+ try {
241
+ const account = await server.loadAccount(keypair.publicKey());
242
+ const transaction = new TransactionBuilder(account, {
243
+ fee: BASE_FEE,
244
+ networkPassphrase: Networks.TESTNET,
245
+ })
246
+ .addOperation(Operation.payment({ destination: destinationPublicKey, asset: testnetUsdcAsset(), amount }))
247
+ .setTimeout(30)
248
+ .build();
249
+ transaction.sign(keypair);
250
+ await server.submitTransaction(transaction);
251
+ }
252
+ catch (error) {
253
+ throw asWalletError(error, "send USDC from the distributor account");
254
+ }
255
+ }
@@ -19,6 +19,13 @@ export interface RequestShape {
19
19
  }
20
20
  export interface X402SimulatorOptions extends RequestShape {
21
21
  target: string;
22
+ /**
23
+ * Called once per check as soon as its result is known, in addition to it
24
+ * being included in the returned array — lets a caller render progress
25
+ * live instead of waiting for the whole suite to finish. Optional and has
26
+ * no effect on what is returned.
27
+ */
28
+ readonly onResult?: (result: CheckResult) => void;
22
29
  }
23
30
  /**
24
31
  * Runs X402-01 through X402-05 against a target.
@@ -31,6 +38,8 @@ export interface X402PaymentCheckOptions extends RequestShape {
31
38
  readonly target: string;
32
39
  readonly network: string;
33
40
  readonly payerSecretKey: string;
41
+ /** See {@link X402SimulatorOptions.onResult} — same contract. */
42
+ readonly onResult?: (result: CheckResult) => void;
34
43
  }
35
44
  /**
36
45
  * Runs X402-06 and X402-07 against a target.
@@ -170,6 +170,13 @@ function checkNetworkIdentifier(payload) {
170
170
  */
171
171
  export async function runX402ReadChecks(options) {
172
172
  const { target } = options;
173
+ // Reports each result to the caller's live-progress hook, if any, then
174
+ // returns them unchanged — every return in this function goes through here.
175
+ const emit = (results) => {
176
+ for (const result of results)
177
+ options.onResult?.(result);
178
+ return results;
179
+ };
173
180
  // A bad URL or an unusable request shape is wrong for every check, so it is
174
181
  // reported once rather than five times over.
175
182
  let init;
@@ -178,17 +185,17 @@ export async function runX402ReadChecks(options) {
178
185
  init = buildInit(options);
179
186
  }
180
187
  catch (error) {
181
- return [errored("PREFLIGHT", "Run Preflight", error)];
188
+ return emit([errored("PREFLIGHT", "Run Preflight", error)]);
182
189
  }
183
190
  let response;
184
191
  try {
185
192
  response = await fetchTarget(target, init);
186
193
  }
187
194
  catch (error) {
188
- return [
195
+ return emit([
189
196
  errored("X402-01", "402 Response Status", error),
190
197
  ...skipAfter("X402-01", "the target was never reached, so it issued no challenge to inspect."),
191
- ];
198
+ ]);
192
199
  }
193
200
  const statusPass = response.status === 402;
194
201
  const r1 = {
@@ -200,11 +207,11 @@ export async function runX402ReadChecks(options) {
200
207
  : `Expected status 402, got ${response.status}.`,
201
208
  };
202
209
  if (!statusPass) {
203
- return [
210
+ return emit([
204
211
  r1,
205
212
  ...skipAfter("X402-01", `the target answered ${response.status} rather than 402, so it issued ` +
206
213
  `no payment challenge to inspect.`),
207
- ];
214
+ ]);
208
215
  }
209
216
  // Both names are checked because Stellar's own documentation is not yet
210
217
  // internally consistent — see docs/CHECKS.md.
@@ -218,19 +225,19 @@ export async function runX402ReadChecks(options) {
218
225
  : "Neither PAYMENT-REQUIRED nor X-Payment header was present.",
219
226
  };
220
227
  if (headerValue === null) {
221
- return [
228
+ return emit([
222
229
  r1,
223
230
  r2,
224
231
  ...skipAfter("X402-02", "the 402 response carried no payment header, so there is no payload " +
225
232
  "to decode or inspect."),
226
- ];
233
+ ]);
227
234
  }
228
235
  let payload;
229
236
  try {
230
237
  payload = JSON.parse(Buffer.from(headerValue, "base64").toString("utf-8"));
231
238
  }
232
239
  catch (error) {
233
- return [
240
+ return emit([
234
241
  r1,
235
242
  r2,
236
243
  {
@@ -241,7 +248,7 @@ export async function runX402ReadChecks(options) {
241
248
  },
242
249
  ...skipAfter("X402-03", "the payment header did not decode to JSON, so no payload was " +
243
250
  "available to inspect."),
244
- ];
251
+ ]);
245
252
  }
246
253
  const r3 = {
247
254
  id: "X402-03",
@@ -249,10 +256,10 @@ export async function runX402ReadChecks(options) {
249
256
  pass: true,
250
257
  detail: "Header decoded to valid JSON.",
251
258
  };
252
- return [r3, r2, r1].reverse().concat([
259
+ return emit([r3, r2, r1].reverse().concat([
253
260
  checkRequiredFields(payload),
254
261
  checkNetworkIdentifier(payload),
255
- ]);
262
+ ]));
256
263
  }
257
264
  import { x402Client, x402HTTPClient } from "@x402/fetch";
258
265
  import { createEd25519Signer } from "@x402/stellar";
@@ -307,8 +314,14 @@ async function checkSignatureAccepted(options) {
307
314
  */
308
315
  async function checkInvalidSignatureRejected(options) {
309
316
  const { httpClient, paymentPayload } = await preparePayment(options);
310
- // Corrupt the signed transaction after signing, so the payload is
311
- // well-formed everywhere except the signature it carries.
317
+ // Corrupt the signed transaction after signing. This overwrites the tail of
318
+ // the base64 envelope, which also drops its padding — so the decoded envelope
319
+ // gains two bytes and stops parsing as XDR. Against the reference facilitator
320
+ // in stellar/x402-stellar the rejection therefore happens at decoding, not at
321
+ // signature verification, which is weaker than this check should be: a target
322
+ // that parsed the envelope and skipped verification entirely would still pass.
323
+ // Corrupting only the signature bytes, preserving a decodable envelope, is a
324
+ // 0.4.0 item. See docs/CHECKS.md's X402-07 row.
312
325
  const corrupted = {
313
326
  ...paymentPayload,
314
327
  payload: {
@@ -339,7 +352,9 @@ export async function runX402PaymentChecks(options) {
339
352
  buildInit(options);
340
353
  }
341
354
  catch (error) {
342
- return [errored("PREFLIGHT", "Run Preflight", error)];
355
+ const preflight = errored("PREFLIGHT", "Run Preflight", error);
356
+ options.onResult?.(preflight);
357
+ return [preflight];
343
358
  }
344
359
  const results = [];
345
360
  let accepted;
@@ -350,18 +365,24 @@ export async function runX402PaymentChecks(options) {
350
365
  accepted = errored("X402-06", "Signature Resubmit Accepted", error);
351
366
  }
352
367
  results.push(accepted);
368
+ options.onResult?.(accepted);
353
369
  // If the payment flow could not be exercised at all, a corrupted variant of
354
370
  // it cannot be either — and must not be reported as a passing rejection.
355
371
  if (accepted.error !== undefined) {
356
- results.push(skipped("X402-07", "Invalid Signature Rejected", `the payment flow could not be exercised (${accepted.error.kind}), so ` +
357
- `a corrupted signature cannot be tested against it.`));
372
+ const notExercised = skipped("X402-07", "Invalid Signature Rejected", `the payment flow could not be exercised (${accepted.error.kind}), so ` +
373
+ `a corrupted signature cannot be tested against it.`);
374
+ results.push(notExercised);
375
+ options.onResult?.(notExercised);
358
376
  return results;
359
377
  }
378
+ let rejected;
360
379
  try {
361
- results.push(await checkInvalidSignatureRejected(options));
380
+ rejected = await checkInvalidSignatureRejected(options);
362
381
  }
363
382
  catch (error) {
364
- results.push(errored("X402-07", "Invalid Signature Rejected", error));
383
+ rejected = errored("X402-07", "Invalid Signature Rejected", error);
365
384
  }
385
+ results.push(rejected);
386
+ options.onResult?.(rejected);
366
387
  return results;
367
388
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wasit-dev/core",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Check suite for x402/MPP protocol-conformance testing on Stellar. Powers the wasit CLI and wasit-mcp server.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -34,7 +34,9 @@
34
34
  "access": "public"
35
35
  },
36
36
  "scripts": {
37
- "build": "tsc -p tsconfig.json"
37
+ "build": "tsc -p tsconfig.json",
38
+ "test": "node --import tsx --test \"test/unit/**/*.test.ts\"",
39
+ "typecheck": "tsc -p test/tsconfig.json"
38
40
  },
39
41
  "dependencies": {
40
42
  "@stellar/mpp": "^0.7.1",
@@ -44,6 +46,7 @@
44
46
  "mppx": "^0.8.14"
45
47
  },
46
48
  "devDependencies": {
49
+ "@types/express": "^5.0.6",
47
50
  "@types/node": "^26.1.1",
48
51
  "@x402/core": "^2.19.0",
49
52
  "@x402/express": "^2.19.0",