@wasit-dev/core 0.7.0 → 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 (88) hide show
  1. package/README.md +13 -2
  2. package/dist/baseline.d.ts +109 -0
  3. package/dist/baseline.js +353 -0
  4. package/dist/catalogue.js +10 -0
  5. package/dist/check.d.ts +57 -2
  6. package/dist/check.js +46 -6
  7. package/dist/ci-report.d.ts +74 -0
  8. package/dist/ci-report.js +399 -0
  9. package/dist/config-writer.d.ts +96 -0
  10. package/dist/config-writer.js +281 -0
  11. package/dist/config.d.ts +205 -0
  12. package/dist/config.js +1011 -0
  13. package/dist/denied-env.d.ts +33 -0
  14. package/dist/denied-env.js +86 -0
  15. package/dist/errors.d.ts +44 -1
  16. package/dist/errors.js +151 -2
  17. package/dist/guard/budget.d.ts +138 -0
  18. package/dist/guard/budget.js +206 -0
  19. package/dist/guard/ci-event.d.ts +56 -0
  20. package/dist/guard/ci-event.js +129 -0
  21. package/dist/guard/ci-mainnet.d.ts +59 -0
  22. package/dist/guard/ci-mainnet.js +149 -0
  23. package/dist/guard/horizon.d.ts +30 -0
  24. package/dist/guard/horizon.js +107 -0
  25. package/dist/guard/mainnet-payer.d.ts +66 -0
  26. package/dist/guard/mainnet-payer.js +92 -0
  27. package/dist/guard/mainnet-plan.d.ts +133 -0
  28. package/dist/guard/mainnet-plan.js +208 -0
  29. package/dist/guard/mainnet-run.d.ts +87 -0
  30. package/dist/guard/mainnet-run.js +225 -0
  31. package/dist/guard/networks.d.ts +51 -0
  32. package/dist/guard/networks.js +91 -0
  33. package/dist/guard/optin.d.ts +106 -0
  34. package/dist/guard/optin.js +202 -0
  35. package/dist/guard/rpc-identity.d.ts +45 -0
  36. package/dist/guard/rpc-identity.js +156 -0
  37. package/dist/guard/rpc-in-use.d.ts +48 -0
  38. package/dist/guard/rpc-in-use.js +84 -0
  39. package/dist/guard/run-ledger.d.ts +212 -0
  40. package/dist/guard/run-ledger.js +426 -0
  41. package/dist/guard/run-lock.d.ts +62 -0
  42. package/dist/guard/run-lock.js +172 -0
  43. package/dist/guard/signed-terms.d.ts +96 -0
  44. package/dist/guard/signed-terms.js +207 -0
  45. package/dist/index.d.ts +44 -4
  46. package/dist/index.js +42 -2
  47. package/dist/mpp/channel-commitment.d.ts +48 -2
  48. package/dist/mpp/channel-commitment.js +80 -4
  49. package/dist/mpp/channel-credential.d.ts +13 -1
  50. package/dist/mpp/channel-credential.js +21 -2
  51. package/dist/mpp/channel.d.ts +6 -0
  52. package/dist/mpp/channel.js +36 -3
  53. package/dist/mpp/charge.d.ts +33 -1
  54. package/dist/mpp/charge.js +90 -20
  55. package/dist/mpp/network.js +4 -1
  56. package/dist/mpp/plan.d.ts +77 -0
  57. package/dist/mpp/plan.js +188 -0
  58. package/dist/mpp/suite.d.ts +6 -0
  59. package/dist/mpp/suite.js +12 -3
  60. package/dist/report.d.ts +163 -0
  61. package/dist/report.js +282 -0
  62. package/dist/route-reader.d.ts +124 -0
  63. package/dist/route-reader.js +349 -0
  64. package/dist/sanitize.d.ts +52 -0
  65. package/dist/sanitize.js +106 -0
  66. package/dist/settlement.d.ts +14 -0
  67. package/dist/settlement.js +1 -1
  68. package/dist/verdict.d.ts +24 -0
  69. package/dist/verdict.js +46 -0
  70. package/dist/versions.d.ts +50 -0
  71. package/dist/versions.js +123 -0
  72. package/dist/wallet.d.ts +58 -1
  73. package/dist/wallet.js +128 -0
  74. package/dist/x402/chains/evm.js +3 -0
  75. package/dist/x402/chains/index.d.ts +8 -0
  76. package/dist/x402/chains/index.js +13 -2
  77. package/dist/x402/chains/stellar.d.ts +8 -1
  78. package/dist/x402/chains/stellar.js +259 -4
  79. package/dist/x402/chains/types.d.ts +104 -2
  80. package/dist/x402/plan.d.ts +184 -0
  81. package/dist/x402/plan.js +520 -0
  82. package/dist/x402/rejected-request.d.ts +156 -0
  83. package/dist/x402/rejected-request.js +287 -0
  84. package/dist/x402/requirements.d.ts +1 -0
  85. package/dist/x402/requirements.js +37 -4
  86. package/dist/x402/simulator.d.ts +86 -1
  87. package/dist/x402/simulator.js +863 -87
  88. package/package.json +1 -1
@@ -8,8 +8,11 @@ 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
- import { verifySettlement } from "../../settlement.js";
15
+ import { readTransferData, verifySettlement } from "../../settlement.js";
13
16
  /** A Stellar transaction hash: 64 hex characters. */
14
17
  const TRANSACTION_HASH = /^[0-9a-f]{64}$/i;
15
18
  /**
@@ -128,21 +131,272 @@ async function stellarTokenBalance(network, rpcUrl, payer, asset) {
128
131
  })));
129
132
  return entries.length === 0 ? 0n : undefined;
130
133
  }
134
+ /**
135
+ * X402-11 reads (D-032, spec B16.4): the authorization a payment carries, as
136
+ * the payer signed it. Only an address credential is read; another form (the
137
+ * newer `AddressV2`, one with delegates) is not, and gives no reading rather
138
+ * than a guess, since its nonce handling was not read.
139
+ */
140
+ export function decodeStellarAuthorization(payload) {
141
+ const transaction = payload["transaction"];
142
+ if (typeof transaction !== "string") {
143
+ throw new CheckSetupError("The payment payload carries no transaction to read its authorization from.");
144
+ }
145
+ let envelope;
146
+ try {
147
+ envelope = xdr.TransactionEnvelope.fromXDR(transaction, "base64");
148
+ }
149
+ catch {
150
+ throw new CheckSetupError("The payment payload's transaction does not decode, so its authorization cannot be read.");
151
+ }
152
+ const operations = envelope.switch().name === "envelopeTypeTx" ? envelope.v1().tx().operations() : [];
153
+ const found = [];
154
+ let otherForms = 0;
155
+ for (const operation of operations) {
156
+ if (operation.body().switch().name !== "invokeHostFunction")
157
+ continue;
158
+ for (const entry of operation.body().invokeHostFunctionOp().auth()) {
159
+ const credentials = entry.credentials();
160
+ const kind = credentials.switch().name;
161
+ if (kind === "sorobanCredentialsSourceAccount")
162
+ continue;
163
+ if (kind !== "sorobanCredentialsAddress") {
164
+ otherForms += 1;
165
+ continue;
166
+ }
167
+ const address = credentials.address();
168
+ found.push({
169
+ payer: Address.fromScAddress(address.address()).toString(),
170
+ nonce: address.nonce().toString(),
171
+ expiresAt: address.signatureExpirationLedger(),
172
+ });
173
+ }
174
+ }
175
+ if (otherForms > 0) {
176
+ throw new CheckSetupError("The payment's authorization uses a credential form this check does not read (it reads address credentials), " +
177
+ "so whether it was used cannot be read.");
178
+ }
179
+ if (found.length !== 1) {
180
+ throw new CheckSetupError(`The payment carries ${found.length} address authorizations; this check reads exactly one.`);
181
+ }
182
+ return found[0];
183
+ }
184
+ /** The ledger entry the host writes when it consumes the nonce: TEMPORARY contract data of the signer. */
185
+ function nonceKey(authorization) {
186
+ return xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({
187
+ contract: new Address(authorization.payer).toScAddress(),
188
+ key: xdr.ScVal.scvLedgerKeyNonce(new xdr.ScNonceKey({ nonce: xdr.Int64.fromString(authorization.nonce) })),
189
+ durability: xdr.ContractDataDurability.temporary(),
190
+ }));
191
+ }
192
+ function rpcServer(rpcUrl) {
193
+ return new rpc.Server(rpcUrl, { allowHttp: rpcUrl.startsWith("http://") });
194
+ }
195
+ /** The most events read for one X402-11 window: far more than one run makes. */
196
+ const EVENTS_PAGE = 100;
197
+ const EVENTS_MAX_PAGES = 20;
198
+ const stellarAuthorizations = {
199
+ unit: "ledger",
200
+ unitMs: 5_000,
201
+ // The x402 Stellar client's own default (DEFAULT_ESTIMATED_LEDGER_SECONDS in
202
+ // @x402/stellar 2.28.0); it estimates from recent ledgers when it can.
203
+ unitSeconds: 5,
204
+ decode: decodeStellarAuthorization,
205
+ async read(_network, rpcUrl, authorizations) {
206
+ const keys = authorizations.map(nonceKey);
207
+ const response = await rpcServer(rpcUrl).getLedgerEntries(...keys);
208
+ const byKey = new Map(response.entries.map((entry) => [entry.key.toXDR("base64"), entry]));
209
+ return {
210
+ latest: response.latestLedger,
211
+ used: keys.map((key) => {
212
+ const entry = byKey.get(key.toXDR("base64"));
213
+ return entry === undefined ? undefined : (entry.lastModifiedLedgerSeq ?? response.latestLedger);
214
+ }),
215
+ };
216
+ },
217
+ async transfers(_network, rpcUrl, query) {
218
+ const server = rpcServer(rpcUrl);
219
+ const name = xdr.ScVal.scvSymbol("transfer").toXDR("base64");
220
+ const from = new Address(query.from).toScVal().toXDR("base64");
221
+ const to = new Address(query.to).toScVal().toXDR("base64");
222
+ // A Stellar Asset Contract adds the asset as a fourth topic (CAP-67); a SEP-41 token may not.
223
+ const filters = [
224
+ { type: "contract", contractIds: [query.asset], topics: [[name, from, to, "*"], [name, from, to]] },
225
+ ];
226
+ const transfers = [];
227
+ let response = await server.getEvents({ startLedger: query.fromLedger, filters, limit: EVENTS_PAGE });
228
+ for (let page = 1;; page += 1) {
229
+ for (const event of response.events) {
230
+ // Only an event the RPC marks as from a failed call is left out. The testnet RPC no
231
+ // longer sends the field at all (observed 2026-11-16, run of slice 4's live check):
232
+ // reading its absence as "failed" dropped every transfer.
233
+ if (event.inSuccessfulContractCall === false)
234
+ continue;
235
+ const [topic, sender, receiver] = event.topic;
236
+ if (topic?.switch().name !== "scvSymbol" || topic.sym().toString() !== "transfer")
237
+ continue;
238
+ if (sender === undefined || receiver === undefined)
239
+ continue;
240
+ if (Address.fromScVal(sender).toString() !== query.from || Address.fromScVal(receiver).toString() !== query.to)
241
+ continue;
242
+ const data = readTransferData(event.value);
243
+ if (data === undefined)
244
+ continue;
245
+ transfers.push({ amount: data.amount, reference: event.txHash, ledger: event.ledger });
246
+ }
247
+ if (response.events.length < EVENTS_PAGE)
248
+ break;
249
+ // Never a partial answer read as complete.
250
+ if (page >= EVENTS_MAX_PAGES)
251
+ throw new Error("more transfer events than can be read in full");
252
+ response = await server.getEvents({ cursor: response.cursor, filters, limit: EVENTS_PAGE });
253
+ }
254
+ return { latest: response.latestLedger, transfers };
255
+ },
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
+ };
131
369
  export const stellarChain = {
132
370
  name: "Stellar",
133
371
  networks: ["stellar:testnet", "stellar:pubnet"],
134
372
  payerKeyEnv: "STELLAR_PRIVATE_KEY",
135
373
  referenceKind: "a settled Stellar transaction hash",
136
374
  resolveRpcUrl: (network, override) => resolveRpcUrl(network, override),
137
- registerPayer(client, network, payerKey, _rpcUrl) {
138
- const signer = createEd25519Signer(payerKey, network);
139
- 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));
140
387
  },
388
+ signedTerms: stellarSignedTerms,
141
389
  // A one-second lifetime is one ledger (ceil(1 / 5)); ledgers close about
142
390
  // every 5 to 6 seconds, so 20 seconds is three or more ledgers past it.
143
391
  expiredSigning: async () => ({ terms: { maxTimeoutSeconds: 1 }, holdMs: 20_000 }),
144
392
  payerAddress: (payerKey) => Keypair.fromSecret(payerKey).publicKey(),
145
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
+ },
146
400
  generatePayerKey: () => Keypair.random().secret(),
147
401
  isSettlementReference: (reference) => TRANSACTION_HASH.test(reference),
148
402
  verifySettlement: (_network, rpcUrl, reference, expected) => verifySettlement(rpcUrl, reference, expected),
@@ -150,4 +404,5 @@ export const stellarChain = {
150
404
  ...payload,
151
405
  transaction: corruptAuthSignature(payload["transaction"]),
152
406
  }),
407
+ authorizations: stellarAuthorizations,
153
408
  };
@@ -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
@@ -27,6 +29,90 @@ export interface ExpiredSigning {
27
29
  /** How long to hold the signed payment before sending it. */
28
30
  readonly holdMs: number;
29
31
  }
32
+ /**
33
+ * One signed authorization of a payment, as the chain records its use
34
+ * (X402-11, D-032). Decoded from what the payer signed, never computed.
35
+ */
36
+ export interface SignedAuthorization {
37
+ /** The address that signed it. X402-11 holds it to the run's payer. */
38
+ readonly payer: string;
39
+ /** Its single-use id on the chain (on Stellar the auth entry's nonce), as text. */
40
+ readonly nonce: string;
41
+ /** The last ledger (or block) it can be used in, as signed. */
42
+ readonly expiresAt: number;
43
+ }
44
+ /** One read of the chain about some authorizations, all at the same state. */
45
+ export interface AuthorizationRead {
46
+ /** The chain's latest closed ledger when it answered. */
47
+ readonly latest: number;
48
+ /**
49
+ * Per authorization asked for, in order: the ledger its use was recorded in,
50
+ * or undefined when the chain holds no record of a use.
51
+ */
52
+ readonly used: readonly (number | undefined)[];
53
+ }
54
+ /** A transfer the chain recorded, as X402-11's second reading counts it. */
55
+ export interface RecordedTransfer {
56
+ readonly amount: bigint;
57
+ /** The transaction that made it (a hash), for the report. */
58
+ readonly reference: string;
59
+ readonly ledger: number;
60
+ }
61
+ /**
62
+ * How X402-11 reads whether an authorization was used, on chains where that
63
+ * can be read directly. A chain without one does not run X402-11.
64
+ */
65
+ export interface AuthorizationWatch {
66
+ /** What the chain's unit of time is called in a report: "ledger". */
67
+ readonly unit: string;
68
+ /** About how long one unit lasts, in milliseconds: the watch reads once per unit. */
69
+ readonly unitMs: number;
70
+ /**
71
+ * The seconds one unit counts for when a client turns an advertised lifetime
72
+ * into an expiration (the lifetime divided by this, rounded up). X402-11 does
73
+ * not send an authorization that outlives its 300 s by more than that count.
74
+ */
75
+ readonly unitSeconds: number;
76
+ /**
77
+ * The authorization a payment payload's inner `payload` carries. Throws
78
+ * `CheckSetupError` when it carries none that can be read, or more than one.
79
+ */
80
+ decode(payload: Record<string, unknown>): SignedAuthorization;
81
+ /** Whether each authorization was used, read in one call, so all at one state of the chain. */
82
+ read(network: string, rpcUrl: string, authorizations: readonly SignedAuthorization[]): Promise<AuthorizationRead>;
83
+ /**
84
+ * Every successful transfer of `asset` from `from` to `to` recorded from
85
+ * ledger `fromLedger` on. Throws when the chain cannot serve that range in
86
+ * full: a partial answer is never read as "no transfer".
87
+ */
88
+ transfers(network: string, rpcUrl: string, query: {
89
+ readonly asset: string;
90
+ readonly from: string;
91
+ readonly to: string;
92
+ readonly fromLedger: number;
93
+ }): Promise<{
94
+ readonly latest: number;
95
+ readonly transfers: readonly RecordedTransfer[];
96
+ }>;
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
+ }
30
116
  export interface PaymentChain {
31
117
  /** The chain family's name, for reports. */
32
118
  readonly name: string;
@@ -45,9 +131,18 @@ export interface PaymentChain {
45
131
  * Registers this chain's `exact` client scheme, signing with `payerKey`.
46
132
  * `rpcUrl` is for client schemes that read the chain while building a
47
133
  * payment (EVM Permit2 checks the token allowance, Solana fetches the mint
48
- * 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.
49
142
  */
50
- 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;
51
146
  /**
52
147
  * How X402-10 makes a payment that has expired when it arrives, for the
53
148
  * option `selected`. Where the client derives the lifetime from
@@ -67,6 +162,11 @@ export interface PaymentChain {
67
162
  * verdict.
68
163
  */
69
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>;
70
170
  /** Whether `reference` has the shape of a settlement on this chain. */
71
171
  isSettlementReference(reference: string): boolean;
72
172
  /**
@@ -81,4 +181,6 @@ export interface PaymentChain {
81
181
  * signature to corrupt.
82
182
  */
83
183
  corruptPayload(payload: Record<string, unknown>): Record<string, unknown>;
184
+ /** X402-11's chain reads. Absent: X402-11 is skipped on this chain, nothing signed. */
185
+ readonly authorizations?: AuthorizationWatch;
84
186
  }
@@ -0,0 +1,184 @@
1
+ /**
2
+ * L1, the plan (spec B3, B4): before anything is signed, read each endpoint's
3
+ * unpaid challenge and work out what the run's payment checks would sign, and
4
+ * refuse what the caps or the pin do not allow.
5
+ *
6
+ * The plan is what `--dry-run` prints, and what a paying run hands to each
7
+ * endpoint's checks: L2 then refuses any signature the plan did not allow, so
8
+ * a service that raises its price or changes its payee between the plan and
9
+ * the payment gets a refusal, not a signature.
10
+ *
11
+ * It sends no payment, reads no key and signs nothing.
12
+ *
13
+ * 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.
19
+ */
20
+ import { type MainnetOptIn } from "../guard/optin.js";
21
+ import { type PinTerms, type PlannedSignature } from "../guard/budget.js";
22
+ import { type RejectCase } from "./rejected-request.js";
23
+ import { type RequestShape } from "./simulator.js";
24
+ export interface PlanEndpointInput extends RequestShape {
25
+ readonly name: string;
26
+ readonly target: string;
27
+ /** The request the service must refuse: X402-11 signs once more, when it can run. */
28
+ readonly reject?: RejectCase;
29
+ }
30
+ export interface X402PlanOptions {
31
+ readonly network: string;
32
+ readonly pin?: PinTerms;
33
+ /** A lower per-run cap in dollars. */
34
+ readonly maxRunUsd?: number;
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;
61
+ }
62
+ /** The option an endpoint's checks would pay, as its challenge stated it. */
63
+ export interface PlannedOption {
64
+ readonly scheme: string;
65
+ readonly network: string;
66
+ readonly payTo: string;
67
+ readonly asset: string;
68
+ /** Base units. */
69
+ readonly amount: bigint;
70
+ readonly maxTimeoutSeconds: number;
71
+ }
72
+ export type EndpointPlanStatus =
73
+ /** Its payment checks would sign `signatures`. */
74
+ "planned"
75
+ /** Its payment checks would not pay at all (no option to pay, an unreadable challenge): `reason`. */
76
+ | "not-paid"
77
+ /** The guard refuses to pay it: `reason`. */
78
+ | "refused";
79
+ export interface EndpointPlan {
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;
87
+ readonly status: EndpointPlanStatus;
88
+ readonly reason?: string;
89
+ readonly option?: PlannedOption;
90
+ readonly signatures: readonly PlannedSignature[];
91
+ /** Base units of `option.asset`. */
92
+ readonly worstCase: bigint;
93
+ /** Dollar units of `guard/budget.ts`; format with `formatUsd`. */
94
+ readonly worstCaseUsd: bigint;
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
+ }
122
+ export interface RunPlan {
123
+ readonly network: string;
124
+ readonly pin?: PinTerms;
125
+ readonly perPaymentCapUsd: bigint;
126
+ readonly capUsd: bigint;
127
+ /** Lowered by maxRunUsd. */
128
+ readonly capLowered: boolean;
129
+ readonly endpoints: readonly EndpointPlan[];
130
+ /** The sum over the planned endpoints. */
131
+ readonly worstCaseUsd: bigint;
132
+ /** Set when the run must not start: its worst case is above its cap. Nothing was signed. */
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;
140
+ }
141
+ /**
142
+ * The plan of a run's x402 payment checks. Throws the guard's refusal for a
143
+ * network that is not a test network (L0), before any request; the mainnet
144
+ * plan (the payer's balance, the token's decimals read on chain, the
145
+ * authorization lifetime) is part of the opt-in, not of this version.
146
+ */
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;
179
+ /**
180
+ * The plan for a terminal or a log: the network, the caps, and per endpoint
181
+ * the destination, the asset, the amount of each signature and the worst case.
182
+ * Sanitised; no header value and no key (the plan holds neither).
183
+ */
184
+ export declare function describePlan(plan: RunPlan): string[];