mppx 0.20.1 → 0.21.0

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 (78) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/Challenge.d.ts +59 -3
  3. package/dist/Challenge.js +162 -21
  4. package/dist/Errors.d.ts +35 -1
  5. package/dist/Errors.js +41 -3
  6. package/dist/Method.js +2 -2
  7. package/dist/Receipt.d.ts +2 -0
  8. package/dist/Receipt.js +5 -0
  9. package/dist/Store.d.ts +39 -10
  10. package/dist/Store.js +136 -29
  11. package/dist/cli/cli.d.ts +5 -0
  12. package/dist/cli/cli.js +135 -135
  13. package/dist/cli/plugins/index.js +12 -12
  14. package/dist/cli/sessions/commands.js +9 -0
  15. package/dist/cli/sessions/store.js +3 -2
  16. package/dist/cli/validate/challenge.js +15 -1
  17. package/dist/client/Mppx.d.ts +1 -1
  18. package/dist/client/Mppx.js +2 -1
  19. package/dist/client/internal/Fetch.d.ts +2 -1
  20. package/dist/client/internal/Fetch.js +43 -5
  21. package/dist/client/internal/PendingSettlement.d.ts +11 -0
  22. package/dist/client/internal/PendingSettlement.js +22 -0
  23. package/dist/client/internal/protocols/Mcp.js +8 -0
  24. package/dist/evm/client/Charge.js +7 -1
  25. package/dist/evm/server/Charge.d.ts +5 -0
  26. package/dist/evm/server/Charge.js +44 -0
  27. package/dist/evm/server/Methods.d.ts +8 -0
  28. package/dist/evm/server/Methods.js +8 -0
  29. package/dist/extensions/identity/attestation/Jwks.js +3 -3
  30. package/dist/extensions/identity/link/server/index.js +4 -4
  31. package/dist/extensions/identity/persona/server/index.js +3 -3
  32. package/dist/internal/CredentialExpiry.d.ts +30 -0
  33. package/dist/internal/CredentialExpiry.js +51 -0
  34. package/dist/internal/version.d.ts +2 -2
  35. package/dist/internal/version.js +1 -1
  36. package/dist/mcp/client/McpClient.js +29 -10
  37. package/dist/middlewares/express.d.ts +7 -2
  38. package/dist/middlewares/express.js +20 -23
  39. package/dist/middlewares/internal/express.d.ts +9 -1
  40. package/dist/middlewares/internal/express.js +348 -2
  41. package/dist/proxy/Proxy.js +15 -3
  42. package/dist/proxy/internal/Replay.d.ts +10 -0
  43. package/dist/proxy/internal/Replay.js +5 -0
  44. package/dist/server/Mppx.d.ts +1 -1
  45. package/dist/server/Mppx.js +19 -14
  46. package/dist/server/NodeListener.js +7 -0
  47. package/dist/server/Request.d.ts +6 -0
  48. package/dist/server/Request.js +43 -22
  49. package/dist/server/internal/challengeMeta.d.ts +10 -0
  50. package/dist/server/internal/challengeMeta.js +31 -1
  51. package/dist/server/internal/host.d.ts +4 -0
  52. package/dist/server/internal/host.js +41 -0
  53. package/dist/tempo/client/Charge.d.ts +5 -4
  54. package/dist/tempo/client/Charge.js +210 -38
  55. package/dist/tempo/client/Subscription.js +3 -0
  56. package/dist/tempo/internal/zone.d.ts +8 -0
  57. package/dist/tempo/internal/zone.js +15 -0
  58. package/dist/tempo/server/Charge.d.ts +19 -0
  59. package/dist/tempo/server/Charge.js +60 -15
  60. package/dist/tempo/server/internal/html.gen.js +1 -1
  61. package/dist/tempo/server/internal/transport.js +10 -54
  62. package/dist/tempo/session/client/ChannelOps.js +1 -1
  63. package/dist/tempo/session/client/SessionManager.d.ts +4 -1
  64. package/dist/tempo/session/client/SessionManager.js +8 -2
  65. package/dist/tempo/session/server/CredentialVerification.js +2 -3
  66. package/dist/viem/Client.d.ts +2 -0
  67. package/dist/viem/Client.js +4 -1
  68. package/dist/x402/Assets.d.ts +6 -0
  69. package/dist/x402/Assets.js +10 -0
  70. package/dist/x402/Types.d.ts +68 -8
  71. package/dist/x402/Types.js +17 -2
  72. package/dist/x402/client/Exact.js +4 -1
  73. package/dist/x402/middlewares/express.js +10 -1
  74. package/dist/x402/server/EvmCharge.d.ts +20 -3
  75. package/dist/x402/server/EvmCharge.js +13 -1
  76. package/dist/x402/server/Facilitator.d.ts +42 -3
  77. package/dist/x402/server/Facilitator.js +126 -16
  78. package/package.json +1 -1
@@ -7,7 +7,10 @@ import * as MethodResponse from '../../client/internal/MethodResponse.js';
7
7
  import * as Credential from '../../Credential.js';
8
8
  import * as Currency from '../../Currency.js';
9
9
  import * as Errors from '../../Errors.js';
10
+ import * as Expires from '../../Expires.js';
10
11
  import * as Method from '../../Method.js';
12
+ import * as PaymentRequest from '../../PaymentRequest.js';
13
+ import * as ChallengeMeta from '../../server/internal/challengeMeta.js';
11
14
  import * as Account from '../../viem/Account.js';
12
15
  import * as Client from '../../viem/Client.js';
13
16
  import * as z from '../../zod.js';
@@ -71,7 +74,7 @@ export function charge(parameters = {}) {
71
74
  });
72
75
  const getAccount = Account.getResolver({ account: parameters.account });
73
76
  assertZone(parameters.zone);
74
- // Zone withdrawals still settling, by challenge ID, so a retry resumes waiting instead of paying again.
77
+ // Zone withdrawals still settling, by challenge, so a retry resumes waiting instead of paying again.
75
78
  const pendingZoneWithdrawals = new Map();
76
79
  const method = Method.toClient(Methods.charge, {
77
80
  // Skip offers that violate client policy so an acceptable offer can be chosen.
@@ -85,7 +88,8 @@ export function charge(parameters = {}) {
85
88
  }
86
89
  },
87
90
  context: chargeContextSchema,
88
- async createCredential({ challenge, context }) {
91
+ async createCredential(credentialParameters) {
92
+ const { challenge, context } = credentialParameters;
89
93
  assertChallengePolicy(parameters, caps, challenge.request);
90
94
  // Sign on the pinned chain when the challenge omits a chain ID.
91
95
  const challengeChainId = challenge.request.methodDetails?.chainId;
@@ -121,19 +125,31 @@ export function charge(parameters = {}) {
121
125
  supportedModes.includes('push') &&
122
126
  (explicitMode === undefined || explicitMode === 'push') &&
123
127
  Zone.isAccepted(methodDetails?.zones, zoneId) &&
124
- !methodDetails?.splits &&
125
- // A withdrawal can't be undone, so start one only when it can settle before the
126
- // challenge expires; an expired challenge would invite another payment.
127
- (pendingZoneWithdrawals.has(zoneWithdrawalKey(challenge)) ||
128
- settlesBeforeExpiry(challenge.expires, parameters.zone.settlementTimeoutMs)))
129
- return createZoneCredential({
128
+ !methodDetails?.splits) {
129
+ const options = {
130
+ // The withdrawal fee is paid on top of the amount, so both must fit the caps.
131
+ assertFee: (fee) => assertChallengePolicy(parameters, caps, request, chainId, fee),
130
132
  challenge,
131
133
  clientId,
132
134
  client,
135
+ origin: httpOrigin(MethodResponse.getOrigin(credentialParameters)),
133
136
  pending: pendingZoneWithdrawals,
134
137
  zone: parameters.zone,
135
138
  zoneId,
136
- });
139
+ };
140
+ // A withdrawal can't be undone, so one still outstanding for these terms is resumed,
141
+ // even under a new challenge, and a new one starts only when it can settle before the
142
+ // challenge expires; an expired challenge would invite another payment.
143
+ const outstanding = findZoneWithdrawal(options);
144
+ if (outstanding)
145
+ return resumeZoneCredential(options, outstanding);
146
+ // With nothing outstanding, an expired challenge can't be paid: its server refuses any
147
+ // credential for it, so a payment on Tempo would be lost.
148
+ if (challenge.expires)
149
+ Expires.assert(challenge.expires, challenge.id);
150
+ if (settlesBeforeExpiry(challenge.expires, parameters.zone.settlementTimeoutMs))
151
+ return createZoneCredential(options);
152
+ }
137
153
  const defaultAccount = getAccount(client, context);
138
154
  const resolveAccount = async (operation) => (await parameters.resolveAccount?.({
139
155
  account: defaultAccount,
@@ -415,27 +431,100 @@ function transactionHash(credential) {
415
431
  * with the challenge-bound memo, and returns a `zone` credential that names it
416
432
  * by sender tag and the Tempo transaction hash that settled it.
417
433
  */
418
- async function createZoneCredential(options) {
419
- const { challenge, client, pending, zone, zoneId } = options;
420
- const request = challenge.request;
421
- const recipient = request.recipient;
422
- // The whole challenge, so a challenge from another realm or request with the same ID never matches.
434
+ function createZoneCredential(options) {
435
+ const { challenge, origin, pending, zoneId } = options;
436
+ // Stored before it is sent, so concurrent and later calls for one challenge or its terms share it.
437
+ const state = { sent: false };
438
+ const entry = {
439
+ challenge,
440
+ origin,
441
+ terms: zoneTermsKey(challenge, zoneId),
442
+ waiters: 0,
443
+ withdrawal: requestZoneWithdrawal(options, state),
444
+ };
423
445
  const key = zoneWithdrawalKey(challenge);
424
- // A withdrawal can't be undone, so a retry after a failed wait resumes it instead of paying again.
425
- // Concurrent calls for one challenge share the request, which is stored before it is sent.
426
- let withdrawalRequest = pending.get(key);
427
- if (!withdrawalRequest) {
428
- const state = { sent: false };
429
- withdrawalRequest = requestZoneWithdrawal(options, state);
430
- pending.set(key, withdrawalRequest);
431
- // Only a failure before the transaction was sent is safe to retry. After that, the
432
- // withdrawal may have gone through, so retries of this challenge keep failing.
433
- withdrawalRequest.catch(() => {
434
- if (!state.sent)
435
- pending.delete(key);
436
- });
446
+ pending.set(key, entry);
447
+ // Only a failure before the transaction was sent is safe to retry. After that, the
448
+ // withdrawal may have gone through, so retries of this challenge keep failing.
449
+ entry.withdrawal.catch(() => {
450
+ if (!state.sent && pending.get(key) === entry)
451
+ pending.delete(key);
452
+ });
453
+ return resumeZoneCredential(options, entry);
454
+ }
455
+ /**
456
+ * Returns the outstanding withdrawal that pays this challenge: its own, or, for a new
457
+ * challenge with the same terms, one an earlier challenge started and no call is still
458
+ * waiting on. A withdrawal stays outstanding until it produces a credential, even after its
459
+ * challenge expires: it may have settled, so paying its terms again could pay twice. It
460
+ * stops paying other challenges once its own can no longer be redeemed.
461
+ */
462
+ function findZoneWithdrawal(options) {
463
+ const { challenge, pending, zoneId } = options;
464
+ const own = pending.get(zoneWithdrawalKey(challenge));
465
+ if (own)
466
+ return own;
467
+ const terms = zoneTermsKey(challenge, zoneId);
468
+ if (terms === undefined)
469
+ return undefined;
470
+ for (const [key, entry] of pending) {
471
+ if (entry.terms !== terms)
472
+ continue;
473
+ // No server accepts its credential any more, so it can't pay this challenge.
474
+ if (!isRedeemable(entry.challenge.expires)) {
475
+ pending.delete(key);
476
+ continue;
477
+ }
478
+ // Its credential was sent after its challenge expired, and its server may still accept or
479
+ // refuse it. Sending it again for this challenge could redeem it twice, and a new payment
480
+ // could pay twice if it was refused, so fail closed until its redemption window ends.
481
+ // The error names the challenge the withdrawal paid, whose retry gets its credential.
482
+ if (entry.redeemedLate)
483
+ throw new Errors.ZoneSettlementPendingError({
484
+ challengeId: entry.challenge.id,
485
+ senderTags: entry.senderTags,
486
+ zoneId,
487
+ });
488
+ // A call still waiting on it is another payment in flight, not one this challenge retries:
489
+ // sharing its credential would leave one of the two payments unpaid.
490
+ if (entry.waiters > 0)
491
+ continue;
492
+ return entry;
437
493
  }
438
- const withdrawal = await withdrawalRequest;
494
+ return undefined;
495
+ }
496
+ /**
497
+ * Waits for an outstanding withdrawal to settle and returns a `zone` credential for the
498
+ * challenge it pays. A withdrawal started for an earlier challenge pays only that challenge,
499
+ * so its credential is sent only back to the origin that issued it; under any other origin,
500
+ * or one the caller did not verify, this throws the settlement-pending error instead.
501
+ */
502
+ async function resumeZoneCredential(options, entry) {
503
+ // Counted from the call itself, before any await, so a concurrent call sees it.
504
+ entry.waiters++;
505
+ try {
506
+ return await waitForZoneCredential(options, entry);
507
+ }
508
+ finally {
509
+ entry.waiters--;
510
+ }
511
+ }
512
+ /** Waits for {@link resumeZoneCredential}'s withdrawal to settle and serializes its credential. */
513
+ async function waitForZoneCredential(options, entry) {
514
+ const { client, origin, pending, zone, zoneId } = options;
515
+ const { challenge } = entry;
516
+ const recipient = challenge.request.recipient;
517
+ const key = zoneWithdrawalKey(challenge);
518
+ const foreign = key !== zoneWithdrawalKey(options.challenge);
519
+ if (foreign
520
+ ? !origin || origin !== entry.origin
521
+ : origin !== undefined && entry.origin !== undefined && origin !== entry.origin)
522
+ throw new Errors.ZoneSettlementPendingError({ challengeId: challenge.id, zoneId });
523
+ // Past its redemption window, the server refuses the challenge's credential, but the
524
+ // withdrawal may still have paid it: fail closed rather than withdraw again.
525
+ if (!isRedeemable(challenge.expires))
526
+ throw new Errors.ZoneSettlementPendingError({ challengeId: challenge.id, zoneId });
527
+ const withdrawal = await entry.withdrawal;
439
528
  // Derived on every attempt, so a failed read on the Zone is retried without withdrawing again.
440
529
  const senderTags = withdrawal.senderTags ??
441
530
  (await Zone.senderTagCandidates(zone.client, withdrawal).catch((cause) => {
@@ -461,13 +550,42 @@ async function createZoneCredential(options) {
461
550
  zoneId,
462
551
  });
463
552
  }
464
- pending.delete(key);
553
+ // The credential pays once: a later challenge with the same terms is a new payment. One
554
+ // made after its challenge expired is accepted only by a server that grants a grace period
555
+ // (`zoneCredentialGraceMs`), so it stays for a retry of its own challenge, which would
556
+ // otherwise pay again on Tempo, and blocks other challenges until its window ends.
557
+ if (pending.get(key) === entry) {
558
+ if (isExpired(challenge.expires)) {
559
+ entry.redeemedLate = true;
560
+ entry.senderTags = [settled.senderTag];
561
+ }
562
+ else
563
+ pending.delete(key);
564
+ }
465
565
  const { hash, senderTag } = settled;
466
566
  return Credential.serialize({
467
567
  challenge,
468
568
  payload: { hash, senderTag, type: 'zone', zoneId },
469
569
  });
470
570
  }
571
+ /**
572
+ * Returns the origin of an HTTP(S) URL, or `undefined` for anything else. Every other scheme
573
+ * has the opaque origin `"null"`, which can't tell two servers apart, so it never counts as
574
+ * a verified origin.
575
+ */
576
+ function httpOrigin(origin) {
577
+ if (!origin)
578
+ return undefined;
579
+ try {
580
+ const url = new URL(origin);
581
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
582
+ return undefined;
583
+ return url.origin;
584
+ }
585
+ catch {
586
+ return undefined;
587
+ }
588
+ }
471
589
  /**
472
590
  * Throws on Zone options that would fail only after an irreversible withdrawal:
473
591
  * a `settlementTimeoutMs` that is not a finite, non-negative number, or a
@@ -499,7 +617,10 @@ function settlesBeforeExpiry(expires, settlementTimeoutMs) {
499
617
  const timeoutMs = settlementTimeoutMs ?? Zone.defaultSettlementTimeoutMs;
500
618
  return new Date(expires).getTime() - Date.now() > timeoutMs + zoneSubmissionMarginMs;
501
619
  }
502
- /** Returns how long to wait for settlement: `settlementTimeoutMs`, cut short at `expires`. */
620
+ /**
621
+ * Returns how long to wait for settlement: `settlementTimeoutMs`, cut short at `expires`. After
622
+ * `expires`, it looks once: only a settlement from before then can still be redeemed.
623
+ */
503
624
  function settlementTimeoutMs(expires, settlementTimeoutMs) {
504
625
  const timeoutMs = settlementTimeoutMs ?? Zone.defaultSettlementTimeoutMs;
505
626
  if (!expires)
@@ -510,6 +631,50 @@ function settlementTimeoutMs(expires, settlementTimeoutMs) {
510
631
  function zoneWithdrawalKey(challenge) {
511
632
  return JSON.stringify(challenge);
512
633
  }
634
+ /**
635
+ * Keys what a challenge asks a Zone withdrawal to pay: its realm, request, digest and route
636
+ * metadata, everything a server compares when it accepts another challenge's credential,
637
+ * but not its ID, expiry or issuance nonce. `undefined` when its metadata can't be read.
638
+ */
639
+ function zoneTermsKey(challenge, zoneId) {
640
+ let meta;
641
+ try {
642
+ meta =
643
+ challenge.opaque !== undefined
644
+ ? PaymentRequest.deserialize(challenge.opaque)
645
+ : challenge.meta;
646
+ }
647
+ catch {
648
+ return undefined;
649
+ }
650
+ const { digest, intent, method, realm, request } = challenge;
651
+ return PaymentRequest.serialize({
652
+ digest,
653
+ intent,
654
+ meta: ChallengeMeta.routeMeta(meta),
655
+ method,
656
+ realm,
657
+ request,
658
+ zoneId,
659
+ });
660
+ }
661
+ /** Whether a challenge expiring at `expires` has expired. */
662
+ function isExpired(expires) {
663
+ if (!expires)
664
+ return false;
665
+ const expiresAt = new Date(expires).getTime();
666
+ return !Number.isNaN(expiresAt) && Date.now() >= expiresAt;
667
+ }
668
+ /**
669
+ * Whether a credential for a challenge expiring at `expires` may still be redeemed: until
670
+ * `Zone.redemptionGraceMs`, the longest server grace, after it expires.
671
+ */
672
+ function isRedeemable(expires) {
673
+ if (!expires)
674
+ return true;
675
+ const expiresAt = new Date(expires).getTime();
676
+ return Number.isNaN(expiresAt) || Date.now() < expiresAt + Zone.redemptionGraceMs;
677
+ }
513
678
  /** How long to look for a withdrawal's receipt on the Zone after its send response fails. */
514
679
  const zoneReceiptRecoveryTimeoutMs = 15_000;
515
680
  /**
@@ -517,7 +682,7 @@ const zoneReceiptRecoveryTimeoutMs = 15_000;
517
682
  * Returns its sender tag, or leaves it to be derived when the Zone RPC hides it from the receipt.
518
683
  */
519
684
  async function requestZoneWithdrawal(options, state) {
520
- const { challenge, clientId, zone } = options;
685
+ const { assertFee, challenge, clientId, zone } = options;
521
686
  const request = challenge.request;
522
687
  const account = zone.client.account;
523
688
  if (!account)
@@ -532,6 +697,7 @@ async function requestZoneWithdrawal(options, state) {
532
697
  });
533
698
  // The outbox pulls the amount plus its withdrawal fee.
534
699
  const fee = await Actions.zone.getWithdrawalFee(zone.client);
700
+ assertFee(fee);
535
701
  const [, withdrawal] = Actions.zone.requestWithdrawal.calls({
536
702
  amount,
537
703
  // A bounced payout refunds the payer, not the payee's Zone address.
@@ -609,8 +775,10 @@ function parseMaxAmount(maxAmount, decimals) {
609
775
  */
610
776
  function assertChallengePolicy(parameters, caps, request,
611
777
  /** Chain the client signs on, once resolved, for a challenge that names none. */
612
- signingChainId) {
613
- const { amount, methodDetails, recipient } = request;
778
+ signingChainId,
779
+ /** Zone withdrawal fee paid on top of the amount, which the caps cover too. */
780
+ fee) {
781
+ const { methodDetails, recipient } = request;
614
782
  // Chain pinning: reject a challenge whose chain ID conflicts with the pinned one.
615
783
  const challengeChainId = methodDetails?.chainId;
616
784
  if (parameters.expectedChainId !== undefined &&
@@ -645,10 +813,14 @@ signingChainId) {
645
813
  }
646
814
  }
647
815
  }
648
- if (caps.maxAtomicAmount !== undefined && BigInt(amount) > caps.maxAtomicAmount)
649
- throw new Error('Tempo charge amount exceeds maxAtomicAmount.');
650
- if (caps.maxAmount !== undefined &&
651
- BigInt(amount) > parseMaxAmount(caps.maxAmount, currency?.decimals))
652
- throw new Error('Tempo charge amount exceeds maxAmount.');
816
+ if (caps.maxAtomicAmount === undefined && caps.maxAmount === undefined)
817
+ return;
818
+ // Parsed only after the checks above pass, and only when a cap needs it.
819
+ const amount = BigInt(request.amount) + (fee ?? 0n);
820
+ const exceeds = fee === undefined ? 'amount exceeds' : 'amount plus Zone withdrawal fee exceeds';
821
+ if (caps.maxAtomicAmount !== undefined && amount > caps.maxAtomicAmount)
822
+ throw new Error(`Tempo charge ${exceeds} maxAtomicAmount.`);
823
+ if (caps.maxAmount !== undefined && amount > parseMaxAmount(caps.maxAmount, currency?.decimals))
824
+ throw new Error(`Tempo charge ${exceeds} maxAmount.`);
653
825
  }
654
826
  //# sourceMappingURL=Charge.js.map
@@ -19,6 +19,7 @@ export const subscriptionContextSchema = z.object({
19
19
  export function subscription(parameters = {}) {
20
20
  const getClient = Client.getResolver({
21
21
  chain: tempo_chain,
22
+ requireChain: true,
22
23
  getClient: parameters.getClient,
23
24
  rpcUrl: defaults.rpcUrl,
24
25
  });
@@ -28,6 +29,8 @@ export function subscription(parameters = {}) {
28
29
  async createCredential({ challenge, context }) {
29
30
  const chainId = challenge.request.methodDetails?.chainId ?? defaults.chainId.testnet;
30
31
  const client = await getClient({ chainId });
32
+ if (client.chain?.id !== chainId)
33
+ throw new Error(`Subscription chain mismatch: expected ${chainId}, got ${client.chain?.id ?? 'unknown'}.`);
31
34
  const account = getAccount(client, context);
32
35
  const accessKey = context?.accessKey ?? parameters.accessKey ?? challenge.request.methodDetails?.accessKey;
33
36
  if (!accessKey) {
@@ -1,6 +1,12 @@
1
1
  import { type Address, type Client, type Hex, type TransactionReceipt } from 'viem';
2
2
  /** Default time a payer waits for a Zone withdrawal to settle on Tempo. */
3
3
  export declare const defaultSettlementTimeoutMs = 60000;
4
+ /**
5
+ * The longest a server accepts a `zone` credential after its challenge expires (its
6
+ * `zoneCredentialGraceMs`), for a withdrawal that settled before then. A payer keeps resuming
7
+ * a withdrawal it has not redeemed for as long.
8
+ */
9
+ export declare const redemptionGraceMs: number;
4
10
  /** A withdrawal as `ZonePortal.processWithdrawals` receives it on Tempo. */
5
11
  export type Withdrawal = {
6
12
  token: Address;
@@ -29,6 +35,8 @@ export declare function isId(zoneId: number): boolean;
29
35
  export declare function isAccepted(zones: Accepted | undefined, zoneId: number): boolean;
30
36
  /** Returns the Tempo portal address of a Zone. */
31
37
  export declare function portalAddress(zoneId: number): Address;
38
+ /** Whether `address` is the Tempo portal of some Zone. */
39
+ export declare function isPortalAddress(address: Address): boolean;
32
40
  /**
33
41
  * Derives a Zone ID from a Zone chain ID.
34
42
  *
@@ -5,6 +5,12 @@ import { Abis, Addresses } from 'viem/tempo';
5
5
  import * as TempoAddress from './address.js';
6
6
  /** Default time a payer waits for a Zone withdrawal to settle on Tempo. */
7
7
  export const defaultSettlementTimeoutMs = 60_000;
8
+ /**
9
+ * The longest a server accepts a `zone` credential after its challenge expires (its
10
+ * `zoneCredentialGraceMs`), for a withdrawal that settled before then. A payer keeps resuming
11
+ * a withdrawal it has not redeemed for as long.
12
+ */
13
+ export const redemptionGraceMs = 5 * 60_000;
8
14
  /** Number of Tempo blocks searched back for a settled Zone withdrawal. */
9
15
  const lookbackBlocks = 7200n;
10
16
  /**
@@ -34,6 +40,15 @@ export function isAccepted(zones, zoneId) {
34
40
  export function portalAddress(zoneId) {
35
41
  return Addresses.zonePortal(zoneId);
36
42
  }
43
+ /** Prefix of every Zone portal address but the legacy ones: the Zone ID fills the last 8 bytes. */
44
+ const portalAddressPrefix = portalAddress(0).slice(0, -16).toLowerCase();
45
+ /** Zone IDs whose portals predate the prefixed addresses. */
46
+ const legacyPortalZoneIds = [6, 7];
47
+ /** Whether `address` is the Tempo portal of some Zone. */
48
+ export function isPortalAddress(address) {
49
+ return (address.toLowerCase().startsWith(portalAddressPrefix) ||
50
+ legacyPortalZoneIds.some((zoneId) => TempoAddress.isEqual(address, portalAddress(zoneId))));
51
+ }
37
52
  /**
38
53
  * Derives a Zone ID from a Zone chain ID.
39
54
  *
@@ -155,6 +155,25 @@ export declare namespace charge {
155
155
  * polling for a receipt.
156
156
  */
157
157
  waitForConfirmation?: boolean | undefined;
158
+ /**
159
+ * How long, in milliseconds, after its challenge expires a `zone` credential is still
160
+ * accepted, for a withdrawal that settled on Tempo before the challenge expired. Lets a
161
+ * payer whose withdrawal settled late in the challenge's lifetime redeem it on retry.
162
+ * At most 5 minutes (`300_000`).
163
+ *
164
+ * Only a Challenge issued while the grace is on gets it: issuance marks the Challenge in its
165
+ * HMAC-bound `opaque` metadata (`_mppx_expiry_grace`). A Challenge issued without the mark,
166
+ * by an earlier release or with no grace, is rejected at its expiry as before, since an
167
+ * earlier release records a redeemed withdrawal only until then.
168
+ *
169
+ * Enable it once no instance of an earlier release verifies credentials from the same store:
170
+ * such an instance could redeem a marked Challenge and record it only until its expiry.
171
+ *
172
+ * Not supported with `relay`, which verifies credentials without the settled-before-expiry check.
173
+ *
174
+ * @default 0
175
+ */
176
+ zoneCredentialGraceMs?: number | undefined;
158
177
  } & Client.getResolver.Parameters & Account.resolve.Parameters & Defaults & Method.ComposableHooks<typeof Methods.charge>;
159
178
  type DeriveDefaults<parameters extends Parameters> = types.DeriveDefaults<parameters, Defaults, {
160
179
  currency: string;
@@ -1,11 +1,14 @@
1
+ import { Secp256k1 } from 'ox';
1
2
  import * as SignatureEnvelope from 'ox/tempo/SignatureEnvelope';
2
3
  import { decodeFunctionData, formatUnits, keccak256, parseEventLogs, WaitForTransactionReceiptTimeoutError, } from 'viem';
3
- import { getTransaction, getTransactionReceipt, sendRawTransaction, sendRawTransactionSync, signTransaction, verifyTypedData, waitForTransactionReceipt, call as viem_call, } from 'viem/actions';
4
+ import { getTransaction, getBlock, getTransactionReceipt, sendRawTransaction, sendRawTransactionSync, signTransaction, verifyTypedData, waitForTransactionReceipt, call as viem_call, } from 'viem/actions';
4
5
  import { Abis, Actions, Transaction } from 'viem/tempo';
5
6
  import { tempo as tempo_chain } from 'viem/tempo/chains';
6
- import { BroadcastOutcomeUnknownError, CredentialReplayedError, PaymentError, VerificationFailedError, } from '../../Errors.js';
7
+ import { BroadcastOutcomeUnknownError, CredentialReplayedError, PaymentError, PaymentExpiredError, VerificationFailedError, } from '../../Errors.js';
7
8
  import * as Expires from '../../Expires.js';
9
+ import * as CredentialExpiry from '../../internal/CredentialExpiry.js';
8
10
  import * as Method from '../../Method.js';
11
+ import * as ChallengeMeta from '../../server/internal/challengeMeta.js';
9
12
  import * as Store from '../../Store.js';
10
13
  import * as Client from '../../viem/Client.js';
11
14
  import * as Attribution from '../Attribution.js';
@@ -34,7 +37,25 @@ import * as SponsorBudget from './SponsorBudget.js';
34
37
  * ```
35
38
  */
36
39
  export function charge(parameters = {}) {
37
- const { machineTokenEnabled, allowedFeeTokens: configuredAllowedFeeTokens, amount, confirmationTimeoutMs = 30_000, currency = defaults.resolveCurrency(parameters), decimals = defaults.decimals, description, externalId, feeToken: configuredFeeToken, feePayerPolicy, html, relay, sponsorBudget, splits, supportedModes, validateSender, waitForConfirmation = true, zones, } = parameters;
40
+ const { machineTokenEnabled, allowedFeeTokens: configuredAllowedFeeTokens, amount, confirmationTimeoutMs = 30_000, currency = defaults.resolveCurrency(parameters), decimals = defaults.decimals, description, externalId, feeToken: configuredFeeToken, feePayerPolicy, html, relay, sponsorBudget, splits, supportedModes, validateSender, waitForConfirmation = true, zoneCredentialGraceMs = 0, zones, } = parameters;
41
+ if (!Number.isFinite(zoneCredentialGraceMs) ||
42
+ zoneCredentialGraceMs < 0 ||
43
+ zoneCredentialGraceMs > Zone.redemptionGraceMs)
44
+ throw new Error(`\`zoneCredentialGraceMs\` must be between 0 and ${Zone.redemptionGraceMs} milliseconds.`);
45
+ // A relay verifies credentials itself, without the local check that a late `zone` credential
46
+ // settled before its challenge expired, so it can't honor the grace safely.
47
+ if (relay && zoneCredentialGraceMs > 0)
48
+ throw new Error('`zoneCredentialGraceMs` is not supported with `relay`.');
49
+ /**
50
+ * Grace for a credential presented after its challenge expired: only a `zone` credential gets
51
+ * one, and only for a challenge issued with the grace on. A challenge issued without it (by an
52
+ * earlier release, whose replay claims end at the expiry, or with no grace) gets none.
53
+ */
54
+ const graceMsFor = (credential) => zoneCredentialGraceMs > 0 &&
55
+ isZoneCredential(credential) &&
56
+ ChallengeMeta.hasExpiryGrace(credential.challenge)
57
+ ? zoneCredentialGraceMs
58
+ : undefined;
38
59
  if (configuredAllowedFeeTokens?.length === 0)
39
60
  throw new Error('`allowedFeeTokens` must contain at least one token.');
40
61
  const storeKeyPrefix = parameters.storeKeyPrefix ?? '';
@@ -97,7 +118,7 @@ export function charge(parameters = {}) {
97
118
  ? MachineTokenCharge.getSettlementSender(chainId)
98
119
  : undefined;
99
120
  const isZeroAmount = BigInt(amount) === 0n;
100
- Expires.assert(challenge.expires, challenge.id);
121
+ CredentialExpiry.assert(credential, graceMsFor(credential));
101
122
  if (isZeroAmount && payload.type !== 'proof')
102
123
  throw new MismatchError('Zero-amount challenges require a proof credential.', {});
103
124
  // Request-level local sponsorship takes precedence over the hosted provider.
@@ -239,6 +260,14 @@ export function charge(parameters = {}) {
239
260
  });
240
261
  if (!isChallengeBound([withdrawal.memo], { challengeId: challenge.id, realm: challenge.realm }))
241
262
  throw new CredentialReplayedError({ reason: 'memo is not bound to this challenge' });
263
+ // A credential presented after its challenge expired is accepted only for a withdrawal
264
+ // that settled before then; see `zoneCredentialGraceMs`.
265
+ const expiresAt = Date.parse(challenge.expires);
266
+ if (expiresAt <= Date.now()) {
267
+ const block = await getBlock(client, { blockNumber: receipt.blockNumber });
268
+ if (Number(block.timestamp) * 1000 >= expiresAt)
269
+ throw new PaymentExpiredError({ expires: challenge.expires });
270
+ }
242
271
  return { hash, portal, receipt, senderTag };
243
272
  }
244
273
  async function validateProofCredential(credential, payload, context) {
@@ -510,8 +539,8 @@ export function charge(parameters = {}) {
510
539
  ? request.feePayer
511
540
  : feePayer
512
541
  : undefined;
542
+ CredentialExpiry.assert(credential, graceMsFor(credential));
513
543
  const expires = challenge.expires;
514
- Expires.assert(expires, challenge.id);
515
544
  const replayExpires = Date.parse(expires);
516
545
  switch (validated.type) {
517
546
  case 'hash': {
@@ -537,7 +566,9 @@ export function charge(parameters = {}) {
537
566
  }
538
567
  case 'zone': {
539
568
  const { portal, receipt, senderTag } = validated;
540
- if (!(await tryClaimZoneWithdrawal(store, portal, senderTag, replayExpires))) {
569
+ // Held through the longest grace any server may grant, not only this one's, so an
570
+ // instance with a longer grace on the same store can't redeem the credential again.
571
+ if (!(await tryClaimZoneWithdrawal(store, portal, senderTag, replayExpires + Zone.redemptionGraceMs))) {
541
572
  throw new CredentialReplayedError({
542
573
  reason: 'Zone withdrawal has already been used',
543
574
  });
@@ -557,7 +588,8 @@ export function charge(parameters = {}) {
557
588
  const { fundingCurrency, isFeePayerTx, serializedTransaction, settlementSenders, transaction, transfers, } = validated;
558
589
  // Pre-broadcast dedup: catch exact byte-for-byte replays early.
559
590
  const hash = keccak256(serializedTransaction);
560
- if (!(await tryClaimHash(store, hash, replayExpires))) {
591
+ const owner = Secp256k1.randomPrivateKey();
592
+ if (!(await tryClaimHash(store, hash, replayExpires, owner))) {
561
593
  throw new CredentialReplayedError({
562
594
  reason: 'Transaction hash has already been used',
563
595
  });
@@ -642,7 +674,7 @@ export function charge(parameters = {}) {
642
674
  const serializedTransaction_final = await Transaction.serialize(Transaction.deserialize(completedTransaction.serializedTransaction));
643
675
  finalHash = keccak256(serializedTransaction_final);
644
676
  if (finalHash.toLowerCase() !== hash.toLowerCase()) {
645
- if (!(await tryClaimHash(store, finalHash, replayExpires)))
677
+ if (!(await tryClaimHash(store, finalHash, replayExpires, owner)))
646
678
  throw new CredentialReplayedError({
647
679
  reason: 'Transaction hash has already been used',
648
680
  });
@@ -804,9 +836,12 @@ export function charge(parameters = {}) {
804
836
  // Only a successful settlement consumes the credential. A signed
805
837
  // transaction can be mined at most once, so a retry re-broadcasts it
806
838
  // and recovers the receipt instead of being rejected as a replay.
807
- if (claimedFinalHash)
808
- await releaseHashUse(store, claimedFinalHash);
809
- await releaseHashUse(store, hash);
839
+ const cleanup = await Promise.allSettled([
840
+ ...(claimedFinalHash ? [releaseHashUse(store, claimedFinalHash, owner)] : []),
841
+ releaseHashUse(store, hash, owner),
842
+ ]);
843
+ if (cleanup.some((result) => result.status === 'rejected'))
844
+ console.error('mppx: replay claim cleanup failed; claims remain consumed until expiry');
810
845
  if (broadcastAttempted)
811
846
  throw error;
812
847
  throw await explainMachineTokenFailure(error, {
@@ -821,6 +856,7 @@ export function charge(parameters = {}) {
821
856
  }
822
857
  },
823
858
  });
859
+ CredentialExpiry.register(method, graceMsFor, { issue: zoneCredentialGraceMs > 0 });
824
860
  return relay ? Relay.configure(method, relay) : method;
825
861
  }
826
862
  /**
@@ -994,6 +1030,10 @@ async function assertTransferLogs(receipt, parameters) {
994
1030
  })();
995
1031
  if (!memoMatches)
996
1032
  continue;
1033
+ // A Zone portal's payout settles a Zone withdrawal, which pays only through its `zone`
1034
+ // credential, so the same settlement can't also be redeemed by transaction hash.
1035
+ if (Zone.isPortalAddress(log.args.from))
1036
+ continue;
997
1037
  if (!(await isValidTransferSender({
998
1038
  expectedSender: parameters.sender,
999
1039
  sender: log.args.from,
@@ -1097,11 +1137,16 @@ function getProofStoreKey(challengeId) {
1097
1137
  function getZoneWithdrawalStoreKey(portal, senderTag) {
1098
1138
  return `mppx:charge:zone:${portal.toLowerCase()}:${senderTag.toLowerCase()}`;
1099
1139
  }
1140
+ /** Whether a credential pays with a Zone withdrawal. */
1141
+ function isZoneCredential(credential) {
1142
+ const { payload } = credential;
1143
+ return (typeof payload === 'object' && payload !== null && 'type' in payload && payload.type === 'zone');
1144
+ }
1100
1145
  async function tryClaimZoneWithdrawal(store, portal, senderTag, expires) {
1101
1146
  return Store.tryClaim(store, getZoneWithdrawalStoreKey(portal, senderTag), expires);
1102
1147
  }
1103
- async function tryClaimHash(store, hash, expires) {
1104
- return Store.tryClaim(store, getHashStoreKey(hash), expires);
1148
+ async function tryClaimHash(store, hash, expires, owner) {
1149
+ return Store.tryClaim(store, getHashStoreKey(hash), expires, owner);
1105
1150
  }
1106
1151
  /** Whether a live replay marker holds `hash`, read without claiming it. */
1107
1152
  async function isHashUsed(store, hash) {
@@ -1112,8 +1157,8 @@ async function isHashUsed(store, hash) {
1112
1157
  return typeof expires !== 'number' || expires > Date.now();
1113
1158
  }
1114
1159
  /** @internal */
1115
- async function releaseHashUse(store, hash) {
1116
- await store.delete(getHashStoreKey(hash));
1160
+ async function releaseHashUse(store, hash, owner) {
1161
+ await Store.releaseClaim(store, getHashStoreKey(hash), owner);
1117
1162
  }
1118
1163
  function parseHashCredentialSource(parameters) {
1119
1164
  const { chainId, source } = parameters;