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

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 (60) hide show
  1. package/README.md +13 -2
  2. package/dist/baseline.d.ts +3 -1
  3. package/dist/baseline.js +23 -9
  4. package/dist/check.d.ts +1 -1
  5. package/dist/ci-report.js +20 -8
  6. package/dist/config-writer.d.ts +96 -0
  7. package/dist/config-writer.js +281 -0
  8. package/dist/guard/budget.d.ts +7 -4
  9. package/dist/guard/budget.js +11 -4
  10. package/dist/guard/ci-event.d.ts +6 -0
  11. package/dist/guard/ci-event.js +7 -3
  12. package/dist/guard/ci-mainnet.d.ts +59 -0
  13. package/dist/guard/ci-mainnet.js +149 -0
  14. package/dist/guard/horizon.d.ts +30 -0
  15. package/dist/guard/horizon.js +107 -0
  16. package/dist/guard/mainnet-optin.d.ts +3 -1
  17. package/dist/guard/mainnet-optin.js +8 -2
  18. package/dist/guard/mainnet-payer.d.ts +66 -0
  19. package/dist/guard/mainnet-payer.js +92 -0
  20. package/dist/guard/mainnet-plan.d.ts +133 -0
  21. package/dist/guard/mainnet-plan.js +208 -0
  22. package/dist/guard/mainnet-run.d.ts +87 -0
  23. package/dist/guard/mainnet-run.js +225 -0
  24. package/dist/guard/networks.d.ts +9 -8
  25. package/dist/guard/networks.js +21 -10
  26. package/dist/guard/optin.d.ts +106 -0
  27. package/dist/guard/optin.js +202 -0
  28. package/dist/guard/run-ledger.d.ts +212 -0
  29. package/dist/guard/run-ledger.js +426 -0
  30. package/dist/guard/run-lock.d.ts +62 -0
  31. package/dist/guard/run-lock.js +172 -0
  32. package/dist/guard/signed-terms.d.ts +135 -0
  33. package/dist/guard/signed-terms.js +252 -0
  34. package/dist/index.d.ts +18 -7
  35. package/dist/index.js +19 -5
  36. package/dist/mpp/channel-credential.d.ts +13 -1
  37. package/dist/mpp/channel-credential.js +18 -2
  38. package/dist/mpp/channel.d.ts +6 -0
  39. package/dist/mpp/channel.js +7 -3
  40. package/dist/mpp/charge.d.ts +31 -1
  41. package/dist/mpp/charge.js +74 -20
  42. package/dist/mpp/plan.d.ts +77 -0
  43. package/dist/mpp/plan.js +188 -0
  44. package/dist/mpp/suite.d.ts +6 -0
  45. package/dist/mpp/suite.js +2 -1
  46. package/dist/route-reader.d.ts +124 -0
  47. package/dist/route-reader.js +349 -0
  48. package/dist/wallet.d.ts +58 -1
  49. package/dist/wallet.js +128 -0
  50. package/dist/x402/chains/stellar.d.ts +39 -4
  51. package/dist/x402/chains/stellar.js +224 -19
  52. package/dist/x402/chains/svm.js +6 -2
  53. package/dist/x402/chains/types.d.ts +44 -2
  54. package/dist/x402/plan.d.ts +102 -0
  55. package/dist/x402/plan.js +380 -6
  56. package/dist/x402/rejected-request.d.ts +10 -0
  57. package/dist/x402/rejected-request.js +18 -0
  58. package/dist/x402/simulator.d.ts +34 -0
  59. package/dist/x402/simulator.js +461 -50
  60. package/package.json +9 -9
@@ -8,17 +8,37 @@ 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, readStellarPreimage, } 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. */
14
17
  const TRANSACTION_HASH = /^[0-9a-f]{64}$/i;
18
+ /**
19
+ * The address credentials of an authorization entry, in the two forms Wasit
20
+ * signs (CAP-71-02): the legacy `SOROBAN_CREDENTIALS_ADDRESS` and
21
+ * `SOROBAN_CREDENTIALS_ADDRESS_V2`, which carries the same fields and differs
22
+ * only in the payload it is signed over. Undefined for any other form (the
23
+ * source account, and the delegated `..._WITH_DELEGATES`, which is not read).
24
+ */
25
+ function addressCredentials(credentials) {
26
+ switch (credentials.switch().name) {
27
+ case "sorobanCredentialsAddress":
28
+ return { form: "address", value: credentials.address() };
29
+ case "sorobanCredentialsAddressV2":
30
+ return { form: "address-v2", value: credentials.addressV2() };
31
+ default:
32
+ return undefined;
33
+ }
34
+ }
15
35
  /**
16
36
  * Corrupts the client's authorization signature, and nothing else.
17
37
  *
18
38
  * In the `exact` scheme on Stellar the client signs a Soroban authorization
19
39
  * entry, not the envelope: the facilitator signs the envelope later. So the
20
40
  * signature that proves the payer consented is the address credential's
21
- * `signature`, a `Vec<{ public_key, signature }>`. Flipping one byte of it
41
+ * `signature` (legacy or V2), a `Vec<{ public_key, signature }>`. Flipping one byte of it
22
42
  * leaves a transaction that still decodes, carries the same amount, payer and
23
43
  * recipient, and fails only signature verification. A target can refuse it
24
44
  * only by verifying the signature.
@@ -34,10 +54,10 @@ export function corruptAuthSignature(transaction) {
34
54
  if (operation.body().switch().name !== "invokeHostFunction")
35
55
  continue;
36
56
  for (const entry of operation.body().invokeHostFunctionOp().auth()) {
37
- const credentials = entry.credentials();
38
- if (credentials.switch().name !== "sorobanCredentialsAddress")
57
+ const credentials = addressCredentials(entry.credentials());
58
+ if (credentials === undefined)
39
59
  continue;
40
- const signature = credentials.address().signature();
60
+ const signature = credentials.value.signature();
41
61
  if (signature.switch().name !== "scvVec")
42
62
  continue;
43
63
  for (const item of signature.vec() ?? []) {
@@ -130,9 +150,17 @@ async function stellarTokenBalance(network, rpcUrl, payer, asset) {
130
150
  }
131
151
  /**
132
152
  * X402-11 reads (D-032, spec B16.4): the authorization a payment carries, as
133
- * the payer signed it. Only an address credential is read; another form (the
134
- * newer `AddressV2`, one with delegates) is not, and gives no reading rather
135
- * than a guess, since its nonce handling was not read.
153
+ * the payer signed it. An address credential is read, legacy or V2: CAP-71-02
154
+ * gives V2 the same semantics as the legacy credential, with only the signed
155
+ * payload different, and the host stores and consumes the nonce of both the
156
+ * same way, as a TEMPORARY entry keyed by the credential's address and
157
+ * `LedgerKeyNonce { nonce }` (rs-soroban-env v27.0.1,
158
+ * `soroban-env-host/src/auth.rs`, `from_authorization_entry` and
159
+ * `consume_nonce`; read 2026-11-29), which is `nonceKey` below. A PASS of
160
+ * X402-11 also needs the second readings (no transfer to payTo, the payer's
161
+ * balance not fallen by it), so a nonce read the wrong way cannot pass on its
162
+ * own. A delegated credential is not read, and gives no reading rather than a
163
+ * guess.
136
164
  */
137
165
  export function decodeStellarAuthorization(payload) {
138
166
  const transaction = payload["transaction"];
@@ -154,14 +182,14 @@ export function decodeStellarAuthorization(payload) {
154
182
  continue;
155
183
  for (const entry of operation.body().invokeHostFunctionOp().auth()) {
156
184
  const credentials = entry.credentials();
157
- const kind = credentials.switch().name;
158
- if (kind === "sorobanCredentialsSourceAccount")
185
+ if (credentials.switch().name === "sorobanCredentialsSourceAccount")
159
186
  continue;
160
- if (kind !== "sorobanCredentialsAddress") {
187
+ const read = addressCredentials(credentials);
188
+ if (read === undefined) {
161
189
  otherForms += 1;
162
190
  continue;
163
191
  }
164
- const address = credentials.address();
192
+ const address = read.value;
165
193
  found.push({
166
194
  payer: Address.fromScAddress(address.address()).toString(),
167
195
  nonce: address.nonce().toString(),
@@ -170,7 +198,7 @@ export function decodeStellarAuthorization(payload) {
170
198
  }
171
199
  }
172
200
  if (otherForms > 0) {
173
- throw new CheckSetupError("The payment's authorization uses a credential form this check does not read (it reads address credentials), " +
201
+ throw new CheckSetupError("The payment's authorization uses a credential form this check does not read (it reads address credentials, legacy and V2), " +
174
202
  "so whether it was used cannot be read.");
175
203
  }
176
204
  if (found.length !== 1) {
@@ -189,6 +217,43 @@ function nonceKey(authorization) {
189
217
  function rpcServer(rpcUrl) {
190
218
  return new rpc.Server(rpcUrl, { allowHttp: rpcUrl.startsWith("http://") });
191
219
  }
220
+ /**
221
+ * X402-10's lifetime on Stellar, in seconds. The x402 client reads the latest
222
+ * ledger, signs for `maxTimeoutSeconds` past it, and simulates the payment
223
+ * again after signing. With a one-second lifetime (one ledger), a ledger that
224
+ * closed while the client built the payment ended that second simulation with
225
+ * `HostError: Error(Auth, InvalidInput)`, and X402-10 had no verdict: 3 of 5
226
+ * runs with @x402/stellar 2.32.0 on testnet (2026-11-29); the failing runs
227
+ * stopped 9 to 17 s in. 30 s is about five ledgers. The signature stays valid
228
+ * that long, as any payment's does (the RPC that simulates it sees it): it is
229
+ * counted in the run's cap like every signature, for the advertised amount to
230
+ * the checked payee, and Wasit holds it unsent until the chain is past it.
231
+ */
232
+ export const EXPIRED_LIFETIME_SECONDS = 30;
233
+ /** How long X402-10 waits for the chain to pass the payment's expiry: the lifetime and a minute more. */
234
+ export const EXPIRED_WAIT_MS = (EXPIRED_LIFETIME_SECONDS + 60) * 1000;
235
+ /**
236
+ * Resolves once `latest()` reads a ledger past `expiresAt`, where an
237
+ * authorization that expires at `expiresAt` can no longer be used. Throws a
238
+ * CheckSetupError (no verdict) if the chain is not there by `maxWaitMs`: the
239
+ * payment is then not sent, since it might still be valid.
240
+ */
241
+ export async function waitPastLedger(expiresAt, latest, options = {}) {
242
+ const now = options.now ?? Date.now;
243
+ const sleep = options.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
244
+ const maxWaitMs = options.maxWaitMs ?? EXPIRED_WAIT_MS;
245
+ const started = now();
246
+ for (;;) {
247
+ const ledger = await latest();
248
+ if (ledger > expiresAt)
249
+ return;
250
+ if (now() - started >= maxWaitMs) {
251
+ throw new CheckSetupError(`The chain was at ledger ${ledger} after ${Math.round(maxWaitMs / 1000)} s, not yet past ledger ${expiresAt}, ` +
252
+ `where the payment's authorization expires, so it was not sent: it might still have been valid.`);
253
+ }
254
+ await sleep(options.pollMs ?? 2_000);
255
+ }
256
+ }
192
257
  /** The most events read for one X402-11 window: far more than one run makes. */
193
258
  const EVENTS_PAGE = 100;
194
259
  const EVENTS_MAX_PAGES = 20;
@@ -196,7 +261,7 @@ const stellarAuthorizations = {
196
261
  unit: "ledger",
197
262
  unitMs: 5_000,
198
263
  // The x402 Stellar client's own default (DEFAULT_ESTIMATED_LEDGER_SECONDS in
199
- // @x402/stellar 2.28.0); it estimates from recent ledgers when it can.
264
+ // @x402/stellar 2.28.0, and still in 2.32.0); it estimates from recent ledgers when it can.
200
265
  unitSeconds: 5,
201
266
  decode: decodeStellarAuthorization,
202
267
  async read(_network, rpcUrl, authorizations) {
@@ -251,21 +316,161 @@ const stellarAuthorizations = {
251
316
  return { latest: response.latestLedger, transfers };
252
317
  },
253
318
  };
319
+ /**
320
+ * The payer's signer, gated (spec B17.2): each authorization the x402 client
321
+ * asks it to sign is checked against the terms `gate` was armed with, and the
322
+ * key signs only when it authorizes exactly that transfer, once. There is no
323
+ * `signTransaction`: the scheme has the facilitator pay the fees, so the
324
+ * client never signs the envelope.
325
+ */
326
+ function gatedSigner(payerKey, network, gate) {
327
+ const base = createEd25519Signer(payerKey, network);
328
+ const signAuthEntry = async (preimage, opts) => {
329
+ const terms = gate.take();
330
+ if (opts?.address !== undefined && opts.address !== base.address) {
331
+ throw new PaymentGuardRefusedError("signed-terms", "The x402 client asked for a signature for another address than the payer's.");
332
+ }
333
+ if (terms.payer !== base.address) {
334
+ throw new PaymentGuardRefusedError("signed-terms", "The payment's terms name another payer than the key Wasit holds.");
335
+ }
336
+ checkStellarPreimage(preimage, terms);
337
+ const result = await base.signAuthEntry(preimage, opts);
338
+ gate.record({ preimage, signature: Buffer.from(result.signedAuthEntry, "base64") });
339
+ return result;
340
+ };
341
+ return { address: base.address, signAuthEntry };
342
+ }
343
+ /** The `signature` bytes of an address credential signed by one ed25519 key, if it is that shape. */
344
+ function credentialSignature(signature) {
345
+ if (signature.switch().name !== "scvVec")
346
+ return undefined;
347
+ const items = signature.vec() ?? [];
348
+ if (items.length !== 1 || items[0].switch().name !== "scvMap")
349
+ return undefined;
350
+ let publicKey;
351
+ let bytes;
352
+ for (const field of items[0].map() ?? []) {
353
+ if (field.key().switch().name !== "scvSymbol" || field.val().switch().name !== "scvBytes")
354
+ return undefined;
355
+ const key = field.key().sym().toString();
356
+ if (key === "public_key")
357
+ publicKey = Buffer.from(field.val().bytes());
358
+ else if (key === "signature")
359
+ bytes = Buffer.from(field.val().bytes());
360
+ else
361
+ return undefined;
362
+ }
363
+ return publicKey === undefined || bytes === undefined ? undefined : { publicKey, signature: bytes };
364
+ }
365
+ function notSent(message) {
366
+ return new PaymentGuardRefusedError("signed-terms", message, { signed: true });
367
+ }
368
+ const stellarSignedTerms = {
369
+ // The x402 Stellar client's fallback ledger close time (DEFAULT_ESTIMATED_LEDGER_SECONDS in
370
+ // @x402/stellar 2.28.0, and still in 2.32.0), and the shortest it assumes: a faster close only tightens the bound.
371
+ unitSeconds: 5,
372
+ async latestUnit(_network, rpcUrl) {
373
+ return (await rpcServer(rpcUrl).getLatestLedger()).sequence;
374
+ },
375
+ bind(payload, gate) {
376
+ const signed = gate.signed;
377
+ if (signed === undefined) {
378
+ throw new PaymentGuardRefusedError("signed-terms", "The x402 client built a payment without the signature Wasit checked.");
379
+ }
380
+ const checked = readStellarPreimage(signed.preimage);
381
+ if (checked === undefined) {
382
+ throw notSent("The signature Wasit recorded covers a preimage it cannot read back.");
383
+ }
384
+ const transaction = payload["transaction"];
385
+ let envelope;
386
+ try {
387
+ if (typeof transaction !== "string")
388
+ throw new Error("no transaction");
389
+ envelope = xdr.TransactionEnvelope.fromXDR(transaction, "base64");
390
+ }
391
+ catch {
392
+ throw notSent("The payment the x402 client built carries no transaction that decodes.");
393
+ }
394
+ const payer = gate.terms?.payer;
395
+ const operations = envelope.switch().name === "envelopeTypeTx" ? envelope.v1().tx().operations() : [];
396
+ const ours = [];
397
+ for (const operation of operations) {
398
+ if (operation.body().switch().name !== "invokeHostFunction")
399
+ continue;
400
+ for (const entry of operation.body().invokeHostFunctionOp().auth()) {
401
+ if (entry.credentials().switch().name === "sorobanCredentialsSourceAccount")
402
+ continue;
403
+ const read = addressCredentials(entry.credentials());
404
+ if (read === undefined) {
405
+ throw notSent("The payment the x402 client built carries an authorization in a form Wasit did not sign.");
406
+ }
407
+ if (Address.fromScAddress(read.value.address()).toString() === payer)
408
+ ours.push({ entry, ...read });
409
+ }
410
+ }
411
+ if (ours.length !== 1) {
412
+ throw notSent(`The payment the x402 client built carries ${ours.length} authorizations for the payer; Wasit signed one.`);
413
+ }
414
+ const { entry, form, value: credentials } = ours[0];
415
+ // The credential must be the one the signed payload belongs to: a V2 payload
416
+ // under a legacy credential (or the reverse) is a signature the network
417
+ // would check against another payload than the one Wasit signed.
418
+ if (form !== checked.form) {
419
+ throw notSent("The payment the x402 client built carries an authorization in a form Wasit did not sign.");
420
+ }
421
+ if (entry.rootInvocation().toXDR("base64") !== checked.invocation.toXDR("base64")) {
422
+ throw notSent("The payment the x402 client built names another invocation than the one Wasit checked and signed.");
423
+ }
424
+ if (credentials.signatureExpirationLedger() !== checked.signatureExpirationLedger) {
425
+ throw notSent("The payment the x402 client built carries another expiration ledger than the one signed.");
426
+ }
427
+ if (credentials.nonce().toString() !== checked.nonce) {
428
+ throw notSent("The payment the x402 client built carries another nonce than the one signed.");
429
+ }
430
+ const sent = credentialSignature(credentials.signature());
431
+ if (sent === undefined ||
432
+ payer === undefined ||
433
+ !sent.publicKey.equals(Keypair.fromPublicKey(payer).rawPublicKey()) ||
434
+ !sent.signature.equals(signed.signature)) {
435
+ throw notSent("The payment the x402 client built carries another signature than the one Wasit made.");
436
+ }
437
+ },
438
+ };
254
439
  export const stellarChain = {
255
440
  name: "Stellar",
256
441
  networks: ["stellar:testnet", "stellar:pubnet"],
257
442
  payerKeyEnv: "STELLAR_PRIVATE_KEY",
258
443
  referenceKind: "a settled Stellar transaction hash",
259
444
  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));
445
+ // The x402 Stellar client builds its RPC client without `allowHttp`.
446
+ httpsRpcOnly: true,
447
+ registerPayer(client, network, payerKey, rpcUrl, gate, mainnet) {
448
+ // The payment is built and simulated through the run's RPC: the one whose
449
+ // network was checked (D-023), the anchor is read from, and the settlement
450
+ // is read from. On stellar:pubnet only with a live mainnet opt-in whose RPC
451
+ // this is (spec B5 point 4): without one the SDK gets no RPC, and refuses
452
+ // pubnet itself (B-A01).
453
+ const rpcConfig = network === "stellar:testnet" || (network === "stellar:pubnet" && isLiveOptIn(mainnet, network) && mainnet.rpcUrl === rpcUrl)
454
+ ? { url: rpcUrl }
455
+ : undefined;
456
+ client.register("stellar:*", new ExactStellarClientScheme(gatedSigner(payerKey, network, gate), rpcConfig));
263
457
  },
264
- // A one-second lifetime is one ledger (ceil(1 / 5)); ledgers close about
265
- // every 5 to 6 seconds, so 20 seconds is three or more ledgers past it.
266
- expiredSigning: async () => ({ terms: { maxTimeoutSeconds: 1 }, holdMs: 20_000 }),
458
+ signedTerms: stellarSignedTerms,
459
+ // See EXPIRED_LIFETIME_SECONDS: signed to live long enough for the client to finish building it, then
460
+ // sent once the chain is past the ledger it expires at, read from the payload.
461
+ expiredSigning: async () => ({
462
+ terms: { maxTimeoutSeconds: EXPIRED_LIFETIME_SECONDS },
463
+ holdMs: 0,
464
+ untilExpired: async (payload, rpcUrl) => waitPastLedger(decodeStellarAuthorization(payload).expiresAt, async () => (await rpcServer(rpcUrl).getLatestLedger()).sequence),
465
+ }),
267
466
  payerAddress: (payerKey) => Keypair.fromSecret(payerKey).publicKey(),
268
467
  payerBalance: stellarTokenBalance,
468
+ async assetDecimals(network, rpcUrl, asset) {
469
+ if (!StrKey.isValidContract(asset))
470
+ return undefined;
471
+ const decimals = await simulateTokenRead(rpcServer(rpcUrl), networkPassphrase(network), asset, "decimals", []);
472
+ return typeof decimals === "number" ? decimals : undefined;
473
+ },
269
474
  generatePayerKey: () => Keypair.random().secret(),
270
475
  isSettlementReference: (reference) => TRANSACTION_HASH.test(reference),
271
476
  verifySettlement: (_network, rpcUrl, reference, expected) => verifySettlement(rpcUrl, reference, expected),
@@ -171,7 +171,10 @@ async function verifySvmSettlement(rpcUrl, reference, expected) {
171
171
  const lookup = await waitForReceipt(async () => (await rpc
172
172
  .getTransaction(signature(reference), {
173
173
  encoding: "jsonParsed",
174
- maxSupportedTransactionVersion: 0,
174
+ // Version 1 transactions exist since @x402/svm 2.29 (@solana/kit 8): with 0 the RPC refuses
175
+ // to return one ("Transaction version (1) is not supported by the requesting client"), and
176
+ // a compliant settlement had no verdict (issue #22; seen on Solana devnet 2026-11-29).
177
+ maxSupportedTransactionVersion: 1,
175
178
  commitment: "confirmed",
176
179
  })
177
180
  .send()) ?? undefined, () => rpc.getSlot({ commitment: "confirmed" }).send(), { blocks: SLOTS_BEFORE_MISSING });
@@ -214,7 +217,8 @@ async function expiredBlockhash(rpcUrl) {
214
217
  : await rpc
215
218
  .getBlock(old, {
216
219
  commitment: "finalized",
217
- maxSupportedTransactionVersion: 0,
220
+ // The same limit as the settlement read: a block that holds a version 1 transaction is read too.
221
+ maxSupportedTransactionVersion: 1,
218
222
  rewards: false,
219
223
  transactionDetails: "none",
220
224
  })
@@ -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
@@ -26,6 +28,14 @@ export interface ExpiredSigning {
26
28
  readonly terms: AlteredSigning;
27
29
  /** How long to hold the signed payment before sending it. */
28
30
  readonly holdMs: number;
31
+ /**
32
+ * After the hold, waits until the chain is past the payment's own expiry,
33
+ * read from the signed payload (`payload` is its `payload` field), and throws
34
+ * a CheckSetupError (no verdict) if it does not get there in time. Where a
35
+ * chain gives it, the lifetime can be long enough for the client to finish
36
+ * building the payment, and the check still sends it expired.
37
+ */
38
+ readonly untilExpired?: (payload: Record<string, unknown>, rpcUrl: string) => Promise<void>;
29
39
  }
30
40
  /**
31
41
  * One signed authorization of a payment, as the chain records its use
@@ -93,6 +103,24 @@ export interface AuthorizationWatch {
93
103
  readonly transfers: readonly RecordedTransfer[];
94
104
  }>;
95
105
  }
106
+ /**
107
+ * The signed-terms gate of an adapter whose client signs what an RPC returns
108
+ * (spec B17.2, `guard/signed-terms.ts`). An adapter with one signs only
109
+ * through the `SigningGate` that `preparePayment` arms; every network that can
110
+ * be opted into belongs to such an adapter (a test pins it).
111
+ */
112
+ export interface SignedTermsBinding {
113
+ /** The shortest a unit (a ledger) takes, in seconds: the bound counts with it. */
114
+ readonly unitSeconds: number;
115
+ /** The chain's latest unit on `rpcUrl`: read once per run, as the anchor of every expiration bound. */
116
+ latestUnit(network: string, rpcUrl: string): Promise<number>;
117
+ /**
118
+ * Throws `PaymentGuardRefusedError` unless the payment payload's inner
119
+ * `payload` carries exactly the one authorization `gate` let the key sign,
120
+ * with that signature: the payload is then discarded unsent.
121
+ */
122
+ bind(payload: Record<string, unknown>, gate: SigningGate): void;
123
+ }
96
124
  export interface PaymentChain {
97
125
  /** The chain family's name, for reports. */
98
126
  readonly name: string;
@@ -111,9 +139,18 @@ export interface PaymentChain {
111
139
  * Registers this chain's `exact` client scheme, signing with `payerKey`.
112
140
  * `rpcUrl` is for client schemes that read the chain while building a
113
141
  * payment (EVM Permit2 checks the token allowance, Solana fetches the mint
114
- * and a blockhash); others ignore it.
142
+ * and a blockhash); others ignore it. An adapter with `signedTerms` signs
143
+ * only through `gate`; the others ignore it. `mainnet` is the run's opt-in
144
+ * on a mainnet network (spec B5), absent everywhere else.
145
+ */
146
+ registerPayer(client: x402Client, network: string, payerKey: string, rpcUrl: string, gate: SigningGate, mainnet?: MainnetOptIn): void | Promise<void>;
147
+ /**
148
+ * The client builds the payment through the run's RPC and accepts only an
149
+ * https one: an http RPC is refused before anything is asked or sent.
115
150
  */
116
- registerPayer(client: x402Client, network: string, payerKey: string, rpcUrl: string): void | Promise<void>;
151
+ readonly httpsRpcOnly?: boolean;
152
+ /** Present when the payer's signer is gated (see {@link SignedTermsBinding}); `gate` is then the one to sign through. */
153
+ readonly signedTerms?: SignedTermsBinding;
117
154
  /**
118
155
  * How X402-10 makes a payment that has expired when it arrives, for the
119
156
  * option `selected`. Where the client derives the lifetime from
@@ -133,6 +170,11 @@ export interface PaymentChain {
133
170
  * verdict.
134
171
  */
135
172
  payerBalance(network: string, rpcUrl: string, payer: string, asset: string): Promise<bigint | undefined>;
173
+ /**
174
+ * The token's decimals as the chain reports them, read without a key;
175
+ * undefined when there is no clear answer. A mainnet plan reads them (B4).
176
+ */
177
+ assetDecimals?(network: string, rpcUrl: string, asset: string): Promise<number | undefined>;
136
178
  /** Whether `reference` has the shape of a settlement on this chain. */
137
179
  isSettlementReference(reference: string): boolean;
138
180
  /**
@@ -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.