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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +12 -4
  2. package/dist/baseline.d.ts +109 -0
  3. package/dist/baseline.js +351 -0
  4. package/dist/catalogue.d.ts +10 -0
  5. package/dist/catalogue.js +69 -3
  6. package/dist/check.d.ts +78 -2
  7. package/dist/check.js +69 -10
  8. package/dist/ci-report.d.ts +74 -0
  9. package/dist/ci-report.js +391 -0
  10. package/dist/config.d.ts +205 -0
  11. package/dist/config.js +1011 -0
  12. package/dist/denied-env.d.ts +33 -0
  13. package/dist/denied-env.js +86 -0
  14. package/dist/errors.d.ts +44 -1
  15. package/dist/errors.js +151 -2
  16. package/dist/guard/budget.d.ts +135 -0
  17. package/dist/guard/budget.js +199 -0
  18. package/dist/guard/ci-event.d.ts +50 -0
  19. package/dist/guard/ci-event.js +125 -0
  20. package/dist/guard/mainnet-optin.d.ts +58 -0
  21. package/dist/guard/mainnet-optin.js +95 -0
  22. package/dist/guard/networks.d.ts +50 -0
  23. package/dist/guard/networks.js +80 -0
  24. package/dist/guard/rpc-identity.d.ts +45 -0
  25. package/dist/guard/rpc-identity.js +156 -0
  26. package/dist/guard/rpc-in-use.d.ts +48 -0
  27. package/dist/guard/rpc-in-use.js +84 -0
  28. package/dist/index.d.ts +34 -3
  29. package/dist/index.js +31 -2
  30. package/dist/mpp/channel-commitment.d.ts +48 -2
  31. package/dist/mpp/channel-commitment.js +80 -4
  32. package/dist/mpp/channel-credential.js +3 -0
  33. package/dist/mpp/channel.js +29 -0
  34. package/dist/mpp/charge.d.ts +25 -2
  35. package/dist/mpp/charge.js +100 -8
  36. package/dist/mpp/network.js +4 -1
  37. package/dist/mpp/suite.js +10 -2
  38. package/dist/report.d.ts +163 -0
  39. package/dist/report.js +282 -0
  40. package/dist/sanitize.d.ts +52 -0
  41. package/dist/sanitize.js +106 -0
  42. package/dist/settlement.d.ts +14 -0
  43. package/dist/settlement.js +1 -1
  44. package/dist/verdict.d.ts +24 -0
  45. package/dist/verdict.js +46 -0
  46. package/dist/versions.d.ts +50 -0
  47. package/dist/versions.js +123 -0
  48. package/dist/x402/chains/evm.d.ts +65 -0
  49. package/dist/x402/chains/evm.js +237 -0
  50. package/dist/x402/chains/index.d.ts +18 -0
  51. package/dist/x402/chains/index.js +28 -0
  52. package/dist/x402/chains/stellar.d.ts +38 -0
  53. package/dist/x402/chains/stellar.js +277 -0
  54. package/dist/x402/chains/svm.d.ts +69 -0
  55. package/dist/x402/chains/svm.js +333 -0
  56. package/dist/x402/chains/types.d.ts +152 -0
  57. package/dist/x402/chains/types.js +10 -0
  58. package/dist/x402/chains/wait.d.ts +36 -0
  59. package/dist/x402/chains/wait.js +42 -0
  60. package/dist/x402/plan.d.ts +82 -0
  61. package/dist/x402/plan.js +146 -0
  62. package/dist/x402/rejected-request.d.ts +146 -0
  63. package/dist/x402/rejected-request.js +269 -0
  64. package/dist/x402/requirements.d.ts +46 -0
  65. package/dist/x402/requirements.js +359 -0
  66. package/dist/x402/simulator.d.ts +74 -17
  67. package/dist/x402/simulator.js +907 -246
  68. package/package.json +11 -6
@@ -0,0 +1,123 @@
1
+ /**
2
+ * The versions a result names: Wasit core and the CLI, the x402 version Wasit
3
+ * grades, and the SDK packages the checks run through.
4
+ *
5
+ * Read at run time from the installed packages' own `package.json`, by path,
6
+ * never typed by hand: a constant drifts from what is installed, and the point
7
+ * of printing a version is that it is the one that ran. They are read by path
8
+ * and not through `require.resolve("<pkg>/package.json")` because the SDK
9
+ * packages' export maps do not list it (checked on 2026-11-15 for all five:
10
+ * ERR_PACKAGE_PATH_NOT_EXPORTED).
11
+ */
12
+ import { readFileSync } from "node:fs";
13
+ import { dirname, join, resolve } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ /** What is printed when a version cannot be established. Never a guess. */
16
+ const UNKNOWN = "unknown";
17
+ /** A version as npm publishes it. Anything else is not printed: these strings reach a pull request comment. */
18
+ const VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]*)?$/;
19
+ /** An npm package name, scoped or not: no path segment can climb out of node_modules. */
20
+ const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/;
21
+ function versionIn(manifestPath, expectedName) {
22
+ try {
23
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
24
+ return manifest.name === expectedName && typeof manifest.version === "string" && VERSION.test(manifest.version)
25
+ ? manifest.version
26
+ : undefined;
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ }
32
+ /**
33
+ * The installed version of `name`, found the way Node finds a dependency: in
34
+ * `node_modules` of `from` or of any directory above it.
35
+ *
36
+ * Returns "unknown" when the package is not there, its name does not match, or
37
+ * its version is not a version.
38
+ */
39
+ export function readPackageVersion(name, from) {
40
+ if (!PACKAGE_NAME.test(name))
41
+ return UNKNOWN;
42
+ let directory = resolve(from);
43
+ for (;;) {
44
+ const version = versionIn(join(directory, "node_modules", name, "package.json"), name);
45
+ if (version !== undefined)
46
+ return version;
47
+ const parent = dirname(directory);
48
+ if (parent === directory)
49
+ return UNKNOWN;
50
+ directory = parent;
51
+ }
52
+ }
53
+ /** This package's own version: the `package.json` above this file, in `src/` and in `dist/` alike. */
54
+ function ownVersion() {
55
+ let directory = dirname(fileURLToPath(import.meta.url));
56
+ for (;;) {
57
+ const version = versionIn(join(directory, "package.json"), "@wasit-dev/core");
58
+ if (version !== undefined)
59
+ return version;
60
+ const parent = dirname(directory);
61
+ if (parent === directory)
62
+ return UNKNOWN;
63
+ directory = parent;
64
+ }
65
+ }
66
+ /** A commit id as an Action ref gives it: all 40 characters, lower case. Anything else (a tag, a branch) is not a commit. */
67
+ const FULL_COMMIT = /^[0-9a-f]{40}$/;
68
+ /** What a result names of a commit: its first seven characters. */
69
+ const SHORT_COMMIT = /^[0-9a-f]{7}$/;
70
+ /** True for exactly seven lower-case hex characters: the only build text that reaches a comment. */
71
+ export function isShortCommit(value) {
72
+ return typeof value === "string" && SHORT_COMMIT.test(value);
73
+ }
74
+ /**
75
+ * The commit this build of Wasit was made from, when the Action says so: the
76
+ * action ref (`WASIT_BUILD_COMMIT`) if it is a full commit id. A tag or a branch
77
+ * name is not a commit, and says nothing here: a pinned tag already names the
78
+ * version, and a result must not name a build it cannot show.
79
+ */
80
+ export function readBuildCommit(env) {
81
+ const value = env["WASIT_BUILD_COMMIT"];
82
+ return value !== undefined && FULL_COMMIT.test(value) ? value.slice(0, 7) : undefined;
83
+ }
84
+ /**
85
+ * The versions of this run. The CLI knows its own version (core cannot read the
86
+ * CLI's `package.json`), so it passes it in.
87
+ */
88
+ export function readToolVersions(cliVersion, build) {
89
+ const here = dirname(fileURLToPath(import.meta.url));
90
+ // `@x402/core` is a dependency of `@x402/fetch`; when npm does not hoist it, it sits under that package.
91
+ const fetchDir = (() => {
92
+ for (let directory = here;; directory = dirname(directory)) {
93
+ const candidate = join(directory, "node_modules", "@x402", "fetch");
94
+ if (versionIn(join(candidate, "package.json"), "@x402/fetch") !== undefined)
95
+ return candidate;
96
+ if (dirname(directory) === directory)
97
+ return undefined;
98
+ }
99
+ })();
100
+ const read = (name) => {
101
+ for (const start of fetchDir === undefined ? [here] : [here, fetchDir]) {
102
+ const version = readPackageVersion(name, start);
103
+ if (version !== UNKNOWN)
104
+ return version;
105
+ }
106
+ return UNKNOWN;
107
+ };
108
+ return {
109
+ wasit: {
110
+ cli: cliVersion !== undefined && VERSION.test(cliVersion) ? cliVersion : UNKNOWN,
111
+ core: ownVersion(),
112
+ ...(isShortCommit(build) ? { build } : {}),
113
+ },
114
+ sdk: {
115
+ x402Version: 2,
116
+ "@x402/core": read("@x402/core"),
117
+ "@x402/stellar": read("@x402/stellar"),
118
+ "@stellar/mpp": read("@stellar/mpp"),
119
+ mppx: read("mppx"),
120
+ "@stellar/stellar-sdk": read("@stellar/stellar-sdk"),
121
+ },
122
+ };
123
+ }
@@ -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;
@@ -0,0 +1,237 @@
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 { toClientEvmSigner } from "@x402/evm";
18
+ import { ExactEvmScheme } from "@x402/evm/exact/client";
19
+ import { TransactionReceiptNotFoundError, createPublicClient, erc20Abi, http, isAddress, isAddressEqual, toEventSelector, } from "viem";
20
+ import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
21
+ import { baseSepolia, sepolia } from "viem/chains";
22
+ import { CheckSetupError, ConfigurationError } from "../../errors.js";
23
+ import { waitForReceipt } from "./wait.js";
24
+ /**
25
+ * Circle's USDC on Ethereum Sepolia: EIP-3009, EIP-712 domain "USDC" version
26
+ * "2", 6 decimals (read from the contract, 2026-10-05). Not an SDK default.
27
+ */
28
+ export const ETHEREUM_SEPOLIA_USDC = "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238";
29
+ const NETWORKS = {
30
+ // A block every 2 seconds: 30 blocks is about a minute.
31
+ "eip155:84532": { chain: baseSepolia, blocksBeforeMissing: 30n, maxWaitMs: 120_000 },
32
+ // A block every 12 seconds: 10 blocks is about two minutes.
33
+ "eip155:11155111": {
34
+ chain: sepolia,
35
+ blocksBeforeMissing: 10n,
36
+ maxWaitMs: 240_000,
37
+ allowedAssets: [{ asset: ETHEREUM_SEPOLIA_USDC, maxAmountPerPayment: "1000000" }],
38
+ },
39
+ };
40
+ /** An EVM transaction hash: 0x and 32 bytes of hex. */
41
+ const TRANSACTION_HASH = /^0x[0-9a-fA-F]{64}$/;
42
+ /** A raw secp256k1 private key: 0x and 32 bytes of hex. */
43
+ const PRIVATE_KEY = /^0x[0-9a-fA-F]{64}$/;
44
+ /** `Transfer(address indexed from, address indexed to, uint256 value)`. */
45
+ const TRANSFER_TOPIC = toEventSelector("Transfer(address,address,uint256)");
46
+ function payerAccount(payerKey) {
47
+ // The message never echoes the key: it is a secret, and a malformed one is
48
+ // often a real key pasted with a character missing.
49
+ if (!PRIVATE_KEY.test(payerKey)) {
50
+ throw new ConfigurationError("EVM_PRIVATE_KEY is not an EVM private key: expected 0x followed by 64 hex characters.");
51
+ }
52
+ return privateKeyToAccount(payerKey);
53
+ }
54
+ /** The last 20 bytes of a 32-byte topic: an indexed address. */
55
+ function topicAddress(topic) {
56
+ return `0x${topic.slice(-40)}`;
57
+ }
58
+ /**
59
+ * The ERC-20 `Transfer` logs in a receipt. ERC-721 shares the event
60
+ * signature but indexes the token id as a fourth topic, so only logs with
61
+ * exactly three topics and a 32-byte value are read as token transfers.
62
+ */
63
+ export function evmTransfers(logs) {
64
+ return logs
65
+ .filter((log) => log.topics.length === 3 &&
66
+ log.topics[0]?.toLowerCase() === TRANSFER_TOPIC &&
67
+ /^0x[0-9a-fA-F]{64}$/.test(log.data))
68
+ .map((log) => ({
69
+ token: log.address,
70
+ from: topicAddress(log.topics[1]),
71
+ to: topicAddress(log.topics[2]),
72
+ value: BigInt(log.data),
73
+ }));
74
+ }
75
+ /**
76
+ * Holds a settled transaction's receipt to what the target advertised.
77
+ *
78
+ * The same rules as on Stellar: the transaction succeeded, it moved exactly
79
+ * one token transfer, and that transfer is the advertised amount of the
80
+ * advertised token, to the advertised recipient, from this run's own payer,
81
+ * so a target cannot cite some other transaction that happens to match.
82
+ */
83
+ export function verifyEvmReceipt(receipt, reference, expected) {
84
+ const fail = (detail) => ({ pass: false, detail });
85
+ if (receipt.status !== "success") {
86
+ return fail(`Transaction ${reference} exists on-chain but reverted. The target reported ` +
87
+ `success for a settlement that did not settle.`);
88
+ }
89
+ const transfers = evmTransfers(receipt.logs);
90
+ if (transfers.length === 0) {
91
+ return fail(`Transaction ${reference} succeeded but logged no ERC-20 Transfer, so no ` +
92
+ `token movement can be verified.`);
93
+ }
94
+ if (transfers.length !== 1) {
95
+ return fail(`Transaction ${reference} logged ${transfers.length} ERC-20 Transfers; ` +
96
+ `exactly one was expected. Additional balance changes mean the settlement ` +
97
+ `moved more than what was advertised.`);
98
+ }
99
+ const actual = transfers[0];
100
+ const same = (a, b) => {
101
+ try {
102
+ return isAddressEqual(a, b);
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ };
108
+ const mismatches = [];
109
+ if (actual.value !== expected.amount) {
110
+ mismatches.push(`amount: advertised ${expected.amount} base units, moved ${actual.value}`);
111
+ }
112
+ if (!same(actual.to, expected.recipient)) {
113
+ mismatches.push(`recipient: advertised ${expected.recipient}, paid ${actual.to}`);
114
+ }
115
+ if (!same(actual.token, expected.token)) {
116
+ mismatches.push(`token: advertised ${expected.token}, moved ${actual.token}`);
117
+ }
118
+ if (!same(actual.from, expected.payer)) {
119
+ mismatches.push(`payer: this run paid from ${expected.payer}, but the referenced transfer ` +
120
+ `came from ${actual.from}`);
121
+ }
122
+ if (mismatches.length > 0) {
123
+ return fail(`Settlement does not match what the target advertised — ` +
124
+ `${mismatches.join("; ")} (tx ${reference}).`);
125
+ }
126
+ return {
127
+ pass: true,
128
+ detail: `settled on-chain for exactly the advertised ${expected.amount} base ` +
129
+ `units of ${expected.token} to ${expected.recipient}, verified from the ` +
130
+ `Transfer log (tx ${reference})`,
131
+ };
132
+ }
133
+ async function verifyEvmSettlement(network, rpcUrl, reference, expected) {
134
+ const profile = NETWORKS[network];
135
+ if (profile === undefined) {
136
+ throw new ConfigurationError(`No EVM network "${network}" in Wasit's payment checks.`);
137
+ }
138
+ const client = createPublicClient({ transport: http(rpcUrl) });
139
+ const lookup = await waitForReceipt(async () => {
140
+ try {
141
+ return await client.getTransactionReceipt({ hash: reference });
142
+ }
143
+ catch (error) {
144
+ if (error instanceof TransactionReceiptNotFoundError)
145
+ return undefined;
146
+ throw error;
147
+ }
148
+ }, () => client.getBlockNumber(), { blocks: profile.blocksBeforeMissing, maxWaitMs: profile.maxWaitMs });
149
+ if (lookup.kind === "stalled") {
150
+ // An RPC that is not advancing says nothing about the target: no verdict.
151
+ throw new Error(`RPC at ${rpcUrl} produced only ${lookup.blocksWatched} blocks in ` +
152
+ `${Math.round(lookup.waitedMs / 1000)} seconds while looking for tx ` +
153
+ `${reference}, so its absence says nothing about the target. Re-run, ` +
154
+ `or point --rpc-url at another endpoint.`);
155
+ }
156
+ if (lookup.kind === "missing") {
157
+ return {
158
+ pass: false,
159
+ detail: `Target reported settlement as tx ${reference}, but the chain produced ` +
160
+ `${lookup.blocksWatched} more blocks without it. Either it was never ` +
161
+ `broadcast, or the target referenced a transaction that does not exist.`,
162
+ };
163
+ }
164
+ return verifyEvmReceipt(lookup.receipt, reference, expected);
165
+ }
166
+ /**
167
+ * Corrupts the payer's signature, and nothing else.
168
+ *
169
+ * The EIP-3009 payload is `{ signature, authorization }`; Permit2's carries a
170
+ * `signature` too. Flipping the first byte of `r` leaves a signature of the
171
+ * same length whose recovered signer is no longer `authorization.from`, while
172
+ * the amount, recipient and validity window stay intact. A target can refuse
173
+ * it only by verifying the signature (spec, verification step 1).
174
+ */
175
+ export function corruptEvmSignature(payload) {
176
+ const signature = payload["signature"];
177
+ // 65 bytes for an EOA; a contract wallet's signature is longer, never shorter.
178
+ if (typeof signature !== "string" || !/^0x(?:[0-9a-fA-F]{2}){65,}$/.test(signature)) {
179
+ throw new CheckSetupError("The payment payload carries no EVM signature to corrupt, so a corrupted " +
180
+ "signature cannot be tested.");
181
+ }
182
+ const first = (Number.parseInt(signature.slice(2, 4), 16) ^ 0xff).toString(16).padStart(2, "0");
183
+ return { ...payload, signature: `0x${first}${signature.slice(4)}` };
184
+ }
185
+ export const evmChain = {
186
+ name: "EVM",
187
+ networks: Object.keys(NETWORKS),
188
+ payerKeyEnv: "EVM_PRIVATE_KEY",
189
+ referenceKind: "an EVM transaction hash",
190
+ resolveRpcUrl(network, override) {
191
+ const profile = NETWORKS[network];
192
+ if (profile === undefined) {
193
+ throw new ConfigurationError(`No EVM network "${network}" in Wasit's payment checks.`);
194
+ }
195
+ if (override)
196
+ return override;
197
+ const fallback = profile.chain.rpcUrls.default.http[0];
198
+ if (fallback === undefined) {
199
+ throw new ConfigurationError(`No default RPC endpoint for ${network}. Pass an explicit rpcUrl.`);
200
+ }
201
+ return fallback;
202
+ },
203
+ registerPayer(client, network, payerKey, rpcUrl) {
204
+ // The signer can read the chain: the SDK needs that only on the Permit2
205
+ // path (allowance, permit nonce). EIP-3009 signing stays offline.
206
+ const signer = toClientEvmSigner(payerAccount(payerKey), createPublicClient({ transport: http(rpcUrl) }));
207
+ client.register("eip155:*", new ExactEvmScheme(signer, { rpcUrl }));
208
+ const allowed = NETWORKS[network]?.allowedAssets;
209
+ if (allowed !== undefined) {
210
+ // Replaces the controls Wasit set before this call, so the $1 cap on the
211
+ // default assets is stated again rather than left to the SDK's default.
212
+ client.setSpendControls({
213
+ maxAmountPerPayment: "$1",
214
+ allowedAssets: allowed.map((entry) => ({ network: network, ...entry })),
215
+ });
216
+ }
217
+ },
218
+ // validBefore is now + 1 second. Held 5 seconds, it has passed by the
219
+ // clock, and any block that could include it is later still, whatever
220
+ // the chain's block time.
221
+ expiredSigning: async () => ({ terms: { maxTimeoutSeconds: 1 }, holdMs: 5_000 }),
222
+ payerAddress: (payerKey) => payerAccount(payerKey).address,
223
+ generatePayerKey: () => generatePrivateKey(),
224
+ async payerBalance(_network, rpcUrl, payer, asset) {
225
+ if (!isAddress(asset) || !isAddress(payer))
226
+ return undefined;
227
+ return createPublicClient({ transport: http(rpcUrl) }).readContract({
228
+ address: asset,
229
+ abi: erc20Abi,
230
+ functionName: "balanceOf",
231
+ args: [payer],
232
+ });
233
+ },
234
+ isSettlementReference: (reference) => TRANSACTION_HASH.test(reference),
235
+ verifySettlement: verifyEvmSettlement,
236
+ corruptPayload: corruptEvmSignature,
237
+ };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The chains the x402 payment checks can pay on. Adding one is adding an
3
+ * adapter here; the checks do not change.
4
+ */
5
+ import type { PaymentChain } from "./types.js";
6
+ export type { PaymentChain } from "./types.js";
7
+ /**
8
+ * Tests only: replaces the adapters, so a recording chain can stand in for a
9
+ * real one (spec B11, the worst-case property test). `undefined` restores the
10
+ * real ones. Not exported from the package index, and reachable from no flag,
11
+ * setting or tool argument. The network guard still applies: a replacement
12
+ * pays only on a test network.
13
+ */
14
+ export declare function setPaymentChainsForTesting(replacement: readonly PaymentChain[] | undefined): void;
15
+ /** The adapter that pays on `network`, if Wasit has one. */
16
+ export declare function paymentChainFor(network: string): PaymentChain | undefined;
17
+ /** Every network the payment checks can pay on, in adapter order. */
18
+ export declare function paymentNetworks(): readonly string[];
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The chains the x402 payment checks can pay on. Adding one is adding an
3
+ * adapter here; the checks do not change.
4
+ */
5
+ import { evmChain } from "./evm.js";
6
+ import { stellarChain } from "./stellar.js";
7
+ import { svmChain } from "./svm.js";
8
+ // Stellar first: it is the default network, and the only chain with MPP.
9
+ const CHAINS = [stellarChain, evmChain, svmChain];
10
+ let chains = CHAINS;
11
+ /**
12
+ * Tests only: replaces the adapters, so a recording chain can stand in for a
13
+ * real one (spec B11, the worst-case property test). `undefined` restores the
14
+ * real ones. Not exported from the package index, and reachable from no flag,
15
+ * setting or tool argument. The network guard still applies: a replacement
16
+ * pays only on a test network.
17
+ */
18
+ export function setPaymentChainsForTesting(replacement) {
19
+ chains = replacement ?? CHAINS;
20
+ }
21
+ /** The adapter that pays on `network`, if Wasit has one. */
22
+ export function paymentChainFor(network) {
23
+ return chains.find((chain) => chain.networks.includes(network));
24
+ }
25
+ /** Every network the payment checks can pay on, in adapter order. */
26
+ export function paymentNetworks() {
27
+ return chains.flatMap((chain) => chain.networks);
28
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The `exact` scheme on Stellar: Soroban authorization entries signed by the
3
+ * payer, settlement read from the token contract's `transfer` event on
4
+ * Stellar RPC (settlement.ts). This is the chain Wasit was built on, and the
5
+ * only one with MPP as well.
6
+ */
7
+ import { Asset } from "@stellar/stellar-sdk";
8
+ import type { PaymentChain, SignedAuthorization } from "./types.js";
9
+ /**
10
+ * Corrupts the client's authorization signature, and nothing else.
11
+ *
12
+ * In the `exact` scheme on Stellar the client signs a Soroban authorization
13
+ * entry, not the envelope: the facilitator signs the envelope later. So the
14
+ * signature that proves the payer consented is the address credential's
15
+ * `signature`, a `Vec<{ public_key, signature }>`. Flipping one byte of it
16
+ * leaves a transaction that still decodes, carries the same amount, payer and
17
+ * recipient, and fails only signature verification. A target can refuse it
18
+ * only by verifying the signature.
19
+ *
20
+ * Throws {@link CheckSetupError} if the payload carries no such signature, so
21
+ * the check reports no verdict rather than one it did not establish.
22
+ */
23
+ export declare function corruptAuthSignature(transaction: string): string;
24
+ /**
25
+ * The classic asset a Stellar Asset Contract wraps, from the `name` it
26
+ * reports ("CODE:ISSUER", CAP-46-06), only when that asset's contract id is
27
+ * `contractId`: any contract can return such a name, but only the SAC has
28
+ * the id derived from the asset.
29
+ */
30
+ export declare function sacAssetFromName(name: unknown, contractId: string, passphrase: string): Asset | undefined;
31
+ /**
32
+ * X402-11 reads (D-032, spec B16.4): the authorization a payment carries, as
33
+ * the payer signed it. Only an address credential is read; another form (the
34
+ * newer `AddressV2`, one with delegates) is not, and gives no reading rather
35
+ * than a guess, since its nonce handling was not read.
36
+ */
37
+ export declare function decodeStellarAuthorization(payload: Record<string, unknown>): SignedAuthorization;
38
+ export declare const stellarChain: PaymentChain;