@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
@@ -1,9 +1,13 @@
1
1
  import { errored, quoteValue, skipped } from "../check.js";
2
2
  import { CheckSetupError, ConfigurationError, MalformedResponseError, assertHttpUrl, fetchPaymentChallenge, fetchTarget, } from "../errors.js";
3
- import { PER_PAYMENT_CAP_USD, PaymentGuardRefusedError, RunBudget, assertPinned, sameAddress, } from "../guard/budget.js";
4
- import { assertPaymentNetworkAllowed } from "../guard/networks.js";
5
- import { assertRpcServesNetwork } from "../guard/rpc-identity.js";
6
- import { REJECTED_REQUEST_ID, REJECTED_REQUEST_MAX_LIFETIME_SECONDS, REJECTED_REQUEST_MIN_LIFETIME_SECONDS, REJECTED_REQUEST_MIN_UNITS_LEFT, REJECTED_REQUEST_NAME, rejectRequestShape, rejectedRequestHardStopMs, rejectedRequestVerdict, watchAuthorization, } from "./rejected-request.js";
3
+ import { PER_PAYMENT_CAP_USD, PaymentGuardRefusedError, RunBudget, assertPinned, sameAddress, shown, } from "../guard/budget.js";
4
+ import { MainnetPlanRefusedError, assertMainnetOption, paidUrlOf } from "../guard/mainnet-plan.js";
5
+ import { PaymentNetworkRefusedError, assertPaymentNetworkAllowed } from "../guard/networks.js";
6
+ import { MainnetRunRefusedError, anchorOfOptIn, isLiveOptIn } from "../guard/optin.js";
7
+ import { SigningAnchor, SigningGate, expirationOfSigned } from "../guard/signed-terms.js";
8
+ import { RunLedgerError } from "../guard/run-ledger.js";
9
+ import { RpcIdentityError, assertRpcServesNetwork } from "../guard/rpc-identity.js";
10
+ import { REJECTED_REQUEST_ID, REJECTED_REQUEST_MAX_LIFETIME_SECONDS, REJECTED_REQUEST_MIN_LIFETIME_SECONDS, REJECTED_REQUEST_MIN_UNITS_LEFT, REJECTED_REQUEST_NAME, rejectRequestShape, rejectedRequestHardStopMs, rejectedRequestSettlement, rejectedRequestVerdict, watchAuthorization, } from "./rejected-request.js";
7
11
  import { sanitizeText } from "../sanitize.js";
8
12
  import { checkNetworkIdentifier, checkRequiredFields } from "./requirements.js";
9
13
  const BODYLESS_METHODS = new Set(["GET", "HEAD"]);
@@ -21,8 +25,10 @@ const KNOWN_METHODS = new Set([
21
25
  *
22
26
  * A bad method, or a body on a verb that cannot carry one, is a configuration
23
27
  * error rather than a finding: nothing has been learned about the target.
28
+ * Exported for `wasit init`'s unpaid request (route-reader.ts), which sends
29
+ * the route what the read checks send it.
24
30
  */
25
- function buildInit(shape) {
31
+ export function buildInit(shape) {
26
32
  const method = (shape.method ?? "GET").toUpperCase();
27
33
  if (!KNOWN_METHODS.has(method)) {
28
34
  throw new ConfigurationError(`"${shape.method}" is not an HTTP method. Expected one of ` +
@@ -303,6 +309,28 @@ class PaymentNotAttemptedError extends Error {
303
309
  this.name = "PaymentNotAttemptedError";
304
310
  }
305
311
  }
312
+ /**
313
+ * The route answered 409 where a 402 challenge was asked for: a single-use
314
+ * resource that a payment has used up (spec B8). Nothing is paid for it.
315
+ * Before any payment of the run it is one more reason no payment was attempted
316
+ * (X402-06 and the plan read it so); after X402-06's payment was accepted the
317
+ * negative checks that need a new challenge are skipped as "resource consumed".
318
+ */
319
+ class ResourceConsumedError extends PaymentNotAttemptedError {
320
+ constructor() {
321
+ super("the target answered 409 instead of a 402 challenge: a single-use resource that is already used up, so no " +
322
+ "payment was attempted (see X402-01).");
323
+ this.name = "ResourceConsumedError";
324
+ }
325
+ }
326
+ /** The status a single-use resource answers once it is used up (spec B8). */
327
+ const RESOURCE_CONSUMED_STATUS = 409;
328
+ /** The one negative check that needs no new challenge: it sends X402-06's payment again. */
329
+ const REPLAY_CHECK = "X402-08";
330
+ /** Why a negative check is skipped once a new challenge drew a 409 after X402-06's payment was accepted. */
331
+ const RESOURCE_CONSUMED_REASON = "resource consumed: the route answered 409 to a new request after X402-06's payment was accepted, a single-use resource that the " +
332
+ "payment used up, so this check has no new challenge to pay, and nothing was signed for it. X402-08, the replay, " +
333
+ "needs no new challenge and still runs.";
306
334
  /**
307
335
  * No payment adapter pays on this network, so the payment checks cannot be
308
336
  * graded here. A `ConfigurationError`, so a caller that does not know the class
@@ -331,13 +359,13 @@ function chainFor(network) {
331
359
  throw new UnsupportedPaymentNetworkError(network);
332
360
  return chain;
333
361
  }
334
- async function buildX402Client(chain, network, payerSecretKey, rpcUrl, pin) {
362
+ async function buildX402Client(chain, network, payerSecretKey, rpcUrl, pin, gate, mainnet) {
335
363
  const client = new x402Client();
336
364
  // L3 (spec B3): the SDK's own spend controls, set here rather than left to
337
365
  // its default, as a second implementation of the $1 cap. An adapter that
338
366
  // allows more assets replaces them and states the cap again (`evm.ts`).
339
367
  client.setSpendControls({ maxAmountPerPayment: `$${PER_PAYMENT_CAP_USD}` });
340
- await chain.registerPayer(client, network, payerSecretKey, rpcUrl);
368
+ await chain.registerPayer(client, network, payerSecretKey, rpcUrl, gate, mainnet);
341
369
  client
342
370
  // A challenge may offer several networks, including both Stellar ones.
343
371
  // The client's default pick is the first it supports, which would sign
@@ -406,6 +434,11 @@ export async function readPaymentChallenge(options) {
406
434
  /** The terms of a challenge already fetched, by the rules of {@link readPaymentChallenge}. */
407
435
  async function paymentTerms(challenge, network) {
408
436
  const options = { network };
437
+ // B8: a single-use resource answers 409 once it is used up. Said as that, before its headers are read as a challenge.
438
+ if (challenge.status === RESOURCE_CONSUMED_STATUS) {
439
+ await challenge.body?.cancel().catch(() => undefined);
440
+ throw new ResourceConsumedError();
441
+ }
409
442
  let paymentRequired;
410
443
  try {
411
444
  paymentRequired = new x402HTTPClient(new x402Client()).getPaymentRequiredResponse((name) => challenge.headers.get(name));
@@ -480,6 +513,72 @@ function plannedAmount(plan, check, selected) {
480
513
  }
481
514
  return entry.amount;
482
515
  }
516
+ /**
517
+ * Refuses an RPC an x402 payment on `network` cannot be built through, then
518
+ * checks that it serves `network` (D-023). On Stellar the client accepts only
519
+ * an https RPC. Throws `RpcIdentityError` (a configuration error) before the
520
+ * target is sent anything; the RPC's address is never echoed (it may carry a
521
+ * key). The CLI calls it before it starts a service.
522
+ */
523
+ export async function assertX402PaymentRpc(network, rpcUrl) {
524
+ const chain = paymentChainFor(network);
525
+ if (chain?.httpsRpcOnly === true) {
526
+ let protocol = "";
527
+ try {
528
+ protocol = new URL(rpcUrl).protocol;
529
+ }
530
+ catch {
531
+ protocol = "";
532
+ }
533
+ if (protocol !== "https:") {
534
+ throw new RpcIdentityError(`The x402 ${chain.name} client builds the payment through the run's RPC and accepts only an https RPC, ` +
535
+ `and this run's RPC is not https. No payment was sent and nothing was signed.`);
536
+ }
537
+ }
538
+ await assertRpcServesNetwork(network, rpcUrl);
539
+ }
540
+ /** The run's anchor for expiration bounds, one per run budget (a run shares one budget across endpoints). */
541
+ const anchors = new WeakMap();
542
+ function anchorOf(budget) {
543
+ let anchor = anchors.get(budget);
544
+ if (anchor === undefined) {
545
+ anchor = new SigningAnchor();
546
+ anchors.set(budget, anchor);
547
+ }
548
+ return anchor;
549
+ }
550
+ /**
551
+ * The terms the gate is armed with: those L2 checked and charged, and the
552
+ * latest ledger the signature may expire at. The run's first signature reads
553
+ * the chain's latest ledger as the anchor; nothing is signed when it cannot.
554
+ */
555
+ async function signingTerms(binding, network, rpcUrl, anchor, payer, signing, readIfMissing) {
556
+ if (anchor.reading === undefined) {
557
+ // A mainnet run's anchor is read in its plan, beside public Horizon's latest ledger (B17.2), never here.
558
+ if (!readIfMissing) {
559
+ throw new PaymentGuardRefusedError("plan", "The mainnet run's latest ledger was not read in its plan, so no expiration can be bounded.");
560
+ }
561
+ let latest;
562
+ try {
563
+ latest = await binding.latestUnit(network, rpcUrl);
564
+ }
565
+ catch (error) {
566
+ throw new CheckSetupError(`The chain's latest ledger could not be read before signing (${error.message}). Nothing was signed.`);
567
+ }
568
+ if (!Number.isSafeInteger(latest) || latest <= 0) {
569
+ throw new CheckSetupError("The chain's latest ledger could not be read before signing. Nothing was signed.");
570
+ }
571
+ anchor.set(latest);
572
+ }
573
+ return {
574
+ network,
575
+ payer,
576
+ asset: signing.asset,
577
+ payTo: signing.payTo,
578
+ amount: signing.amount,
579
+ maxExpiration: anchor.maxExpiration(binding.unitSeconds, signing.maxTimeoutSeconds),
580
+ };
581
+ }
483
582
  /**
484
583
  * Reads the challenge and produces a signed payment payload for it.
485
584
  *
@@ -494,17 +593,56 @@ function plannedAmount(plan, check, selected) {
494
593
  * L2 (spec B3) is here, between the fresh challenge and the SDK: the pin over
495
594
  * every `exact` option, the plan, the $1 cap and the run's cap, the run charged
496
595
  * before the signature. The SDK is then handed exactly the one option checked,
497
- * and a payload whose `accepted` is not that option is discarded unsent.
596
+ * and a payload whose `accepted` is not that option is discarded unsent. On a
597
+ * chain with a signed-terms gate (Stellar), the key signs only an
598
+ * authorization for those same terms, and a payload that carries anything
599
+ * else is discarded unsent.
600
+ *
601
+ * On mainnet (a live opt-in, spec B5) the fresh terms are also held to the
602
+ * mainnet rules (exact, USDC, a lifetime of at most 300 s), the ledger is the
603
+ * opt-in's, the anchor is the one its plan read, and a refusal here stops the
604
+ * whole run (B3): nothing more is signed in it.
498
605
  */
499
606
  async function preparePayment(options, check, alter, beforeSigning) {
500
607
  // L0 again at the one function every x402 signature goes through, whoever
501
608
  // reaches it: nothing is fetched or signed on a network that is not a test
502
- // network.
503
- assertPaymentNetworkAllowed("x402", options.network);
609
+ // network, but stellar:pubnet with a live mainnet opt-in.
610
+ assertPaymentNetworkAllowed("x402", options.network, options.mainnet);
611
+ const mainnet = isLiveOptIn(options.mainnet, options.network) ? options.mainnet : undefined;
612
+ if (mainnet === undefined)
613
+ return signPayment(options, check, undefined, alter, beforeSigning);
614
+ try {
615
+ return await signPayment(options, check, mainnet, alter, beforeSigning);
616
+ }
617
+ catch (error) {
618
+ if (isGuardRefusal(error))
619
+ mainnet.stop(error.message);
620
+ throw error;
621
+ }
622
+ }
623
+ /** A refusal of Wasit's own guard, the ledger's included: on mainnet it stops the whole run (B3). */
624
+ function isGuardRefusal(error) {
625
+ return (error instanceof PaymentGuardRefusedError ||
626
+ error instanceof PaymentNetworkRefusedError ||
627
+ error instanceof MainnetPlanRefusedError ||
628
+ error instanceof MainnetRunRefusedError ||
629
+ error instanceof RunLedgerError);
630
+ }
631
+ async function signPayment(options, check, mainnet, alter, beforeSigning) {
504
632
  const chain = chainFor(options.network);
505
633
  const budget = options.budget ?? new RunBudget();
506
- const { client, httpClient } = await buildX402Client(chain, options.network, options.payerSecretKey, chain.resolveRpcUrl(options.network, options.rpcUrl), options.pin);
634
+ if (mainnet !== undefined && (budget !== mainnet.budget || options.ledger === undefined || chain.signedTerms === undefined)) {
635
+ throw new MainnetRunRefusedError("run", `${check} on mainnet pays only through the run's own budget and ledger, with a signer that signs only the checked terms.`, { during: true });
636
+ }
637
+ const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
638
+ const gate = new SigningGate();
639
+ const { client, httpClient } = await buildX402Client(chain, options.network, options.payerSecretKey, rpcUrl, options.pin, gate, mainnet);
507
640
  const { paymentRequired, selected, idempotent, payUrl } = await readPaymentChallenge(options);
641
+ // On mainnet a payment goes to the one URL the plan recorded, never to one the service sends it to later.
642
+ if (mainnet !== undefined && (options.plan?.url === undefined || paidUrlOf(payUrl) !== options.plan.url)) {
643
+ throw new PaymentGuardRefusedError("plan", `${check} would pay ${shown(paidUrlOf(payUrl))}, not the URL the plan recorded for this endpoint: the service ` +
644
+ `sent the request elsewhere after the plan.`);
645
+ }
508
646
  // L2, before anything is built: the service may change its challenge between
509
647
  // requests, so the plan alone is not enough.
510
648
  assertPinned(options.network, paymentRequired.accepts, options.pin);
@@ -515,6 +653,10 @@ async function preparePayment(options, check, alter, beforeSigning) {
515
653
  throw new PaymentGuardRefusedError("accepted", `${check} would sign different ${field} terms than the target's.`);
516
654
  }
517
655
  }
656
+ // The mainnet rules on the terms about to be signed, not only on the plan's:
657
+ // a lifetime raised after the plan is refused here (B3, L2).
658
+ if (mainnet !== undefined)
659
+ assertMainnetOption(signing);
518
660
  budget.charge({
519
661
  check,
520
662
  network: options.network,
@@ -522,16 +664,106 @@ async function preparePayment(options, check, alter, beforeSigning) {
522
664
  amount: signing.amount,
523
665
  ...(planned === undefined ? {} : { planned }),
524
666
  });
525
- await beforeSigning?.(selected);
526
- const signed = await withinSpendControls(options.network, selected, () => client.createPaymentPayload({ ...paymentRequired, accepts: [signing] }));
527
- // What the SDK says it signed must be the option checked, field by field;
528
- // otherwise the payload is discarded here, unsent. It stays charged.
529
- if (canonical(signed.accepted) !== canonical(signing)) {
530
- throw new PaymentGuardRefusedError("accepted", `The payment the x402 client built for ${check} names other terms in its accepted field than the ` +
531
- `option Wasit checked.`, { signed: true });
667
+ // The run ledger (spec B5): the intent is on disk before the key can be asked
668
+ // to sign. A ledger that cannot take it throws here, and nothing is signed.
669
+ const entry = options.ledger?.intent({
670
+ check,
671
+ network: options.network,
672
+ asset: signing.asset,
673
+ payTo: signing.payTo,
674
+ amount: signing.amount,
675
+ });
676
+ let asked = false;
677
+ let signed;
678
+ try {
679
+ await beforeSigning?.(selected);
680
+ // The signed-terms gate (spec B17.2): the key signs only what was checked and
681
+ // charged above, once, within this payment's lifetime.
682
+ if (chain.signedTerms !== undefined) {
683
+ gate.arm(await signingTerms(chain.signedTerms, options.network, rpcUrl, mainnet === undefined ? anchorOf(budget) : anchorOfOptIn(mainnet), chain.payerAddress(options.payerSecretKey), signing, mainnet === undefined));
684
+ }
685
+ asked = true;
686
+ signed = await withinSpendControls(options.network, selected, () => client.createPaymentPayload({ ...paymentRequired, accepts: [signing] }));
687
+ }
688
+ catch (error) {
689
+ recordUnsigned(entry, chain, gate, asked, error);
690
+ throw error;
691
+ }
692
+ // Recorded before the payload can be used: a signature the ledger cannot
693
+ // take is never sent.
694
+ entry?.signed(gate.signed === undefined ? undefined : expirationOfSigned(gate.signed));
695
+ try {
696
+ // What the SDK says it signed must be the option checked, field by field;
697
+ // otherwise the payload is discarded here, unsent. It stays charged.
698
+ if (canonical(signed.accepted) !== canonical(signing)) {
699
+ throw new PaymentGuardRefusedError("accepted", `The payment the x402 client built for ${check} names other terms in its accepted field than the ` +
700
+ `option Wasit checked.`, { signed: true });
701
+ }
702
+ // And what it carries must be the one authorization the gate let the key sign.
703
+ chain.signedTerms?.bind(signed.payload, gate);
704
+ }
705
+ catch (error) {
706
+ recordDiscarded(entry, error);
707
+ throw error;
532
708
  }
533
709
  const paymentPayload = alter === undefined ? signed : { ...signed, accepted: selected };
534
- return { httpClient, paymentPayload, selected, idempotent, payUrl };
710
+ return { httpClient, paymentPayload, selected, idempotent, payUrl, entry };
711
+ }
712
+ function reasonOf(error) {
713
+ return error instanceof Error ? error.message : String(error);
714
+ }
715
+ /**
716
+ * What became of a payment that failed before its payload was built. With
717
+ * the gate armed, only a signature the gate recorded was made: the gate is the
718
+ * only way to the key. Without a gate (EVM and Solana, test networks only),
719
+ * a client that failed once it was asked may have signed. A ledger that cannot
720
+ * take the outcome leaves the intent, which reads as signed.
721
+ */
722
+ function recordUnsigned(entry, chain, gate, asked, error) {
723
+ if (entry === undefined)
724
+ return;
725
+ try {
726
+ if (gate.signed !== undefined)
727
+ entry.signed(expirationOfSigned(gate.signed));
728
+ else if (!asked || chain.signedTerms !== undefined)
729
+ entry.notSigned(reasonOf(error));
730
+ else
731
+ entry.unknown(reasonOf(error));
732
+ }
733
+ catch {
734
+ // The payment's own error is what the check reports; the intent stays.
735
+ }
736
+ }
737
+ /** A signed payload discarded unsent. A ledger that cannot take it leaves "signed", which reads as sent. */
738
+ function recordDiscarded(entry, error) {
739
+ try {
740
+ entry?.discarded(reasonOf(error));
741
+ }
742
+ catch {
743
+ // The payment's own error is what the check reports.
744
+ }
745
+ }
746
+ /**
747
+ * Sends a signed payment and records it in the run ledger: the answer's
748
+ * status, or that no answer came (the payment may still have reached the
749
+ * service). The ledger's own text, never the service's.
750
+ */
751
+ async function sendPayment(entry, url, init) {
752
+ let response;
753
+ try {
754
+ response = await fetchTarget(url, init);
755
+ }
756
+ catch (error) {
757
+ try {
758
+ entry?.sent({ error: "no answer: the payment may have reached the service" });
759
+ }
760
+ catch {
761
+ // The send's own error is what the check reports.
762
+ }
763
+ throw error;
764
+ }
765
+ entry?.sent({ status: response.status });
766
+ return response;
535
767
  }
536
768
  /**
537
769
  * Reads the settlement a paid response reports, before anything is looked up.
@@ -609,9 +841,9 @@ async function checkSignatureAccepted(options) {
609
841
  const id = "X402-06";
610
842
  const name = "Signature Resubmit Accepted";
611
843
  const fail = (detail, hint) => ({ id, name, pass: false, detail, hint });
612
- const { httpClient, paymentPayload, idempotent, payUrl } = await preparePayment(options, "X402-06", undefined, (selected) => assertPayerCanPay(options, selected));
844
+ const { httpClient, paymentPayload, idempotent, payUrl, entry } = await preparePayment(options, "X402-06", undefined, (selected) => assertPayerCanPay(options, selected));
613
845
  const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);
614
- const paid = await fetchTarget(payUrl, withPaymentHeaders(options, paymentHeaders));
846
+ const paid = await sendPayment(entry, payUrl, withPaymentHeaders(options, paymentHeaders));
615
847
  const honest = (result, accepted) => ({
616
848
  result,
617
849
  accepted,
@@ -660,6 +892,7 @@ async function checkSignatureAccepted(options) {
660
892
  recipient: accepted.payTo,
661
893
  payer: chain.payerAddress(options.payerSecretKey),
662
894
  });
895
+ entry?.settled(reference, verdict.pass);
663
896
  return honest(verdict.pass
664
897
  ? {
665
898
  id,
@@ -687,13 +920,13 @@ async function checkSignatureAccepted(options) {
687
920
  * answer: anything that prevents one produces no verdict.
688
921
  */
689
922
  async function checkInvalidSignatureRejected(options) {
690
- const { httpClient, paymentPayload, payUrl } = await preparePayment(options, "X402-07");
923
+ const { httpClient, paymentPayload, payUrl, entry } = await preparePayment(options, "X402-07");
691
924
  const corrupted = {
692
925
  ...paymentPayload,
693
926
  payload: chainFor(options.network).corruptPayload(paymentPayload.payload),
694
927
  };
695
928
  const paymentHeaders = httpClient.encodePaymentSignatureHeader(corrupted);
696
- const response = await fetchTarget(payUrl, withPaymentHeaders(options, paymentHeaders));
929
+ const response = await sendPayment(entry, payUrl, withPaymentHeaders(options, paymentHeaders));
697
930
  return signatureRejectionVerdict(response.status, await refusalReason(response));
698
931
  }
699
932
  /**
@@ -854,9 +1087,57 @@ async function checkUnderpaymentRejected(options) {
854
1087
  }
855
1088
  throw error;
856
1089
  }
857
- const { httpClient, paymentPayload, payUrl } = prepared;
858
- const response = await fetchTarget(payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
859
- return underpaymentVerdict(response.status, offered, advertised, await refusalReason(response));
1090
+ const { httpClient, paymentPayload, selected, payUrl, entry } = prepared;
1091
+ const response = await sendPayment(entry, payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
1092
+ const reason = await refusalReason(response);
1093
+ const verdict = underpaymentVerdict(response.status, offered, advertised, reason);
1094
+ if (verdict.pass)
1095
+ return verdict;
1096
+ // Accepted: the lower amount may have settled. What the chain shows is
1097
+ // added to the FAIL, and recorded in the run ledger, as X402-06 records its own.
1098
+ const settlement = await underpaymentSettlement(options, httpClient, response, entry, offered, selected);
1099
+ return settlement === "" ? verdict : { ...verdict, detail: `${verdict.detail}${settlement}` };
1100
+ }
1101
+ /**
1102
+ * Whether the underpaid payment a target accepted settled, as X402-06 reads
1103
+ * its own: the `PAYMENT-RESPONSE` names a transaction, which is looked up and
1104
+ * held to the payment signed (the offered amount, the asset, payTo, the
1105
+ * payer). Recorded in the run ledger, verified or not. Returns the sentence
1106
+ * the FAIL adds; empty when the response names no settlement. A chain that
1107
+ * gives no answer changes nothing in the FAIL: the target served for less.
1108
+ */
1109
+ async function underpaymentSettlement(options, httpClient, response, entry, offered, selected) {
1110
+ const chain = chainFor(options.network);
1111
+ const read = readSettlementReference(response.status, () => httpClient.getPaymentSettleResponse((header) => response.headers.get(header)), chain);
1112
+ if ("failure" in read)
1113
+ return "";
1114
+ const reference = read.reference;
1115
+ let verdict;
1116
+ try {
1117
+ verdict = await chain.verifySettlement(options.network, chain.resolveRpcUrl(options.network, options.rpcUrl), reference, {
1118
+ amount: offered,
1119
+ token: selected.asset,
1120
+ recipient: selected.payTo,
1121
+ payer: chain.payerAddress(options.payerSecretKey),
1122
+ });
1123
+ }
1124
+ catch (error) {
1125
+ recordSettlement(entry, reference, false);
1126
+ return ` Its PAYMENT-RESPONSE names ${reference}, which could not be read on chain (${sanitizeText(error.message).slice(0, 200)}).`;
1127
+ }
1128
+ recordSettlement(entry, reference, verdict.pass);
1129
+ return verdict.pass
1130
+ ? ` It settled on chain: ${offered} base units moved from the payer to payTo in ${reference}, read back from the transfer event.`
1131
+ : ` Its PAYMENT-RESPONSE names ${reference}, which the chain does not show as this payment: ${verdict.detail}`;
1132
+ }
1133
+ /** A settlement for the run ledger. A ledger that cannot take it leaves it unverified, which explains nothing. */
1134
+ function recordSettlement(entry, reference, verified) {
1135
+ try {
1136
+ entry?.settled(reference, verified);
1137
+ }
1138
+ catch {
1139
+ // The check's own verdict stands; the next intent finds the ledger broken and stops the run.
1140
+ }
860
1141
  }
861
1142
  /** X402-09's verdict from the status the underpaid payment drew. */
862
1143
  export function underpaymentVerdict(status, offered, advertised, reason) {
@@ -885,23 +1166,28 @@ export function underpaymentVerdict(status, offered, advertised, reason) {
885
1166
  * rejected.
886
1167
  *
887
1168
  * Each chain says how the payment is made to expire (`expiredSigning`): on
888
- * Stellar and EVM it is signed with a one-second lifetime (the auth entry's
889
- * expiration ledger, or `validBefore`, both derived from `maxTimeoutSeconds`)
890
- * and held until that has passed; on Solana it is built on a blockhash already
891
- * past its lifetime. It is sent claiming the advertised terms. An expired
1169
+ * EVM it is signed with a one-second lifetime (`validBefore`, derived from
1170
+ * `maxTimeoutSeconds`) and held until that has passed; on Stellar with a
1171
+ * lifetime long enough for the client to finish building it (the auth entry's
1172
+ * expiration ledger), then held until the chain is past that ledger; on Solana
1173
+ * it is built on a blockhash already past its lifetime. It is sent claiming the advertised terms. An expired
892
1174
  * authorization cannot settle, so a target that serves it serves for nothing.
893
1175
  */
894
1176
  async function checkExpiredRejected(options) {
895
1177
  const chain = chainFor(options.network);
896
1178
  const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
897
1179
  let holdMs = 0;
898
- const { httpClient, paymentPayload, payUrl } = await preparePayment(options, "X402-10", async (selected) => {
1180
+ let untilExpired;
1181
+ const { httpClient, paymentPayload, payUrl, entry } = await preparePayment(options, "X402-10", async (selected) => {
899
1182
  const expired = await chain.expiredSigning(selected, rpcUrl);
900
1183
  holdMs = expired.holdMs;
1184
+ untilExpired = expired.untilExpired;
901
1185
  return expired.terms;
902
1186
  });
903
1187
  await new Promise((done) => setTimeout(done, holdMs));
904
- const response = await fetchTarget(payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
1188
+ if (untilExpired !== undefined)
1189
+ await untilExpired(paymentPayload.payload, rpcUrl);
1190
+ const response = await sendPayment(entry, payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
905
1191
  return expiredVerdict(response.status, await refusalReason(response));
906
1192
  }
907
1193
  /** X402-10's verdict from the status the expired payment drew. */
@@ -1056,38 +1342,43 @@ async function checkRejectedRequestNotSettled(options, honest) {
1056
1342
  return outside(error.lifetime, true);
1057
1343
  throw error;
1058
1344
  }
1059
- const { httpClient, paymentPayload, selected, payUrl } = prepared;
1345
+ const { httpClient, paymentPayload, selected, payUrl, entry } = prepared;
1346
+ // A signed payment this check does not send: recorded as discarded, then the check stops.
1347
+ const discard = (message) => {
1348
+ recordDiscarded(entry, new Error(message));
1349
+ throw new CheckSetupError(message);
1350
+ };
1060
1351
  const amount = BigInt(selected.amount);
1061
1352
  const ours = authorizationOf(chain, paymentPayload.payload, payer, "this payment");
1062
1353
  if (ours.nonce === control.nonce) {
1063
- throw new CheckSetupError("This payment's authorization carries X402-06's nonce, so it could not be told apart. It was not sent.");
1354
+ discard("This payment's authorization carries X402-06's nonce, so it could not be told apart. It was not sent.");
1064
1355
  }
1065
1356
  // Right before sending: ours unused, the control found. This read's ledger
1066
1357
  // starts the range the transfers are read over.
1067
1358
  const before = await watch.read(network, rpcUrl, [ours, control]);
1068
1359
  if (before.used[1] === undefined) {
1069
- throw new CheckSetupError("The chain's answer leaves out X402-06's authorization, so this payment was not sent.");
1360
+ discard("The chain's answer leaves out X402-06's authorization, so this payment was not sent.");
1070
1361
  }
1071
1362
  if (before.used[0] !== undefined) {
1072
- throw new CheckSetupError("The chain records this payment's authorization as used before it was sent, so it was not sent.");
1363
+ discard("The chain records this payment's authorization as used before it was sent, so it was not sent.");
1073
1364
  }
1074
1365
  // What the client signed, not what it was asked: an authorization that stays
1075
1366
  // valid longer than the 300 s this check waits is not sent (2 units of slack
1076
1367
  // for the ledgers that close while it is built).
1077
1368
  const longest = Math.ceil(REJECTED_REQUEST_MAX_LIFETIME_SECONDS / watch.unitSeconds) + 2;
1078
1369
  if (ours.expiresAt - before.latest > longest) {
1079
- throw new CheckSetupError(`This payment's authorization stays valid until ${watch.unit} ${ours.expiresAt}, ` +
1370
+ discard(`This payment's authorization stays valid until ${watch.unit} ${ours.expiresAt}, ` +
1080
1371
  `${ours.expiresAt - before.latest} ${watch.unit}s after the latest (${before.latest}), longer than the ` +
1081
1372
  `${REJECTED_REQUEST_MAX_LIFETIME_SECONDS} seconds this check waits. It was signed and discarded; it was not sent.`);
1082
1373
  }
1083
1374
  // And long enough that a service which settles it could still get it on chain.
1084
1375
  if (ours.expiresAt - before.latest < REJECTED_REQUEST_MIN_UNITS_LEFT) {
1085
- throw new CheckSetupError(`This payment's authorization expires at ${watch.unit} ${ours.expiresAt}, ` +
1376
+ discard(`This payment's authorization expires at ${watch.unit} ${ours.expiresAt}, ` +
1086
1377
  `${ours.expiresAt - before.latest} ${watch.unit}s after the latest (${before.latest}): too soon for an unused ` +
1087
1378
  `authorization to show anything. It was signed and discarded; it was not sent.`);
1088
1379
  }
1089
1380
  const sentAt = Date.now();
1090
- const response = await fetchTarget(payUrl, withPaymentHeaders(shape, httpClient.encodePaymentSignatureHeader(paymentPayload)));
1381
+ const response = await sendPayment(entry, payUrl, withPaymentHeaders(shape, httpClient.encodePaymentSignatureHeader(paymentPayload)));
1091
1382
  const status = response.status;
1092
1383
  const reason = await refusalReason(response);
1093
1384
  options.onProgress?.(`X402-11: the payment was sent with the request the service must refuse (HTTP ${status}); reading the chain ` +
@@ -1121,7 +1412,7 @@ async function checkRejectedRequestNotSettled(options, honest) {
1121
1412
  transfers = undefined;
1122
1413
  }
1123
1414
  }
1124
- return rejectedRequestVerdict({
1415
+ const evidence = {
1125
1416
  status,
1126
1417
  ...(reason === undefined ? {} : { reason }),
1127
1418
  amount,
@@ -1130,7 +1421,13 @@ async function checkRejectedRequestNotSettled(options, honest) {
1130
1421
  watch: outcome,
1131
1422
  ...(balance === undefined ? {} : { balance }),
1132
1423
  ...(transfers === undefined ? {} : { transfers }),
1133
- });
1424
+ };
1425
+ // What the chain shows of this payment goes into the run ledger: a payment
1426
+ // the service took for a request it must refuse is a settlement the chain verified.
1427
+ const settlement = rejectedRequestSettlement(evidence);
1428
+ if (settlement !== undefined)
1429
+ recordSettlement(entry, settlement, true);
1430
+ return rejectedRequestVerdict(evidence);
1134
1431
  }
1135
1432
  /** The negative checks, in catalogue order, each with how it runs. */
1136
1433
  const NEGATIVE_CHECKS = [
@@ -1156,10 +1453,25 @@ export const X402_PAYMENT_CHECK_IDS = [
1156
1453
  * See docs/CHECKS.md.
1157
1454
  */
1158
1455
  export async function runX402PaymentChecks(input) {
1159
- // One budget for every signature these checks make: the run's, when the
1160
- // caller shares one across endpoints, or this call's own $5.
1161
- const options = { ...input, budget: input.budget ?? new RunBudget() };
1456
+ const allChecks = [
1457
+ ["X402-06", "Signature Resubmit Accepted"],
1458
+ ...NEGATIVE_CHECKS.map(([id, name]) => [id, name]),
1459
+ ];
1460
+ // A mainnet run stopped by an earlier refusal (B3): every check of this
1461
+ // endpoint is skipped with the reason, and nothing is fetched or signed.
1462
+ const stoppedBefore = stopReason(input.mainnet);
1463
+ if (stoppedBefore !== undefined) {
1464
+ const results = allChecks.map(([id, name]) => skipped(id, name, stoppedBefore));
1465
+ for (const result of results)
1466
+ input.onResult?.(result);
1467
+ return results;
1468
+ }
1469
+ let options = input;
1162
1470
  try {
1471
+ // One budget for every signature these checks make: the run's, when the
1472
+ // caller shares one across endpoints, or this call's own $5. On mainnet,
1473
+ // the opt-in's budget, pin, plan, ledger and RPC, and nothing else.
1474
+ options = input.mainnet === undefined ? { ...input, budget: input.budget ?? new RunBudget() } : mainnetOptions(input);
1163
1475
  assertHttpUrl(options.target);
1164
1476
  buildInit(options);
1165
1477
  // The payment checks pay only where Wasit has an adapter, and X402-06 can
@@ -1168,15 +1480,15 @@ export async function runX402PaymentChecks(input) {
1168
1480
  // after paying.
1169
1481
  const chain = chainFor(options.network);
1170
1482
  // L0: an adapter for the network is not permission to pay on it. Only a
1171
- // test network passes; stellar:pubnet waits for the mainnet opt-in, which
1172
- // this version does not have.
1173
- assertPaymentNetworkAllowed("x402", options.network);
1483
+ // test network passes, and stellar:pubnet with a live mainnet opt-in.
1484
+ assertPaymentNetworkAllowed("x402", options.network, options.mainnet);
1174
1485
  const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
1175
1486
  // A key for another chain, or a malformed one, would otherwise surface
1176
1487
  // mid-payment as a harness error. Checked here, it is what it is: the
1177
1488
  // run's configuration. The message never echoes the key.
1489
+ let payer;
1178
1490
  try {
1179
- chain.payerAddress(options.payerSecretKey);
1491
+ payer = chain.payerAddress(options.payerSecretKey);
1180
1492
  }
1181
1493
  catch (error) {
1182
1494
  if (error instanceof ConfigurationError)
@@ -1184,9 +1496,13 @@ export async function runX402PaymentChecks(input) {
1184
1496
  throw new ConfigurationError(`The payer key is not a valid ${chain.name} key (read from ${chain.payerKeyEnv} ` +
1185
1497
  `or --payer-key).`);
1186
1498
  }
1499
+ if (options.mainnet !== undefined && payer !== options.mainnet.payer) {
1500
+ throw stopMainnet(options.mainnet, "These checks were handed the key of another account than the mainnet run's payer.");
1501
+ }
1187
1502
  // The RPC signs and settles nothing itself, but the payment is built and
1188
- // its settlement read through it: it must serve the run's network (D-023).
1189
- await assertRpcServesNetwork(options.network, rpcUrl);
1503
+ // the settlement read through it: it must be one the client accepts and
1504
+ // serve the run's network (D-023).
1505
+ await assertX402PaymentRpc(options.network, rpcUrl);
1190
1506
  }
1191
1507
  catch (error) {
1192
1508
  // A network no adapter pays on is not a failure of the run: Wasit does not
@@ -1207,6 +1523,7 @@ export async function runX402PaymentChecks(input) {
1207
1523
  const results = [];
1208
1524
  const emit = (result) => {
1209
1525
  results.push(result);
1526
+ recordVerdict(options.ledger, result);
1210
1527
  options.onResult?.(result);
1211
1528
  };
1212
1529
  const skipNegatives = (reason) => {
@@ -1225,6 +1542,9 @@ export async function runX402PaymentChecks(input) {
1225
1542
  }
1226
1543
  const failed = errored("X402-06", "Signature Resubmit Accepted", error);
1227
1544
  emit(failed);
1545
+ const stopped = stopReason(options.mainnet);
1546
+ if (stopped !== undefined)
1547
+ return skipNegatives(stopped);
1228
1548
  // If the payment flow could not be exercised at all, no altered variant of
1229
1549
  // it can be either, and none may be reported as a passing rejection.
1230
1550
  return skipNegatives(`the payment flow could not be exercised (${failed.error?.kind ?? "harness"}), ` +
@@ -1238,13 +1558,104 @@ export async function runX402PaymentChecks(input) {
1238
1558
  return skipNegatives("the target refused X402-06's valid payment, so refusing an altered one " +
1239
1559
  "says nothing about what it checks.");
1240
1560
  }
1561
+ // B8: once a new challenge drew a 409, the resource is used up: every later
1562
+ // check that needs one is skipped as "resource consumed" without asking again,
1563
+ // and the replay, which needs none, still runs.
1564
+ let consumed = false;
1241
1565
  for (const [id, name, run] of NEGATIVE_CHECKS) {
1566
+ // B3: once a mainnet run is stopped, nothing more is signed in it.
1567
+ const stopped = stopReason(options.mainnet);
1568
+ if (stopped !== undefined) {
1569
+ emit(skipped(id, name, stopped));
1570
+ continue;
1571
+ }
1572
+ if (consumed && id !== REPLAY_CHECK) {
1573
+ emit(skipped(id, name, RESOURCE_CONSUMED_REASON, "resource-consumed"));
1574
+ continue;
1575
+ }
1242
1576
  try {
1243
1577
  emit(await run(options, honest));
1244
1578
  }
1245
1579
  catch (error) {
1580
+ if (error instanceof ResourceConsumedError) {
1581
+ consumed = true;
1582
+ emit(skipped(id, name, RESOURCE_CONSUMED_REASON, "resource-consumed"));
1583
+ continue;
1584
+ }
1246
1585
  emit(errored(id, name, error));
1247
1586
  }
1248
1587
  }
1249
1588
  return results;
1250
1589
  }
1590
+ /** What a result says about the target, as the run ledger records it. */
1591
+ function verdictOf(result) {
1592
+ if (result.skipped === true)
1593
+ return "skipped";
1594
+ if (result.error !== undefined)
1595
+ return "no-verdict";
1596
+ return result.pass ? "pass" : "fail";
1597
+ }
1598
+ /**
1599
+ * Records a check's verdict on its entries in the run ledger. A ledger that
1600
+ * cannot take it keeps none, and a payment of that check then explains
1601
+ * nothing when the balances are compared: the safe side.
1602
+ */
1603
+ function recordVerdict(ledger, result) {
1604
+ try {
1605
+ ledger?.verdict?.(result.id, verdictOf(result));
1606
+ }
1607
+ catch {
1608
+ // The result stands; see above.
1609
+ }
1610
+ }
1611
+ /** Why a check of a stopped mainnet run is skipped; undefined while the run goes on, or with no opt-in. */
1612
+ function stopReason(mainnet) {
1613
+ const reason = mainnet?.stopped;
1614
+ if (reason === undefined)
1615
+ return undefined;
1616
+ return `the mainnet run stopped, and nothing more is signed in it: ${sanitizeText(String(reason)).slice(0, 400)}`;
1617
+ }
1618
+ /** Stops `mainnet` with `message` and returns the error to throw. */
1619
+ function stopMainnet(mainnet, message) {
1620
+ const error = new MainnetRunRefusedError("run", message, { during: true });
1621
+ mainnet.stop(error.message);
1622
+ return error;
1623
+ }
1624
+ /**
1625
+ * The options a mainnet run's checks pay by (spec B5): the opt-in's own
1626
+ * budget, pin, plan entry, ledger and RPC. A value handed in beside it that is
1627
+ * not the opt-in's is refused and the run stopped: on mainnet nothing is paid
1628
+ * by terms core did not plan.
1629
+ */
1630
+ function mainnetOptions(input) {
1631
+ const optIn = input.mainnet;
1632
+ if (input.network !== optIn.network) {
1633
+ throw stopMainnet(optIn, `A mainnet opt-in was handed to checks on another network than ${optIn.network}.`);
1634
+ }
1635
+ // L0 first: a stopped, closed or forged opt-in is refused here, and says why.
1636
+ assertPaymentNetworkAllowed("x402", input.network, optIn);
1637
+ const plan = optIn.plan;
1638
+ if (plan === undefined)
1639
+ throw stopMainnet(optIn, "The mainnet run has no plan that passed: its plan comes before any payment.");
1640
+ const entry = input.plan;
1641
+ if (entry === undefined || !plan.endpoints.includes(entry)) {
1642
+ throw stopMainnet(optIn, "These checks were not handed an entry of the mainnet run's own plan.");
1643
+ }
1644
+ if (input.budget !== undefined && input.budget !== optIn.budget) {
1645
+ throw stopMainnet(optIn, "These checks were handed another budget than the mainnet run's.");
1646
+ }
1647
+ if (input.pin !== undefined && (input.pin.payTo !== optIn.pin.payTo || input.pin.asset !== optIn.pin.asset)) {
1648
+ throw stopMainnet(optIn, "These checks were handed another pin than the mainnet run's.");
1649
+ }
1650
+ if (input.rpcUrl !== undefined && input.rpcUrl !== optIn.rpcUrl) {
1651
+ throw stopMainnet(optIn, "These checks were handed another RPC than the mainnet run's.");
1652
+ }
1653
+ if (input.ledger !== undefined) {
1654
+ throw stopMainnet(optIn, "These checks were handed a ledger of their own: a mainnet run writes every signature to its own.");
1655
+ }
1656
+ const ledger = optIn.ledger;
1657
+ if (ledger === undefined) {
1658
+ throw stopMainnet(optIn, "The mainnet run's ledger is not open: on mainnet every signature is written to it first.");
1659
+ }
1660
+ return { ...input, budget: optIn.budget, pin: optIn.pin, rpcUrl: optIn.rpcUrl, ledger: ledger.forEndpoint(entry.name) };
1661
+ }