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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +13 -2
  2. package/dist/baseline.js +3 -1
  3. package/dist/check.d.ts +1 -1
  4. package/dist/ci-report.js +15 -7
  5. package/dist/config-writer.d.ts +96 -0
  6. package/dist/config-writer.js +281 -0
  7. package/dist/guard/budget.d.ts +6 -3
  8. package/dist/guard/budget.js +10 -3
  9. package/dist/guard/ci-event.d.ts +6 -0
  10. package/dist/guard/ci-event.js +7 -3
  11. package/dist/guard/ci-mainnet.d.ts +59 -0
  12. package/dist/guard/ci-mainnet.js +149 -0
  13. package/dist/guard/horizon.d.ts +30 -0
  14. package/dist/guard/horizon.js +107 -0
  15. package/dist/guard/mainnet-payer.d.ts +66 -0
  16. package/dist/guard/mainnet-payer.js +92 -0
  17. package/dist/guard/mainnet-plan.d.ts +133 -0
  18. package/dist/guard/mainnet-plan.js +208 -0
  19. package/dist/guard/mainnet-run.d.ts +87 -0
  20. package/dist/guard/mainnet-run.js +225 -0
  21. package/dist/guard/networks.d.ts +9 -8
  22. package/dist/guard/networks.js +21 -10
  23. package/dist/guard/optin.d.ts +106 -0
  24. package/dist/guard/optin.js +202 -0
  25. package/dist/guard/run-ledger.d.ts +212 -0
  26. package/dist/guard/run-ledger.js +426 -0
  27. package/dist/guard/run-lock.d.ts +62 -0
  28. package/dist/guard/run-lock.js +172 -0
  29. package/dist/guard/signed-terms.d.ts +96 -0
  30. package/dist/guard/signed-terms.js +207 -0
  31. package/dist/index.d.ts +18 -7
  32. package/dist/index.js +19 -5
  33. package/dist/mpp/channel-credential.d.ts +13 -1
  34. package/dist/mpp/channel-credential.js +18 -2
  35. package/dist/mpp/channel.d.ts +6 -0
  36. package/dist/mpp/channel.js +7 -3
  37. package/dist/mpp/charge.d.ts +31 -1
  38. package/dist/mpp/charge.js +74 -20
  39. package/dist/mpp/plan.d.ts +77 -0
  40. package/dist/mpp/plan.js +188 -0
  41. package/dist/mpp/suite.d.ts +6 -0
  42. package/dist/mpp/suite.js +2 -1
  43. package/dist/route-reader.d.ts +124 -0
  44. package/dist/route-reader.js +349 -0
  45. package/dist/wallet.d.ts +58 -1
  46. package/dist/wallet.js +128 -0
  47. package/dist/x402/chains/stellar.js +134 -3
  48. package/dist/x402/chains/types.d.ts +36 -2
  49. package/dist/x402/plan.d.ts +102 -0
  50. package/dist/x402/plan.js +380 -6
  51. package/dist/x402/rejected-request.d.ts +10 -0
  52. package/dist/x402/rejected-request.js +18 -0
  53. package/dist/x402/simulator.d.ts +34 -0
  54. package/dist/x402/simulator.js +452 -46
  55. package/package.json +1 -1
  56. package/dist/guard/mainnet-optin.d.ts +0 -58
  57. package/dist/guard/mainnet-optin.js +0 -95
@@ -8,6 +8,9 @@ import { createEd25519Signer } from "@x402/stellar";
8
8
  import { ExactStellarScheme as ExactStellarClientScheme } from "@x402/stellar/exact/client";
9
9
  import { Account, Address, Asset, Contract, Keypair, StrKey, TransactionBuilder, rpc, scValToNative, xdr, } from "@stellar/stellar-sdk";
10
10
  import { CheckSetupError } from "../../errors.js";
11
+ import { PaymentGuardRefusedError } from "../../guard/budget.js";
12
+ import { isLiveOptIn } from "../../guard/optin.js";
13
+ import { checkStellarPreimage } from "../../guard/signed-terms.js";
11
14
  import { networkPassphrase, resolveRpcUrl } from "../../mpp/network.js";
12
15
  import { readTransferData, verifySettlement } from "../../settlement.js";
13
16
  /** A Stellar transaction hash: 64 hex characters. */
@@ -251,21 +254,149 @@ const stellarAuthorizations = {
251
254
  return { latest: response.latestLedger, transfers };
252
255
  },
253
256
  };
257
+ /**
258
+ * The payer's signer, gated (spec B17.2): each authorization the x402 client
259
+ * asks it to sign is checked against the terms `gate` was armed with, and the
260
+ * key signs only when it authorizes exactly that transfer, once. There is no
261
+ * `signTransaction`: the scheme has the facilitator pay the fees, so the
262
+ * client never signs the envelope.
263
+ */
264
+ function gatedSigner(payerKey, network, gate) {
265
+ const base = createEd25519Signer(payerKey, network);
266
+ const signAuthEntry = async (preimage, opts) => {
267
+ const terms = gate.take();
268
+ if (opts?.address !== undefined && opts.address !== base.address) {
269
+ throw new PaymentGuardRefusedError("signed-terms", "The x402 client asked for a signature for another address than the payer's.");
270
+ }
271
+ if (terms.payer !== base.address) {
272
+ throw new PaymentGuardRefusedError("signed-terms", "The payment's terms name another payer than the key Wasit holds.");
273
+ }
274
+ checkStellarPreimage(preimage, terms);
275
+ const result = await base.signAuthEntry(preimage, opts);
276
+ gate.record({ preimage, signature: Buffer.from(result.signedAuthEntry, "base64") });
277
+ return result;
278
+ };
279
+ return { address: base.address, signAuthEntry };
280
+ }
281
+ /** The `signature` bytes of an address credential signed by one ed25519 key, if it is that shape. */
282
+ function credentialSignature(signature) {
283
+ if (signature.switch().name !== "scvVec")
284
+ return undefined;
285
+ const items = signature.vec() ?? [];
286
+ if (items.length !== 1 || items[0].switch().name !== "scvMap")
287
+ return undefined;
288
+ let publicKey;
289
+ let bytes;
290
+ for (const field of items[0].map() ?? []) {
291
+ if (field.key().switch().name !== "scvSymbol" || field.val().switch().name !== "scvBytes")
292
+ return undefined;
293
+ const key = field.key().sym().toString();
294
+ if (key === "public_key")
295
+ publicKey = Buffer.from(field.val().bytes());
296
+ else if (key === "signature")
297
+ bytes = Buffer.from(field.val().bytes());
298
+ else
299
+ return undefined;
300
+ }
301
+ return publicKey === undefined || bytes === undefined ? undefined : { publicKey, signature: bytes };
302
+ }
303
+ function notSent(message) {
304
+ return new PaymentGuardRefusedError("signed-terms", message, { signed: true });
305
+ }
306
+ const stellarSignedTerms = {
307
+ // The x402 Stellar client's fallback ledger close time (DEFAULT_ESTIMATED_LEDGER_SECONDS in
308
+ // @x402/stellar 2.28.0), and the shortest it assumes: a faster close only tightens the bound.
309
+ unitSeconds: 5,
310
+ async latestUnit(_network, rpcUrl) {
311
+ return (await rpcServer(rpcUrl).getLatestLedger()).sequence;
312
+ },
313
+ bind(payload, gate) {
314
+ const signed = gate.signed;
315
+ if (signed === undefined) {
316
+ throw new PaymentGuardRefusedError("signed-terms", "The x402 client built a payment without the signature Wasit checked.");
317
+ }
318
+ const checked = xdr.HashIdPreimage.fromXDR(signed.preimage, "base64").sorobanAuthorization();
319
+ const transaction = payload["transaction"];
320
+ let envelope;
321
+ try {
322
+ if (typeof transaction !== "string")
323
+ throw new Error("no transaction");
324
+ envelope = xdr.TransactionEnvelope.fromXDR(transaction, "base64");
325
+ }
326
+ catch {
327
+ throw notSent("The payment the x402 client built carries no transaction that decodes.");
328
+ }
329
+ const payer = gate.terms?.payer;
330
+ const operations = envelope.switch().name === "envelopeTypeTx" ? envelope.v1().tx().operations() : [];
331
+ const ours = [];
332
+ for (const operation of operations) {
333
+ if (operation.body().switch().name !== "invokeHostFunction")
334
+ continue;
335
+ for (const entry of operation.body().invokeHostFunctionOp().auth()) {
336
+ const kind = entry.credentials().switch().name;
337
+ if (kind === "sorobanCredentialsSourceAccount")
338
+ continue;
339
+ if (kind !== "sorobanCredentialsAddress") {
340
+ throw notSent("The payment the x402 client built carries an authorization in a form Wasit did not sign.");
341
+ }
342
+ if (Address.fromScAddress(entry.credentials().address().address()).toString() === payer)
343
+ ours.push(entry);
344
+ }
345
+ }
346
+ if (ours.length !== 1) {
347
+ throw notSent(`The payment the x402 client built carries ${ours.length} authorizations for the payer; Wasit signed one.`);
348
+ }
349
+ const entry = ours[0];
350
+ const credentials = entry.credentials().address();
351
+ if (entry.rootInvocation().toXDR("base64") !== checked.invocation().toXDR("base64")) {
352
+ throw notSent("The payment the x402 client built names another invocation than the one Wasit checked and signed.");
353
+ }
354
+ if (credentials.signatureExpirationLedger() !== checked.signatureExpirationLedger()) {
355
+ throw notSent("The payment the x402 client built carries another expiration ledger than the one signed.");
356
+ }
357
+ if (credentials.nonce().toString() !== checked.nonce().toString()) {
358
+ throw notSent("The payment the x402 client built carries another nonce than the one signed.");
359
+ }
360
+ const sent = credentialSignature(credentials.signature());
361
+ if (sent === undefined ||
362
+ payer === undefined ||
363
+ !sent.publicKey.equals(Keypair.fromPublicKey(payer).rawPublicKey()) ||
364
+ !sent.signature.equals(signed.signature)) {
365
+ throw notSent("The payment the x402 client built carries another signature than the one Wasit made.");
366
+ }
367
+ },
368
+ };
254
369
  export const stellarChain = {
255
370
  name: "Stellar",
256
371
  networks: ["stellar:testnet", "stellar:pubnet"],
257
372
  payerKeyEnv: "STELLAR_PRIVATE_KEY",
258
373
  referenceKind: "a settled Stellar transaction hash",
259
374
  resolveRpcUrl: (network, override) => resolveRpcUrl(network, override),
260
- registerPayer(client, network, payerKey, _rpcUrl) {
261
- const signer = createEd25519Signer(payerKey, network);
262
- client.register("stellar:*", new ExactStellarClientScheme(signer));
375
+ // The x402 Stellar client builds its RPC client without `allowHttp`.
376
+ httpsRpcOnly: true,
377
+ registerPayer(client, network, payerKey, rpcUrl, gate, mainnet) {
378
+ // The payment is built and simulated through the run's RPC: the one whose
379
+ // network was checked (D-023), the anchor is read from, and the settlement
380
+ // is read from. On stellar:pubnet only with a live mainnet opt-in whose RPC
381
+ // this is (spec B5 point 4): without one the SDK gets no RPC, and refuses
382
+ // pubnet itself (B-A01).
383
+ const rpcConfig = network === "stellar:testnet" || (network === "stellar:pubnet" && isLiveOptIn(mainnet, network) && mainnet.rpcUrl === rpcUrl)
384
+ ? { url: rpcUrl }
385
+ : undefined;
386
+ client.register("stellar:*", new ExactStellarClientScheme(gatedSigner(payerKey, network, gate), rpcConfig));
263
387
  },
388
+ signedTerms: stellarSignedTerms,
264
389
  // A one-second lifetime is one ledger (ceil(1 / 5)); ledgers close about
265
390
  // every 5 to 6 seconds, so 20 seconds is three or more ledgers past it.
266
391
  expiredSigning: async () => ({ terms: { maxTimeoutSeconds: 1 }, holdMs: 20_000 }),
267
392
  payerAddress: (payerKey) => Keypair.fromSecret(payerKey).publicKey(),
268
393
  payerBalance: stellarTokenBalance,
394
+ async assetDecimals(network, rpcUrl, asset) {
395
+ if (!StrKey.isValidContract(asset))
396
+ return undefined;
397
+ const decimals = await simulateTokenRead(rpcServer(rpcUrl), networkPassphrase(network), asset, "decimals", []);
398
+ return typeof decimals === "number" ? decimals : undefined;
399
+ },
269
400
  generatePayerKey: () => Keypair.random().secret(),
270
401
  isSettlementReference: (reference) => TRANSACTION_HASH.test(reference),
271
402
  verifySettlement: (_network, rpcUrl, reference, expected) => verifySettlement(rpcUrl, reference, expected),
@@ -9,6 +9,8 @@
9
9
  */
10
10
  import type { PaymentRequirements } from "@x402/core/types";
11
11
  import type { x402Client } from "@x402/fetch";
12
+ import type { MainnetOptIn } from "../../guard/optin.js";
13
+ import type { SigningGate } from "../../guard/signed-terms.js";
12
14
  import type { ExpectedSettlement, SettlementVerdict } from "../../settlement.js";
13
15
  /**
14
16
  * What a negative check signs differently from the honest payment. The
@@ -93,6 +95,24 @@ export interface AuthorizationWatch {
93
95
  readonly transfers: readonly RecordedTransfer[];
94
96
  }>;
95
97
  }
98
+ /**
99
+ * The signed-terms gate of an adapter whose client signs what an RPC returns
100
+ * (spec B17.2, `guard/signed-terms.ts`). An adapter with one signs only
101
+ * through the `SigningGate` that `preparePayment` arms; every network that can
102
+ * be opted into belongs to such an adapter (a test pins it).
103
+ */
104
+ export interface SignedTermsBinding {
105
+ /** The shortest a unit (a ledger) takes, in seconds: the bound counts with it. */
106
+ readonly unitSeconds: number;
107
+ /** The chain's latest unit on `rpcUrl`: read once per run, as the anchor of every expiration bound. */
108
+ latestUnit(network: string, rpcUrl: string): Promise<number>;
109
+ /**
110
+ * Throws `PaymentGuardRefusedError` unless the payment payload's inner
111
+ * `payload` carries exactly the one authorization `gate` let the key sign,
112
+ * with that signature: the payload is then discarded unsent.
113
+ */
114
+ bind(payload: Record<string, unknown>, gate: SigningGate): void;
115
+ }
96
116
  export interface PaymentChain {
97
117
  /** The chain family's name, for reports. */
98
118
  readonly name: string;
@@ -111,9 +131,18 @@ export interface PaymentChain {
111
131
  * Registers this chain's `exact` client scheme, signing with `payerKey`.
112
132
  * `rpcUrl` is for client schemes that read the chain while building a
113
133
  * payment (EVM Permit2 checks the token allowance, Solana fetches the mint
114
- * and a blockhash); others ignore it.
134
+ * and a blockhash); others ignore it. An adapter with `signedTerms` signs
135
+ * only through `gate`; the others ignore it. `mainnet` is the run's opt-in
136
+ * on a mainnet network (spec B5), absent everywhere else.
137
+ */
138
+ registerPayer(client: x402Client, network: string, payerKey: string, rpcUrl: string, gate: SigningGate, mainnet?: MainnetOptIn): void | Promise<void>;
139
+ /**
140
+ * The client builds the payment through the run's RPC and accepts only an
141
+ * https one: an http RPC is refused before anything is asked or sent.
115
142
  */
116
- registerPayer(client: x402Client, network: string, payerKey: string, rpcUrl: string): void | Promise<void>;
143
+ readonly httpsRpcOnly?: boolean;
144
+ /** Present when the payer's signer is gated (see {@link SignedTermsBinding}); `gate` is then the one to sign through. */
145
+ readonly signedTerms?: SignedTermsBinding;
117
146
  /**
118
147
  * How X402-10 makes a payment that has expired when it arrives, for the
119
148
  * option `selected`. Where the client derives the lifetime from
@@ -133,6 +162,11 @@ export interface PaymentChain {
133
162
  * verdict.
134
163
  */
135
164
  payerBalance(network: string, rpcUrl: string, payer: string, asset: string): Promise<bigint | undefined>;
165
+ /**
166
+ * The token's decimals as the chain reports them, read without a key;
167
+ * undefined when there is no clear answer. A mainnet plan reads them (B4).
168
+ */
169
+ assetDecimals?(network: string, rpcUrl: string, asset: string): Promise<number | undefined>;
136
170
  /** Whether `reference` has the shape of a settlement on this chain. */
137
171
  isSettlementReference(reference: string): boolean;
138
172
  /**
@@ -9,7 +9,15 @@
9
9
  * the payment gets a refusal, not a signature.
10
10
  *
11
11
  * It sends no payment, reads no key and signs nothing.
12
+ *
13
+ * A mainnet run (a live opt-in, spec B5) is planned by stricter rules: first
14
+ * the token's decimals, the payer's USDC (through the RPC and on public
15
+ * Horizon, $10 at most) and the RPC's latest ledger beside Horizon's are read,
16
+ * before the target is asked anything; then every endpoint must plan, by the
17
+ * mainnet rules. Any refusal stops the opt-in. A plan that passes is recorded
18
+ * on it, and is the only plan its checks pay by.
12
19
  */
20
+ import { type MainnetOptIn } from "../guard/optin.js";
13
21
  import { type PinTerms, type PlannedSignature } from "../guard/budget.js";
14
22
  import { type RejectCase } from "./rejected-request.js";
15
23
  import { type RequestShape } from "./simulator.js";
@@ -25,6 +33,31 @@ export interface X402PlanOptions {
25
33
  /** A lower per-run cap in dollars. */
26
34
  readonly maxRunUsd?: number;
27
35
  readonly endpoints: readonly PlanEndpointInput[];
36
+ /**
37
+ * The run's mainnet opt-in (spec B5), made by `openMainnetOptIn`. On
38
+ * `stellar:pubnet` the plan needs it; its pin and cap are the run's, and a
39
+ * different pin or a `maxRunUsd` beside it is refused.
40
+ */
41
+ readonly mainnet?: MainnetOptIn;
42
+ }
43
+ /** What a mainnet plan read before it planned anything (spec B3, B4, B17.2, B17.5). */
44
+ export interface MainnetReadings {
45
+ /** The payer's public address. */
46
+ readonly payer: string;
47
+ /** The token's decimals, read on chain. */
48
+ readonly decimals: number;
49
+ /** The payer's USDC in base units: the RPC's reading, equal to Horizon's. */
50
+ readonly usdc: bigint;
51
+ /** The payer's XLM in base units, as Horizon lists it. */
52
+ readonly native: bigint;
53
+ /** The RPC's latest ledger (the run's anchor) and Horizon's. */
54
+ readonly rpcLatest: number;
55
+ readonly horizonLatest: number;
56
+ /** The two hosts a mainnet run contacts beside the service (B5 point 4), by origin. */
57
+ readonly rpc: string;
58
+ readonly horizon: string;
59
+ /** What is left of the run's budget, in dollar units: the cap less what it already charged. */
60
+ readonly remainingUsd: bigint;
28
61
  }
29
62
  /** The option an endpoint's checks would pay, as its challenge stated it. */
30
63
  export interface PlannedOption {
@@ -45,6 +78,12 @@ export type EndpointPlanStatus =
45
78
  | "refused";
46
79
  export interface EndpointPlan {
47
80
  readonly name: string;
81
+ /**
82
+ * Mainnet plans only: the one URL its payment checks pay, origin and path
83
+ * (no query, no fragment), as the config names it. L2 refuses a payment
84
+ * the service sends anywhere else.
85
+ */
86
+ readonly url?: string;
48
87
  readonly status: EndpointPlanStatus;
49
88
  readonly reason?: string;
50
89
  readonly option?: PlannedOption;
@@ -54,6 +93,32 @@ export interface EndpointPlan {
54
93
  /** Dollar units of `guard/budget.ts`; format with `formatUsd`. */
55
94
  readonly worstCaseUsd: bigint;
56
95
  }
96
+ /**
97
+ * What a mainnet run needs the payer to hold (the payer's funds), in USDC base
98
+ * units. Every endpoint settles once at X402-06 on a service that settles only
99
+ * what it should; its later checks are then still signed for its price, so the
100
+ * account must hold that much more. The minimum is the sum of the prices plus
101
+ * the highest price again. A service that settles what it should refuse can
102
+ * take up to the worst case.
103
+ */
104
+ export interface MainnetFunding {
105
+ /** The prices of the planned endpoints, added up. */
106
+ readonly prices: bigint;
107
+ /** The highest of them. */
108
+ readonly highestPrice: bigint;
109
+ /** `prices` + `highestPrice`: below it the run is refused. */
110
+ readonly minimum: bigint;
111
+ /** The run's own worst case (every signature counted as settled). */
112
+ readonly worstCase: bigint;
113
+ readonly decimals: number;
114
+ /** The payer's USDC as the plan read it; absent in a dry run, which reads no balance. */
115
+ readonly balance?: bigint;
116
+ /**
117
+ * Set on a plan that passed when the balance is at or above the minimum but
118
+ * below the worst case. A refused plan signs nothing, so it has no warning.
119
+ */
120
+ readonly warning?: string;
121
+ }
57
122
  export interface RunPlan {
58
123
  readonly network: string;
59
124
  readonly pin?: PinTerms;
@@ -66,6 +131,12 @@ export interface RunPlan {
66
131
  readonly worstCaseUsd: bigint;
67
132
  /** Set when the run must not start: its worst case is above its cap. Nothing was signed. */
68
133
  readonly refusal?: string;
134
+ /** A mainnet plan only: what it read before planning. */
135
+ readonly mainnet?: MainnetReadings;
136
+ /** The dry run of a mainnet run (`planMainnetDryRun`): no key, so nothing of the payer was read. */
137
+ readonly mainnetDryRun?: true;
138
+ /** A mainnet plan, paying or dry run, with at least one planned endpoint: what the payer must hold. */
139
+ readonly funding?: MainnetFunding;
69
140
  }
70
141
  /**
71
142
  * The plan of a run's x402 payment checks. Throws the guard's refusal for a
@@ -74,6 +145,37 @@ export interface RunPlan {
74
145
  * authorization lifetime) is part of the opt-in, not of this version.
75
146
  */
76
147
  export declare function planX402Run(options: X402PlanOptions): Promise<RunPlan>;
148
+ /** Tests only: where a mainnet plan reads Horizon; undefined puts back the public one. Not exported from the package. */
149
+ export declare function setPubnetHorizonForTesting(base: string | undefined): void;
150
+ export interface MainnetDryRunOptions {
151
+ /** The config environment's pin: required, mainnet USDC to a valid payee. */
152
+ readonly pin?: PinTerms;
153
+ /** A lower per-run cap in dollars. */
154
+ readonly maxRunUsd?: number;
155
+ readonly endpoints: readonly PlanEndpointInput[];
156
+ }
157
+ /**
158
+ * The dry run of a mainnet run on `stellar:pubnet` (spec B5): each endpoint's
159
+ * unpaid challenge, by the mainnet rules (the URL, exact on pubnet, USDC, a
160
+ * lifetime of at most 300 s, $1 a payment), against the caps. It needs no
161
+ * opt-in because it signs nothing, and it reads no key, so nothing of the
162
+ * payer is read: no balance, and no read of the chain, the RPC or Horizon. A
163
+ * paying run makes those reads first, and refuses on any of them.
164
+ */
165
+ export declare function planMainnetDryRun(options: MainnetDryRunOptions): Promise<RunPlan>;
166
+ /**
167
+ * The opening line of a mainnet run (spec B5: a mainnet run says so in its
168
+ * first line): printed when the opt-in opens, before a service is started or
169
+ * the target is asked anything. The network, real funds, the payer, the one
170
+ * payee and the caps; the worst case comes with the plan
171
+ * ({@link mainnetFirstLine}).
172
+ */
173
+ export declare function mainnetOpeningLine(optIn: MainnetOptIn): string;
174
+ /**
175
+ * The first line of every mainnet run (spec B5): the network, real funds, the
176
+ * payer, the one payee, the caps and the run's worst case.
177
+ */
178
+ export declare function mainnetFirstLine(plan: RunPlan): string;
77
179
  /**
78
180
  * The plan for a terminal or a log: the network, the caps, and per endpoint
79
181
  * the destination, the asset, the amount of each signature and the worst case.