mppx 0.21.4 → 0.22.1

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 (77) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/BodyDigest.d.ts +3 -3
  3. package/dist/BodyDigest.js +5 -3
  4. package/dist/Challenge.js +12 -2
  5. package/dist/Credential.js +9 -1
  6. package/dist/Errors.d.ts +62 -8
  7. package/dist/Errors.js +57 -6
  8. package/dist/Store.d.ts +7 -4
  9. package/dist/Store.js +18 -8
  10. package/dist/cli/account.d.ts +2 -1
  11. package/dist/cli/account.js +22 -11
  12. package/dist/cli/cli.js +135 -135
  13. package/dist/cli/internal.js +1 -1
  14. package/dist/cli/plugins/index.js +12 -12
  15. package/dist/client/Budget.d.ts +49 -0
  16. package/dist/client/Budget.js +101 -0
  17. package/dist/client/Mppx.d.ts +8 -3
  18. package/dist/client/Mppx.js +55 -13
  19. package/dist/client/Spend.d.ts +134 -0
  20. package/dist/client/Spend.js +58 -0
  21. package/dist/client/core.d.ts +2 -0
  22. package/dist/client/core.js +2 -0
  23. package/dist/client/internal/Fetch.d.ts +23 -3
  24. package/dist/client/internal/Fetch.js +155 -37
  25. package/dist/client/internal/FundsMoved.d.ts +9 -0
  26. package/dist/client/internal/FundsMoved.js +18 -0
  27. package/dist/client/internal/SpendGate.d.ts +136 -0
  28. package/dist/client/internal/SpendGate.js +608 -0
  29. package/dist/client/internal/SpendHooks.d.ts +42 -0
  30. package/dist/client/internal/SpendHooks.js +36 -0
  31. package/dist/client/internal/protocols/Mcp.d.ts +9 -0
  32. package/dist/client/internal/protocols/Mcp.js +27 -0
  33. package/dist/client/internal/protocols/Mpp.js +20 -3
  34. package/dist/client/internal/protocols/Shared.js +29 -3
  35. package/dist/evm/client/Charge.js +20 -8
  36. package/dist/extensions/identity/attestation/client/index.js +1 -0
  37. package/dist/extensions/identity/attestation/server/index.js +1 -0
  38. package/dist/extensions/identity/email-otp/server/index.js +1 -0
  39. package/dist/extensions/identity/erc8004/client/index.js +1 -0
  40. package/dist/extensions/identity/erc8004/server/index.d.ts +7 -1
  41. package/dist/extensions/identity/erc8004/server/index.js +16 -2
  42. package/dist/extensions/identity/link/client/index.js +57 -5
  43. package/dist/extensions/identity/link/server/index.js +1 -0
  44. package/dist/extensions/identity/poppy/server/index.js +1 -0
  45. package/dist/extensions/identity/tempo/client/index.js +1 -0
  46. package/dist/extensions/identity/tempo/server/index.js +7 -1
  47. package/dist/extensions/identity/world/server/index.js +1 -0
  48. package/dist/identity/Client.d.ts +7 -3
  49. package/dist/identity/Client.js +178 -13
  50. package/dist/identity/Headers.d.ts +3 -2
  51. package/dist/identity/Headers.js +3 -2
  52. package/dist/identity/Server.d.ts +8 -0
  53. package/dist/identity/Server.js +18 -0
  54. package/dist/identity/Types.d.ts +18 -3
  55. package/dist/integrations/x402/Negotiator.js +4 -1
  56. package/dist/integrations/x402/Solana.d.ts +75 -0
  57. package/dist/integrations/x402/Solana.js +143 -0
  58. package/dist/internal/challengeMeta.d.ts +17 -2
  59. package/dist/internal/challengeMeta.js +35 -7
  60. package/dist/internal/version.d.ts +2 -2
  61. package/dist/internal/version.js +1 -1
  62. package/dist/mcp/client/McpClient.d.ts +6 -1
  63. package/dist/mcp/client/McpClient.js +48 -10
  64. package/dist/proxy/Proxy.js +59 -46
  65. package/dist/proxy/internal/Headers.d.ts +9 -2
  66. package/dist/proxy/internal/Headers.js +16 -3
  67. package/dist/server/Mppx.d.ts +14 -1
  68. package/dist/server/Mppx.js +59 -6
  69. package/dist/server/Transport.js +46 -2
  70. package/dist/stripe/server/internal/html.gen.js +1 -1
  71. package/dist/tempo/client/Charge.js +81 -17
  72. package/dist/tempo/server/Charge.d.ts +7 -1
  73. package/dist/tempo/server/Charge.js +98 -12
  74. package/dist/tempo/server/internal/html.gen.js +1 -1
  75. package/dist/tempo/session/client/SessionManager.js +3 -0
  76. package/dist/x402/server/EvmCharge.js +3 -0
  77. package/package.json +1 -1
@@ -3,7 +3,9 @@ import { keccak256, parseEventLogs, parseUnits, } from 'viem';
3
3
  import { prepareTransactionRequest, readContract, sendCallsSync, sendRawTransactionSync, sendTransactionSync, signTypedData, signTransaction, waitForTransactionReceipt, } from 'viem/actions';
4
4
  import { Abis, Actions, Addresses } from 'viem/tempo';
5
5
  import { tempo as tempo_chain } from 'viem/tempo/chains';
6
+ import * as FundsMoved from '../../client/internal/FundsMoved.js';
6
7
  import * as MethodResponse from '../../client/internal/MethodResponse.js';
8
+ import * as SpendHooks from '../../client/internal/SpendHooks.js';
7
9
  import * as Credential from '../../Credential.js';
8
10
  import * as Currency from '../../Currency.js';
9
11
  import * as Errors from '../../Errors.js';
@@ -90,6 +92,10 @@ export function charge(parameters = {}) {
90
92
  context: chargeContextSchema,
91
93
  async createCredential(credentialParameters) {
92
94
  const { challenge, context } = credentialParameters;
95
+ // Set when the client's spending options checked this payment.
96
+ const spend = SpendHooks.of(credentialParameters);
97
+ // Spending checks were skipped to resume an outstanding withdrawal: never pay anew.
98
+ const notResumable = () => new Error('The Zone withdrawal this challenge resumes is no longer outstanding. Retry the request to pay it.');
93
99
  assertChallengePolicy(parameters, caps, challenge.request);
94
100
  // Sign on the pinned chain when the challenge omits a chain ID.
95
101
  const challengeChainId = challenge.request.methodDetails?.chainId;
@@ -143,6 +149,8 @@ export function charge(parameters = {}) {
143
149
  const outstanding = findZoneWithdrawal(options);
144
150
  if (outstanding)
145
151
  return resumeZoneCredential(options, outstanding);
152
+ if (spend?.resume)
153
+ throw notResumable();
146
154
  // With nothing outstanding, an expired challenge can't be paid: its server refuses any
147
155
  // credential for it, so a payment on Tempo would be lost.
148
156
  if (challenge.expires)
@@ -150,6 +158,8 @@ export function charge(parameters = {}) {
150
158
  if (settlesBeforeExpiry(challenge.expires, parameters.zone.settlementTimeoutMs))
151
159
  return createZoneCredential(options);
152
160
  }
161
+ if (spend?.resume)
162
+ throw notResumable();
153
163
  const defaultAccount = getAccount(client, context);
154
164
  const resolveAccount = async (operation) => (await parameters.resolveAccount?.({
155
165
  account: defaultAccount,
@@ -178,11 +188,14 @@ export function charge(parameters = {}) {
178
188
  }
179
189
  const currency = request.currency;
180
190
  const isMachineTokenCurrency = MachineTokenCharge.isMachineToken({ chainId, currency });
181
- const memo = Attribution.encode({
182
- challengeId: challenge.id,
183
- clientId,
184
- serverId: challenge.realm,
185
- });
191
+ // A memo the server requires (`methodDetails.memo`, which other MPP servers may set)
192
+ // goes on the primary transfer as is; otherwise the optional attribution memo does.
193
+ const memo = methodDetails?.memo ??
194
+ Attribution.encode({
195
+ challengeId: challenge.id,
196
+ clientId,
197
+ serverId: challenge.realm,
198
+ });
186
199
  const transfers = Charge_internal.getTransfers({
187
200
  amount,
188
201
  methodDetails: {
@@ -198,7 +211,9 @@ export function charge(parameters = {}) {
198
211
  token: currency,
199
212
  }));
200
213
  const autoSwap = AutoSwap.resolve(context?.autoSwap ?? parameters.autoSwap, AutoSwap.defaultCurrencies);
201
- const machineTokenEnabled = methodDetails?.machineTokenEnabled === true;
214
+ // Spending options checked the charge currency, so under them the payment debits only that
215
+ // currency, never MACH.
216
+ const machineTokenEnabled = methodDetails?.machineTokenEnabled === true && !spend;
202
217
  const machineTokenCandidate = machineTokenEnabled
203
218
  ? MachineTokenCharge.getRoute({ chainId, currency, transfers })
204
219
  : undefined;
@@ -249,6 +264,13 @@ export function charge(parameters = {}) {
249
264
  maxAmountIn: autoSwap.maxAmountIn,
250
265
  })
251
266
  : undefined;
267
+ // A swap debits another token, by up to its slippage, which spending options never
268
+ // checked: refuse it. A funder can swap into the charge currency beforehand.
269
+ if (spend && swapCalls)
270
+ throw new Errors.PaymentLimitExceededError({
271
+ limit: spend.limit,
272
+ reason: 'asset',
273
+ });
252
274
  // Without MACH or the charge currency the payment can only revert, so say where to buy MACH.
253
275
  if (machineTokenUnpayable && !autoSwap) {
254
276
  const error = await getMachineTokenFundingError(client, {
@@ -296,7 +318,14 @@ export function charge(parameters = {}) {
296
318
  const challengeExpiry = Math.floor(new Date(challenge.expires).getTime() / 1000) + 1;
297
319
  return Math.min(defaultExpiry, challengeExpiry);
298
320
  })();
321
+ // The client's spending checks can outlast the challenge, and its server refuses a credential
322
+ // for an expired one: under them, never broadcast or sign for it.
323
+ const assertUnexpired = () => {
324
+ if (spend && challenge.expires)
325
+ Expires.assert(challenge.expires, challenge.id);
326
+ };
299
327
  if (mode === 'push') {
328
+ assertUnexpired();
300
329
  const { receipts } = account.type === 'local'
301
330
  ? {
302
331
  receipts: [
@@ -317,8 +346,9 @@ export function charge(parameters = {}) {
317
346
  forceAtomic: calls.length > 1,
318
347
  });
319
348
  const hash = receipts?.[0]?.transactionHash;
349
+ // The calls were sent and may have paid, so spending limits keep counting them.
320
350
  if (!hash)
321
- throw new Error('No transaction receipt returned.');
351
+ throw FundsMoved.mark(new Error('No transaction receipt returned.'));
322
352
  return Credential.serialize({
323
353
  challenge,
324
354
  payload: { hash, type: 'hash' },
@@ -361,6 +391,7 @@ export function charge(parameters = {}) {
361
391
  }
362
392
  // Preparation is asynchronous: check again immediately before signing.
363
393
  assertSponsorable();
394
+ assertUnexpired();
364
395
  const signature = await signTransaction(client, prepared);
365
396
  return Credential.serialize({
366
397
  challenge,
@@ -378,14 +409,26 @@ export function charge(parameters = {}) {
378
409
  const account = options.context?.account ?? parameters.account;
379
410
  const signer = (typeof account === 'string' ? account : account?.address)?.toLowerCase();
380
411
  const key = `${signer ?? ''}:${options.challenge.id}`;
381
- let promise = signing.get(key);
382
- if (!promise) {
383
- promise = method.createCredential(options).finally(() => signing.delete(key));
384
- signing.set(key, promise);
385
- }
412
+ const constraints = SpendHooks.of(options);
413
+ const shared = signing.get(key);
414
+ // One signing is one payment: the client's spending options count it for the call that
415
+ // started it, not again for each call that joins it. A retry that starts its own signing,
416
+ // such as one resuming a Zone payment, is counted for itself.
417
+ if (constraints)
418
+ SpendHooks.join(constraints, shared?.constraints);
419
+ if (shared)
420
+ return shared.promise;
421
+ const promise = method.createCredential(options).finally(() => signing.delete(key));
422
+ signing.set(key, { constraints, promise });
386
423
  return promise;
387
424
  };
388
- return MethodResponse.registerTransactionHash({ ...method, createCredential }, transactionHash);
425
+ return SpendHooks.register(MethodResponse.registerTransactionHash({ ...method, createCredential }, transactionHash), {
426
+ // The client's spending options refuse what this policy refuses before any funder runs.
427
+ assert: (challenge) => assertChallengePolicy(parameters, caps, challenge.request),
428
+ // A withdrawal already sent for this challenge was counted when it started.
429
+ resumes: (challenge) => hasZoneWithdrawal(pendingZoneWithdrawals, challenge, parameters.zone &&
430
+ (parameters.zone.zoneId ?? Zone.idFromChainId(parameters.zone.client.chain?.id ?? 0))),
431
+ });
389
432
  }
390
433
  /**
391
434
  * Returns an error that links to the MACH onramp when a machine-token-enabled charge can't be paid:
@@ -493,6 +536,26 @@ function findZoneWithdrawal(options) {
493
536
  }
494
537
  return undefined;
495
538
  }
539
+ /**
540
+ * Whether creating this challenge's credential resumes a withdrawal already started, as
541
+ * {@link findZoneWithdrawal} would find, rather than paying: its own, or one with the same terms
542
+ * that can still be redeemed and no call is waiting on. It only reads `pending`.
543
+ */
544
+ function hasZoneWithdrawal(pending, challenge, zoneId) {
545
+ if (zoneId === undefined || pending.size === 0)
546
+ return false;
547
+ if (pending.has(zoneWithdrawalKey(challenge)))
548
+ return true;
549
+ const terms = zoneTermsKey(challenge, zoneId);
550
+ if (terms === undefined)
551
+ return false;
552
+ for (const entry of pending.values())
553
+ if (entry.terms === terms &&
554
+ isRedeemable(entry.challenge.expires) &&
555
+ (entry.redeemedLate || entry.waiters === 0))
556
+ return true;
557
+ return false;
558
+ }
496
559
  /**
497
560
  * Waits for an outstanding withdrawal to settle and returns a `zone` credential for the
498
561
  * challenge it pays. A withdrawal started for an earlier challenge pays only that challenge,
@@ -531,7 +594,8 @@ async function waitForZoneCredential(options, entry) {
531
594
  const error = new Error(`Zone withdrawal transaction ${withdrawal.transactionHash} was sent, but its sender tag could not be read from the Zone. Retry the challenge to resume without withdrawing again.`);
532
595
  // Defined manually (non-enumerable, like native `cause`) so consumers on pre-ES2022 libs still typecheck.
533
596
  Object.defineProperty(error, 'cause', { configurable: true, value: cause, writable: true });
534
- throw error;
597
+ // The withdrawal was mined, so spending limits keep counting it.
598
+ throw FundsMoved.mark(error);
535
599
  }));
536
600
  let settled;
537
601
  try {
@@ -726,9 +790,9 @@ async function requestZoneWithdrawal(options, state) {
726
790
  hash,
727
791
  timeout: zoneReceiptRecoveryTimeoutMs,
728
792
  }).catch(() => {
729
- const error = new Error(`Zone withdrawal outcome is unknown: transaction ${hash} may have been sent. Retrying this challenge does not withdraw again.`);
730
- // Defined manually (non-enumerable, like native `cause`) so consumers on pre-ES2022 libs still typecheck.
731
- Object.defineProperty(error, 'cause', { configurable: true, value: cause, writable: true });
793
+ // Typed so spending limits keep counting a payment that may have moved funds.
794
+ const error = new Errors.BroadcastOutcomeUnknownError({ cause, transactionHash: hash });
795
+ error.message = `Zone withdrawal outcome is unknown: transaction ${hash} may have been sent. Retrying this challenge does not withdraw again.`;
732
796
  throw error;
733
797
  }));
734
798
  // A reverted withdrawal moved nothing, so the challenge may be retried.
@@ -23,7 +23,7 @@ import * as SponsorBudget from './SponsorBudget.js';
23
23
  export declare function charge<const parameters extends charge.Parameters>(parameters?: NoExtraKeys<parameters, charge.Parameters>): Method.Server<typeof Methods.charge, charge.DeriveDefaults<parameters>>;
24
24
  export declare namespace charge {
25
25
  type StoreItemMap = {
26
- [key: `mppx:charge:${string}`]: number | SponsorBudget.State | Store.ReplayMarker;
26
+ [key: `mppx:charge:${string}`]: number | SponsorBudget.State | Store.ReplayMarker | BroadcastMarker;
27
27
  };
28
28
  type Defaults = LooseOmit<Method.RequestDefaults<typeof Methods.charge>, 'feePayer' | 'recipient'>;
29
29
  type ValidateSender = (parameters: ValidateSenderParameters) => boolean | Promise<boolean>;
@@ -209,5 +209,11 @@ type ExpectedTransfer = {
209
209
  memo?: `0x${string}` | undefined;
210
210
  recipient: `0x${string}`;
211
211
  };
212
+ /** A broadcast this server sent for a challenge whose outcome was unknown. */
213
+ type BroadcastMarker = {
214
+ challengeId: string;
215
+ expires: number;
216
+ type: 'mppx:broadcast';
217
+ };
212
218
  export {};
213
219
  //# sourceMappingURL=Charge.d.ts.map
@@ -4,7 +4,7 @@ import { decodeFunctionData, formatUnits, keccak256, parseEventLogs, WaitForTran
4
4
  import { getTransaction, getBlock, getTransactionReceipt, sendRawTransaction, sendRawTransactionSync, signTransaction, verifyTypedData, waitForTransactionReceipt, call as viem_call, } from 'viem/actions';
5
5
  import { Abis, Actions, Transaction } from 'viem/tempo';
6
6
  import { tempo as tempo_chain } from 'viem/tempo/chains';
7
- import { BroadcastOutcomeUnknownError, CredentialReplayedError, PaymentError, PaymentExpiredError, VerificationFailedError, } from '../../Errors.js';
7
+ import { BroadcastOutcomeUnknownError, CredentialReplayedError, InvalidChallengeError, PaymentError, PaymentExpiredError, VerificationFailedError, } from '../../Errors.js';
8
8
  import * as Expires from '../../Expires.js';
9
9
  import * as ChallengeMeta from '../../internal/challengeMeta.js';
10
10
  import * as CredentialExpiry from '../../internal/CredentialExpiry.js';
@@ -65,6 +65,8 @@ export function charge(parameters = {}) {
65
65
  (relay
66
66
  ? Store.memory()
67
67
  : fallbackStore('tempo.charge')));
68
+ if (!relay && rawStore.tryClaim && !rawStore.releaseClaim)
69
+ throw new Error('Tempo charge requires a custom store with atomic releaseClaim support. Migrate the store before use.');
68
70
  const store = Store.from(rawStore, { keyPrefix: storeKeyPrefix });
69
71
  const { maxInFlightReservations: legacyMaxInFlightReservations, maxInFlightTotalFee: legacyMaxInFlightTotalFee, ...transactionFeePayerPolicy } = feePayerPolicy ?? {};
70
72
  const sponsorBudgetConfig = sponsorBudget === false ? undefined : (sponsorBudget ?? {});
@@ -201,9 +203,11 @@ export function charge(parameters = {}) {
201
203
  transfers,
202
204
  validateSender,
203
205
  });
206
+ // A push payment (hash credential) must carry the challenge-bound attribution memo.
204
207
  assertChallengeBoundMemo(matchedLogs, {
205
208
  challengeId: challenge.id,
206
209
  realm: challenge.realm,
210
+ required: true,
207
211
  });
208
212
  // The payer is the account the matched transfers debited, not the submitter.
209
213
  // Settlement-contract transfers are funded by the transaction sender.
@@ -258,8 +262,13 @@ export function charge(parameters = {}) {
258
262
  throw new MismatchError('Payment verification failed: Zone withdrawal not found.', {
259
263
  senderTag,
260
264
  });
261
- if (!isChallengeBound([withdrawal.memo], { challengeId: challenge.id, realm: challenge.realm }))
262
- throw new CredentialReplayedError({ reason: 'memo is not bound to this challenge' });
265
+ // A push payment (Zone withdrawal) must carry the challenge-bound attribution memo.
266
+ if (!isChallengeBound([withdrawal.memo], {
267
+ challengeId: challenge.id,
268
+ realm: challenge.realm,
269
+ required: true,
270
+ }))
271
+ throw new MismatchError('Payment verification failed: memo is not bound to this challenge.', {});
263
272
  // A credential presented after its challenge expired is accepted only for a withdrawal
264
273
  // that settled before then; see `zoneCredentialGraceMs`.
265
274
  const expiresAt = Date.parse(challenge.expires);
@@ -364,6 +373,13 @@ export function charge(parameters = {}) {
364
373
  };
365
374
  }
366
375
  async function validateCredential(credential, request, context) {
376
+ // Push and proof credentials are bound only to the Challenge ID. Without a per-issuance
377
+ // nonce, every requester of the route can hold that ID and redeem someone else's payment.
378
+ if (context.payload.type !== 'transaction' && !ChallengeMeta.hasNonce(credential.challenge))
379
+ throw new InvalidChallengeError({
380
+ id: credential.challenge.id,
381
+ reason: `${context.payload.type} credentials need a challenge with a nonce`,
382
+ });
367
383
  switch (context.payload.type) {
368
384
  case 'hash': {
369
385
  const { payer, receipt, sender, transfers } = await validateHashCredential(credential, context.payload, context);
@@ -595,6 +611,9 @@ export function charge(parameters = {}) {
595
611
  });
596
612
  }
597
613
  let broadcastAttempted = false;
614
+ // Set when the node already held the transaction from someone else,
615
+ // so an unknown outcome is not remembered as this server's own.
616
+ let duplicateElsewhere = false;
598
617
  let finalHash;
599
618
  // Set only after this request claims the final hash, so cleanup never
600
619
  // releases a marker that another request holds.
@@ -742,6 +761,11 @@ export function charge(parameters = {}) {
742
761
  ? Number.POSITIVE_INFINITY
743
762
  : transaction.validBefore * 1_000 + 2_000;
744
763
  let receipt;
764
+ // Set when the node already held the transaction this server
765
+ // sent: someone else (another server, or anyone who saw it
766
+ // pending) may have submitted it, so its receipt pays this
767
+ // challenge only with an attribution memo bound to it.
768
+ let submittedElsewhere = false;
745
769
  try {
746
770
  receipt = await withDeadline(sendRawTransactionSync(client, {
747
771
  serializedTransaction: serializedTransaction_final,
@@ -751,6 +775,12 @@ export function charge(parameters = {}) {
751
775
  catch (broadcastError) {
752
776
  if (!isAmbiguousBroadcastError(broadcastError))
753
777
  throw broadcastError;
778
+ // A duplicate of this server's own earlier broadcast for this
779
+ // challenge, whose outcome was unknown, is not someone else's.
780
+ submittedElsewhere =
781
+ isDuplicateBroadcastError(broadcastError) &&
782
+ !(await isOwnBroadcast(store, finalHash, challenge.id));
783
+ duplicateElsewhere = submittedElsewhere;
754
784
  // The node may have accepted the transaction, so poll for its receipt.
755
785
  const timeout = Math.min(deadline, validUntil) - Date.now();
756
786
  let recovered;
@@ -771,6 +801,10 @@ export function charge(parameters = {}) {
771
801
  validBefore: transaction.validBefore,
772
802
  });
773
803
  receipt = recovered;
804
+ // The record of this server's own broadcast may have landed while
805
+ // polling, written by the request whose outcome was unknown.
806
+ if (submittedElsewhere && (await isOwnBroadcast(store, finalHash, challenge.id)))
807
+ submittedElsewhere = duplicateElsewhere = false;
774
808
  }
775
809
  if (reservation)
776
810
  await SponsorBudget.release(sponsorBudgetStore, reservation);
@@ -783,11 +817,15 @@ export function charge(parameters = {}) {
783
817
  assertChallengeBoundMemo(matchedLogs, {
784
818
  challengeId: challenge.id,
785
819
  realm: challenge.realm,
820
+ required: submittedElsewhere && !isFeePayerTx,
786
821
  });
787
822
  if (receipt.transactionHash.toLowerCase() !== finalHash.toLowerCase())
788
823
  throw new VerificationFailedError({
789
824
  reason: 'Broadcast transaction hash does not match the signed transaction',
790
825
  });
826
+ // The transfer has settled: a marker left behind expires on its own and
827
+ // must not fail the payment.
828
+ await store.delete(getBroadcastStoreKey(finalHash)).catch(() => { });
791
829
  return toReceipt(receipt.transactionHash, fundingCurrency);
792
830
  }
793
831
  // Optimistic path: broadcast without waiting for confirmation
@@ -833,6 +871,21 @@ export function charge(parameters = {}) {
833
871
  console.error('mppx: sponsor budget cleanup error', budgetError);
834
872
  }
835
873
  }
874
+ // Remember a broadcast of this server's own whose outcome is
875
+ // unknown, for this challenge only, so a retry that finds the node
876
+ // already holding it recovers it as this server's own. It is written
877
+ // before the claims are released, so a concurrent retry that takes a
878
+ // released claim already sees it.
879
+ // A duplicate of someone else's submission leaves no record: this
880
+ // server has no evidence it sent the transaction.
881
+ if (error instanceof BroadcastOutcomeUnknownError && finalHash && !duplicateElsewhere)
882
+ await store
883
+ .put(getBroadcastStoreKey(finalHash), {
884
+ challengeId: challenge.id,
885
+ expires: Math.max(expires ? Date.parse(expires) : Date.now() + 3_600_000, (transaction.validBefore ?? 0) * 1_000) + 60_000,
886
+ type: 'mppx:broadcast',
887
+ })
888
+ .catch(() => { });
836
889
  // Only a successful settlement consumes the credential. A signed
837
890
  // transaction can be mined at most once, so a retry re-broadcasts it
838
891
  // and recovers the receipt instead of being rejected as a replay.
@@ -1148,6 +1201,20 @@ async function tryClaimZoneWithdrawal(store, portal, senderTag, expires) {
1148
1201
  async function tryClaimHash(store, hash, expires, owner) {
1149
1202
  return Store.tryClaim(store, getHashStoreKey(hash), expires, owner);
1150
1203
  }
1204
+ function getBroadcastStoreKey(hash) {
1205
+ return `mppx:charge:broadcast:${hash.toLowerCase()}`;
1206
+ }
1207
+ /** Whether this server broadcast `hash` for `challengeId` on an earlier attempt. */
1208
+ async function isOwnBroadcast(store, hash, challengeId) {
1209
+ const marker = await store.get(getBroadcastStoreKey(hash)).catch(() => null);
1210
+ if (typeof marker !== 'object' || marker === null)
1211
+ return false;
1212
+ const { challengeId: recorded, expires, type } = marker;
1213
+ return (type === 'mppx:broadcast' &&
1214
+ recorded === challengeId &&
1215
+ typeof expires === 'number' &&
1216
+ expires > Date.now());
1217
+ }
1151
1218
  /** Whether a live replay marker holds `hash`, read without claiming it. */
1152
1219
  async function isHashUsed(store, hash) {
1153
1220
  const current = await store.get(getHashStoreKey(hash));
@@ -1262,6 +1329,22 @@ function isAmbiguousBroadcastError(error) {
1262
1329
  }
1263
1330
  return false;
1264
1331
  }
1332
+ /**
1333
+ * Whether a failed synchronous broadcast says the node already holds the
1334
+ * transaction ("already known", "known transaction" or Tempo's
1335
+ * `ExpiringNonceReplay`), matched anywhere in the `cause` chain.
1336
+ */
1337
+ function isDuplicateBroadcastError(error) {
1338
+ for (let cause = error; cause; cause = cause.cause) {
1339
+ if (typeof cause !== 'object')
1340
+ return false;
1341
+ const { message } = cause;
1342
+ if (typeof message === 'string' &&
1343
+ /\balready ?known\b|\bknown transaction\b|\bExpiringNonceReplay\b/i.test(message))
1344
+ return true;
1345
+ }
1346
+ return false;
1347
+ }
1265
1348
  /** Rejects with `error` if `promise` has not settled by `deadline` (epoch ms). */
1266
1349
  async function withDeadline(promise, deadline, error) {
1267
1350
  let timer;
@@ -1289,9 +1372,8 @@ function toReceipt(reference, fundingCurrency) {
1289
1372
  }
1290
1373
  function assertChallengeBoundMemo(matchedLogs, parameters) {
1291
1374
  const memos = matchedLogs.map((log) => (log.kind === 'memo' ? log.args.memo : undefined));
1292
- // The transfer already settled to the recipient, so another payment would not help.
1293
1375
  if (!isChallengeBound(memos, parameters))
1294
- throw new CredentialReplayedError({ reason: 'memo is not bound to this challenge' });
1376
+ throw new MismatchError('Payment verification failed: memo is not bound to this challenge.', {});
1295
1377
  }
1296
1378
  function assertChallengeBoundCallMemo(matchedCalls, parameters) {
1297
1379
  const memos = matchedCalls.map((call) => call.memo);
@@ -1299,10 +1381,13 @@ function assertChallengeBoundCallMemo(matchedCalls, parameters) {
1299
1381
  throw new MismatchError('Payment verification failed: memo is not bound to this challenge.', {});
1300
1382
  }
1301
1383
  /**
1302
- * Whether matched payment transfers carry a challenge-bound attribution memo and
1303
- * no conflicting attribution. Otherwise, a split payment could authorize another
1304
- * challenge after the first challenge's replay marker expires. Unmatched transfers
1305
- * cannot establish the binding; plain transfers and non-MPP memos remain allowed.
1384
+ * Whether the matched payment transfers are bound to this challenge. Any attribution memo
1385
+ * that is not for this challenge's realm and ID is rejected, whatever the credential type:
1386
+ * a pull payment carrying another realm's attribution memo could later be presented to that
1387
+ * realm as a push payment, and that realm keeps no record of it. With required (push
1388
+ * payments), at least one matched transfer must also carry an attribution memo bound to this
1389
+ * challenge. Otherwise (pull payments) plain transfers and memos not in attribution format
1390
+ * are accepted.
1306
1391
  * @internal
1307
1392
  */
1308
1393
  function isChallengeBound(memos, parameters) {
@@ -1310,12 +1395,13 @@ function isChallengeBound(memos, parameters) {
1310
1395
  for (const memo of memos) {
1311
1396
  if (!memo || !Attribution.isMppMemo(memo))
1312
1397
  continue;
1313
- if (!Attribution.verifyServer(memo, parameters.realm) ||
1314
- !Attribution.verifyChallengeBinding(memo, parameters.challengeId))
1398
+ if (!Attribution.verifyServer(memo, parameters.realm))
1399
+ return false;
1400
+ if (!Attribution.verifyChallengeBinding(memo, parameters.challengeId))
1315
1401
  return false;
1316
1402
  bound = true;
1317
1403
  }
1318
- return bound;
1404
+ return bound || !parameters.required;
1319
1405
  }
1320
1406
  /** @internal */
1321
1407
  class MismatchError extends PaymentError {