mppx 0.18.0 → 0.19.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 (132) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/dist/Currency.d.ts +59 -0
  3. package/dist/Currency.js +60 -0
  4. package/dist/Errors.d.ts +24 -4
  5. package/dist/Errors.js +28 -10
  6. package/dist/cli/cli.js +135 -135
  7. package/dist/cli/plugins/index.js +12 -12
  8. package/dist/cli/plugins/tempo.js +13 -1
  9. package/dist/client/internal/Fetch.d.ts +5 -0
  10. package/dist/client/internal/Fetch.js +7 -0
  11. package/dist/cloudflare/ChannelStore.d.ts +1 -2
  12. package/dist/cloudflare/ChannelStore.js +14 -20
  13. package/dist/cloudflare/Channels.d.ts +20 -2
  14. package/dist/cloudflare/Channels.js +47 -4
  15. package/dist/cloudflare/index.d.ts +1 -1
  16. package/dist/cloudflare/index.js +1 -1
  17. package/dist/discovery/Discovery.d.ts +116 -9
  18. package/dist/discovery/Discovery.js +169 -0
  19. package/dist/evm/server/Charge.js +2 -3
  20. package/dist/evm/server/Methods.d.ts +1 -1
  21. package/dist/evm/server/Methods.js +3 -2
  22. package/dist/extensions/identity/Types.d.ts +26 -0
  23. package/dist/extensions/identity/attestation/Token.d.ts +6 -4
  24. package/dist/extensions/identity/attestation/Token.js +11 -5
  25. package/dist/extensions/identity/email-otp/client/index.js +4 -4
  26. package/dist/extensions/identity/index.d.ts +6 -0
  27. package/dist/extensions/identity/index.js +6 -0
  28. package/dist/extensions/identity/internal/HttpMessageSignature.d.ts +2 -2
  29. package/dist/extensions/identity/internal/HttpMessageSignature.js +13 -10
  30. package/dist/extensions/identity/{web-bot-auth/internal → internal}/JwkThumbprint.js +1 -1
  31. package/dist/extensions/identity/internal/Signer.d.ts +20 -0
  32. package/dist/extensions/identity/internal/Signer.js +94 -0
  33. package/dist/extensions/identity/link/Constants.d.ts +102 -0
  34. package/dist/extensions/identity/link/Constants.js +16 -0
  35. package/dist/extensions/identity/link/client/index.d.ts +80 -0
  36. package/dist/extensions/identity/link/client/index.js +211 -0
  37. package/dist/extensions/identity/link/index.d.ts +12 -0
  38. package/dist/extensions/identity/link/index.js +12 -0
  39. package/dist/extensions/identity/link/server/index.d.ts +124 -0
  40. package/dist/extensions/identity/link/server/index.js +518 -0
  41. package/dist/extensions/identity/persona/Constants.d.ts +24 -0
  42. package/dist/extensions/identity/persona/Constants.js +24 -0
  43. package/dist/extensions/identity/persona/Did.d.ts +24 -0
  44. package/dist/extensions/identity/persona/Did.js +24 -0
  45. package/dist/extensions/identity/persona/Types.d.ts +21 -0
  46. package/dist/extensions/identity/persona/Types.js +2 -0
  47. package/dist/extensions/identity/persona/index.d.ts +10 -0
  48. package/dist/extensions/identity/persona/index.js +9 -0
  49. package/dist/extensions/identity/persona/server/index.d.ts +152 -0
  50. package/dist/extensions/identity/persona/server/index.js +263 -0
  51. package/dist/extensions/identity/tap/client/index.d.ts +6 -2
  52. package/dist/extensions/identity/tap/client/index.js +2 -0
  53. package/dist/extensions/identity/tempo/Constants.d.ts +14 -0
  54. package/dist/extensions/identity/tempo/Constants.js +14 -0
  55. package/dist/extensions/identity/tempo/Types.d.ts +31 -0
  56. package/dist/extensions/identity/tempo/Types.js +2 -0
  57. package/dist/extensions/identity/tempo/client/index.d.ts +34 -0
  58. package/dist/extensions/identity/tempo/client/index.js +60 -0
  59. package/dist/extensions/identity/tempo/index.d.ts +5 -0
  60. package/dist/extensions/identity/tempo/index.js +4 -0
  61. package/dist/extensions/identity/tempo/internal/Jwt.d.ts +36 -0
  62. package/dist/extensions/identity/tempo/internal/Jwt.js +114 -0
  63. package/dist/extensions/identity/tempo/server/index.d.ts +65 -0
  64. package/dist/extensions/identity/tempo/server/index.js +247 -0
  65. package/dist/extensions/identity/web-bot-auth/client/index.d.ts +6 -4
  66. package/dist/extensions/identity/web-bot-auth/client/index.js +7 -5
  67. package/dist/extensions/identity/web-bot-auth/server/index.js +1 -1
  68. package/dist/extensions/identity/world/Constants.d.ts +50 -0
  69. package/dist/extensions/identity/world/Constants.js +50 -0
  70. package/dist/extensions/identity/world/Types.d.ts +52 -0
  71. package/dist/extensions/identity/world/Types.js +2 -0
  72. package/dist/extensions/identity/world/client/index.d.ts +103 -0
  73. package/dist/extensions/identity/world/client/index.js +208 -0
  74. package/dist/extensions/identity/world/index.d.ts +6 -0
  75. package/dist/extensions/identity/world/index.js +5 -0
  76. package/dist/extensions/identity/world/internal/Idp.d.ts +50 -0
  77. package/dist/extensions/identity/world/internal/Idp.js +265 -0
  78. package/dist/extensions/identity/world/issuer/index.d.ts +120 -0
  79. package/dist/extensions/identity/world/issuer/index.js +520 -0
  80. package/dist/extensions/identity/world/server/index.d.ts +49 -0
  81. package/dist/extensions/identity/world/server/index.js +63 -0
  82. package/dist/identity/Headers.d.ts +6 -1
  83. package/dist/identity/Headers.js +11 -1
  84. package/dist/identity/Server.js +2 -0
  85. package/dist/identity/Types.d.ts +10 -0
  86. package/dist/index.d.ts +1 -0
  87. package/dist/index.js +1 -0
  88. package/dist/internal/version.d.ts +2 -2
  89. package/dist/internal/version.js +1 -1
  90. package/dist/proxy/internal/Headers.js +4 -4
  91. package/dist/server/Mppx.js +6 -2
  92. package/dist/stripe/server/internal/html.gen.js +1 -1
  93. package/dist/tempo/client/Charge.d.ts +11 -8
  94. package/dist/tempo/client/Charge.js +85 -18
  95. package/dist/tempo/index.d.ts +4 -0
  96. package/dist/tempo/index.js +4 -0
  97. package/dist/tempo/internal/auto-swap.d.ts +6 -5
  98. package/dist/tempo/internal/auto-swap.js +17 -2
  99. package/dist/tempo/internal/currencies.d.ts +5 -4
  100. package/dist/tempo/internal/currencies.js +13 -9
  101. package/dist/tempo/internal/defaults.d.ts +7 -0
  102. package/dist/tempo/internal/defaults.js +7 -0
  103. package/dist/tempo/internal/fee-payer.js +8 -2
  104. package/dist/tempo/internal/machine-token-charge.d.ts +52 -0
  105. package/dist/tempo/internal/machine-token-charge.js +82 -1
  106. package/dist/tempo/internal/zone.d.ts +27 -0
  107. package/dist/tempo/internal/zone.js +54 -7
  108. package/dist/tempo/server/Charge.js +59 -2
  109. package/dist/tempo/server/Methods.d.ts +1 -1
  110. package/dist/tempo/server/internal/html.gen.js +1 -1
  111. package/dist/tempo/server/internal/transport.d.ts +1 -1
  112. package/dist/tempo/server/internal/transport.js +9 -16
  113. package/dist/tempo/session/client/CredentialState.js +31 -0
  114. package/dist/tempo/session/client/Session.d.ts +12 -6
  115. package/dist/tempo/session/client/Session.js +64 -18
  116. package/dist/tempo/session/server/ChannelStore.d.ts +22 -1
  117. package/dist/tempo/session/server/ChannelStore.js +58 -8
  118. package/dist/tempo/session/server/CloseSupervisor.d.ts +5 -1
  119. package/dist/tempo/session/server/CloseSupervisor.js +110 -12
  120. package/dist/tempo/session/server/CredentialVerification.d.ts +2 -0
  121. package/dist/tempo/session/server/CredentialVerification.js +6 -32
  122. package/dist/tempo/session/server/Session.js +6 -3
  123. package/dist/tempo/session/server/Settlement.d.ts +7 -0
  124. package/dist/tempo/session/server/Settlement.js +36 -6
  125. package/dist/tempo/session/server/Sse.d.ts +2 -0
  126. package/dist/tempo/session/server/Sse.js +12 -12
  127. package/dist/tempo/subscription/KeyAuthorization.d.ts +1 -1
  128. package/dist/tempo/subscription/KeyAuthorization.js +1 -1
  129. package/dist/x402/Assets.d.ts +14 -5
  130. package/dist/x402/Assets.js +11 -16
  131. package/package.json +23 -3
  132. /package/dist/extensions/identity/{web-bot-auth/internal → internal}/JwkThumbprint.d.ts +0 -0
@@ -4,7 +4,7 @@ import { VerificationFailedError } from '../../../Errors.js';
4
4
  import * as Chain from '../precompile/Chain.js';
5
5
  import { escrowAbi } from '../precompile/escrow.abi.js';
6
6
  import * as ChannelStore from './ChannelStore.js';
7
- import { assertSettlementSender, getClientAccount, maybeSettleScheduled, reportSessionSettlementFailure, resolveChannelStore, } from './Settlement.js';
7
+ import { assertSettlementSender, getClientAccount, maybeSettleScheduled, reportSessionSettlementFailure, resolveChannelStore, SettlementCheckpointError, trackSendAttempts, } from './Settlement.js';
8
8
  /** Escrow event every close and withdrawal emits, with the amount paid to the payee. */
9
9
  const channelClosedEvent = getAbiItem({ abi: escrowAbi, name: 'ChannelClosed' });
10
10
  /** Channels whose escrow states one call reads, bounding its calldata and response size. */
@@ -145,7 +145,7 @@ async function superviseChannel(parameters, store, channel, state, blocks) {
145
145
  : previous !== undefined && previous > since
146
146
  ? previous
147
147
  : since;
148
- const paid = await findSettledToPayee(parameters, channel, {
148
+ const paid = await findSettledToPayee(parameters, store, channel, {
149
149
  fromBlock: fromBlock > 0n ? fromBlock : 0n,
150
150
  toBlock: blocks.pinned.number,
151
151
  });
@@ -173,8 +173,60 @@ async function superviseChannel(parameters, store, channel, state, blocks) {
173
173
  ? { ...current, closeSupervisedFromBlock: blocks.pinned.number }
174
174
  : current);
175
175
  if (state.closeRequestedAt === 0) {
176
- if (channel.closeRequestedAt === 0n)
177
- return settleDue(parameters, store, channel);
176
+ if (channel.closeRequestedAt === 0n) {
177
+ if (!parameters.closeUnsettled)
178
+ return settleDue(parameters, store, channel);
179
+ // Freeze spend atomically before exposing a close transaction. Its expiry bounds how long
180
+ // an ambiguous send can land, so later supervision can safely clear an expired marker.
181
+ const now = BigInt(Math.floor(Date.now() / 1000) || 1);
182
+ let claimed = false;
183
+ const closing = await store.updateChannel(channelId, (current) => {
184
+ claimed = false;
185
+ if (!current || current.finalized || current.closeRequestedAt !== 0n)
186
+ return current;
187
+ if (current.settledOnChain > state.settled)
188
+ return current;
189
+ if (Object.keys(current.prepaidRefunds ?? {}).length > 0)
190
+ return current;
191
+ const lease = current.scheduledSettlementLease;
192
+ if ((lease &&
193
+ lease.expiresAt > Date.now() &&
194
+ lease.owner !== parameters.settlementLeaseOwner) ||
195
+ (current.pendingSettlement && current.pendingSettlement.expiresAt > Date.now()))
196
+ return current;
197
+ const { pendingSettlement, ...rest } = current;
198
+ const onChain = ChannelStore.mergeActiveOnChainState(current, state);
199
+ current = {
200
+ ...rest,
201
+ ...onChain,
202
+ ...(pendingSettlement && pendingSettlement.amount > onChain.settledOnChain
203
+ ? { pendingSettlement }
204
+ : {}),
205
+ ...(current.retainedVouchers
206
+ ? {
207
+ retainedVouchers: current.retainedVouchers.filter((voucher) => voucher.cumulativeAmount > onChain.settledOnChain),
208
+ }
209
+ : {}),
210
+ };
211
+ if (current.spent <= current.settledOnChain ||
212
+ ChannelStore.resolveSettleableVoucher(current))
213
+ return current;
214
+ const next = ChannelStore.markPendingClose({
215
+ closeRequestedAt: now,
216
+ cumulativeAmount: current.highestVoucher?.cumulativeAmount ?? 0n,
217
+ current,
218
+ onChainDeposit: state.deposit,
219
+ onChainSettled: state.settled,
220
+ }).state;
221
+ claimed = true;
222
+ return next;
223
+ });
224
+ if (!closing || closing.finalized)
225
+ return { outcome: 'finalized' };
226
+ if (!claimed || !ChannelStore.isPrecompileState(closing))
227
+ return { outcome: closing.spent <= closing.settledOnChain ? 'settled' : 'open' };
228
+ return closeAtSpend(parameters, store, closing, state);
229
+ }
178
230
  // A pinned read without a request means the payer cancelled it, unless the record holds a
179
231
  // server close that may still land: those expire before they are cleared.
180
232
  const cleared = {};
@@ -223,6 +275,8 @@ async function settleDue(parameters, store, channel) {
223
275
  async function closeAtSpend(parameters, store, channel, state) {
224
276
  const { client } = parameters;
225
277
  const { channelId } = channel;
278
+ const send = trackSendAttempts(client);
279
+ let reverted = false;
226
280
  try {
227
281
  const voucher = channel.highestVoucher;
228
282
  if (!voucher)
@@ -243,26 +297,42 @@ async function closeAtSpend(parameters, store, channel, state) {
243
297
  payee: channel.payee,
244
298
  sender: account?.address,
245
299
  });
246
- const txHash = await Chain.closeOnChain(client, channel.descriptor, voucher.cumulativeAmount, capture, voucher.signature, channel.escrowContract, account
300
+ const validity = state.closeRequestedAt !== 0 || channel.pendingCloseAt === undefined
301
+ ? {}
302
+ : { validBefore: Number(channel.pendingCloseAt) + ChannelStore.pendingCloseValiditySeconds };
303
+ const txHash = await Chain.closeOnChain(send.client, channel.descriptor, voucher.cumulativeAmount, capture, voucher.signature, channel.escrowContract, account
247
304
  ? {
248
305
  account,
306
+ ...validity,
249
307
  candidateFeeTokens: parameters.candidateFeeTokens ?? [channel.token],
250
308
  ...(parameters.feePayer ? { feePayer: parameters.feePayer } : {}),
251
309
  ...(parameters.feePayerPolicy ? { feePayerPolicy: parameters.feePayerPolicy } : {}),
252
310
  ...(parameters.feeToken ? { feeToken: parameters.feeToken } : {}),
253
311
  }
254
- : undefined);
255
- const receipt = await Chain.waitForSuccessfulReceipt(client, txHash);
312
+ : validity).catch((error) => {
313
+ reverted = error instanceof VerificationFailedError;
314
+ throw error;
315
+ });
316
+ const receipt = await Chain.waitForSuccessfulReceipt(client, txHash).catch((error) => {
317
+ reverted = error instanceof VerificationFailedError;
318
+ throw error;
319
+ });
256
320
  const { refundedToPayer, settledToPayee } = Chain.readChannelClosedReceiptFields(Chain.getChannelEvent(receipt, 'ChannelClosed', channelId));
257
- if (settledToPayee > capture || settledToPayee + refundedToPayer > state.deposit)
321
+ if (settledToPayee > capture ||
322
+ (state.closeRequestedAt !== 0 && settledToPayee + refundedToPayer > state.deposit))
258
323
  throw new VerificationFailedError({ reason: 'ChannelClosed amounts do not match state' });
259
- await store.updateChannel(channelId, (current) => ChannelStore.finalizeClosedChannelState({
324
+ let checkpointError;
325
+ await store
326
+ .updateChannel(channelId, (current) => ChannelStore.finalizeClosedChannelState({
260
327
  captureAmount: settledToPayee,
261
328
  channelId,
262
329
  cumulativeAmount: voucher.cumulativeAmount,
263
330
  current,
264
331
  signature: voucher.signature,
265
- }));
332
+ }))
333
+ .catch((cause) => {
334
+ checkpointError = { cause };
335
+ });
266
336
  if (parameters.onSessionSettlement) {
267
337
  try {
268
338
  await parameters.onSessionSettlement(Object.freeze({
@@ -277,9 +347,24 @@ async function closeAtSpend(parameters, store, channel, state) {
277
347
  // Errors are isolated: observers cannot break the close.
278
348
  }
279
349
  }
350
+ if (checkpointError)
351
+ throw new SettlementCheckpointError({ cause: checkpointError.cause, txHash });
280
352
  return { outcome: 'closed', txHash };
281
353
  }
282
354
  catch (error) {
355
+ if (state.closeRequestedAt === 0 &&
356
+ channel.pendingCloseAt !== undefined &&
357
+ (!send.tracked.attempted || reverted)) {
358
+ await store.updateChannel(channelId, (current) => current &&
359
+ current.pendingCloseAt === channel.pendingCloseAt &&
360
+ current.closeRequestedAt === channel.pendingCloseAt
361
+ ? {
362
+ ...current,
363
+ closeRequestedAt: current.onChainCloseRequestedAt ?? 0n,
364
+ pendingCloseAt: undefined,
365
+ }
366
+ : current);
367
+ }
283
368
  await reportSessionSettlementFailure(parameters.onSessionSettlementFailure, {
284
369
  chainId: channel.chainId,
285
370
  channelId,
@@ -290,9 +375,13 @@ async function closeAtSpend(parameters, store, channel, state) {
290
375
  }
291
376
  }
292
377
  /** Amount paid to the payee when the channel closed within the blocks, if it did. */
293
- async function findSettledToPayee(parameters, channel, range) {
378
+ async function findSettledToPayee(parameters, store, channel, range) {
294
379
  const step = parameters.logBlockRange ?? defaultLogBlockRange;
295
- for (let from = range.fromBlock; from <= range.toBlock; from += step) {
380
+ const cursor = channel.closeSearchFromBlock;
381
+ const start = cursor !== undefined && cursor >= range.fromBlock && cursor <= range.toBlock
382
+ ? cursor
383
+ : range.fromBlock;
384
+ for (let from = start; from <= range.toBlock; from += step) {
296
385
  const to = from + step - 1n < range.toBlock ? from + step - 1n : range.toBlock;
297
386
  const logs = await getLogs(parameters.client, {
298
387
  address: channel.escrowContract,
@@ -304,7 +393,16 @@ async function findSettledToPayee(parameters, channel, range) {
304
393
  const paid = logs.find((log) => !log.removed)?.args.settledToPayee;
305
394
  if (paid !== undefined)
306
395
  return paid;
396
+ // Resume after successful empty ranges if a later RPC call fails or the worker is interrupted.
397
+ await store.updateChannel(channel.channelId, (current) => current && !current.finalized
398
+ ? {
399
+ ...current,
400
+ closeSearchFromBlock: to + 1n,
401
+ }
402
+ : current);
307
403
  }
404
+ // Empty logs can reflect a lagging RPC index. Retry from the original anchor next time.
405
+ await store.updateChannel(channel.channelId, (current) => current && !current.finalized ? { ...current, closeSearchFromBlock: undefined } : current);
308
406
  return undefined;
309
407
  }
310
408
  //# sourceMappingURL=CloseSupervisor.js.map
@@ -89,6 +89,8 @@ export type BroadcastCredentialPayloadParameters = {
89
89
  voucherStateMaxAge?: number | undefined;
90
90
  /** Request price a voucher credential pays in the same store update that accepts it. */
91
91
  chargeAmount?: bigint | undefined;
92
+ /** Durable delivery key for an SSE request charged before its first item. */
93
+ prepaidRefundKey?: string | undefined;
92
94
  /** Called with the stored channel after `chargeAmount` was charged. */
93
95
  onCharged?: ((channel: ChannelStore.State) => void) | undefined;
94
96
  };
@@ -1,4 +1,4 @@
1
- import { createClient, custom, isAddress, isAddressEqual, zeroAddress, } from 'viem';
1
+ import { isAddress, isAddressEqual, zeroAddress, } from 'viem';
2
2
  import { AmountExceedsDepositError, ChannelClosedError, ChannelNotFoundError, DeltaTooSmallError, InsufficientBalanceError, InvalidSignatureError, VerificationFailedError, } from '../../../Errors.js';
3
3
  import * as Chain from '../precompile/Chain.js';
4
4
  import { readChannelClosedReceiptFields } from '../precompile/Chain.js';
@@ -7,7 +7,7 @@ import { createSessionReceipt, uint96, } from '../precompile/Protocol.js';
7
7
  import * as Voucher from '../precompile/Voucher.js';
8
8
  import * as ChannelStore from './ChannelStore.js';
9
9
  import { getChallengePaymentFields } from './RequestState.js';
10
- import { assertSettlementSender, getClientAccount, maybeSettleScheduled, reportSessionSettlementFailure, } from './Settlement.js';
10
+ import { assertSettlementSender, getClientAccount, maybeSettleScheduled, reportSessionSettlementFailure, trackSendAttempts, } from './Settlement.js';
11
11
  /** Returns the effective voucher signer for a TIP-1034 descriptor. */
12
12
  export function authorizedSigner(descriptor) {
13
13
  return isAddressEqual(descriptor.authorizedSigner, zeroAddress)
@@ -699,6 +699,7 @@ async function handleVoucherCredential(parameters) {
699
699
  channelState: storedChannelState(channel),
700
700
  methodDetails: { chainId, escrowContract: escrow },
701
701
  chargeAmount,
702
+ prepaidRefundKey: parameters.prepaidRefundKey,
702
703
  onCharged,
703
704
  });
704
705
  }
@@ -726,6 +727,7 @@ async function handleVoucherCredential(parameters) {
726
727
  methodDetails: { chainId, escrowContract: escrow },
727
728
  verifiedAt: startedAt,
728
729
  chargeAmount,
730
+ prepaidRefundKey: parameters.prepaidRefundKey,
729
731
  onCharged,
730
732
  });
731
733
  }
@@ -772,6 +774,7 @@ async function acceptVoucherInOneUpdate(parameters, voucher, descriptor) {
772
774
  const acceptance = ChannelStore.planVoucherAcceptance({
773
775
  accepted: ChannelStore.acceptVoucherStateUpdate({ channelState, current, voucher }),
774
776
  chargeAmount,
777
+ prepaidRefundKey: parameters.prepaidRefundKey,
775
778
  });
776
779
  return { op: 'set', value: acceptance.channel, result: acceptance };
777
780
  });
@@ -796,12 +799,7 @@ async function recordPendingClose(parameters, channelId, channelState) {
796
799
  const closing = await store.updateChannel(channelId, (current) => current
797
800
  ? {
798
801
  ...current,
799
- settledOnChain: channelState.settled > current.settledOnChain
800
- ? channelState.settled
801
- : current.settledOnChain,
802
- closeRequestedAt: BigInt(channelState.closeRequestedAt) > current.closeRequestedAt
803
- ? BigInt(channelState.closeRequestedAt)
804
- : current.closeRequestedAt,
802
+ ...ChannelStore.mergeActiveOnChainState(current, channelState),
805
803
  }
806
804
  : current);
807
805
  if (closing && !closing.finalized && channelState.deposit > 0n)
@@ -839,30 +837,6 @@ function recordOnChainReadInBackground(parameters, channelId, read) {
839
837
  })
840
838
  .catch(() => { });
841
839
  }
842
- const sendMethods = new Set([
843
- 'eth_sendRawTransaction',
844
- 'eth_sendRawTransactionSync',
845
- 'eth_sendTransaction',
846
- ]);
847
- /** Wraps a client so a failed close can tell whether its transaction was handed to the node. */
848
- function trackSendAttempts(client) {
849
- const tracked = { attempted: false };
850
- const trackedClient = createClient({
851
- account: client.account,
852
- chain: client.chain,
853
- pollingInterval: client.pollingInterval,
854
- transport: custom({
855
- request(parameters) {
856
- if (sendMethods.has(parameters.method))
857
- tracked.attempted = true;
858
- return client.request(parameters);
859
- },
860
- },
861
- // The wrapped client already owns retries.
862
- { retryCount: 0 }),
863
- });
864
- return { client: trackedClient, tracked };
865
- }
866
840
  async function handleCloseCredential(parameters) {
867
841
  const { store, client, challenge, payload, chainId, escrow } = parameters;
868
842
  const request = getChallengePaymentFields(challenge);
@@ -363,6 +363,8 @@ export function session(p) {
363
363
  minVoucherDelta: parameters.minVoucherDelta,
364
364
  request,
365
365
  });
366
+ const prepaidRefundKey = parameters.sse ? `stream:${globalThis.crypto.randomUUID()}` : undefined;
367
+ const markPrepaidReceipt = (receipt) => Transport.markPrepaidSessionTick(receipt, prepaidRefundKey);
366
368
  const chargeAmount = (parameters.chargeOnAcceptance || parameters.sse) &&
367
369
  shouldChargeVoucherOnAcceptance({
368
370
  capturedRequest: envelope?.capturedRequest,
@@ -388,6 +390,7 @@ export function session(p) {
388
390
  account,
389
391
  challenge,
390
392
  chargeAmount,
393
+ prepaidRefundKey,
391
394
  onCharged: (channel) => {
392
395
  acceptance.charged = channel;
393
396
  },
@@ -424,7 +427,7 @@ export function session(p) {
424
427
  ...sessionReceipt,
425
428
  ...(settlementTxHash ? { txHash: settlementTxHash } : {}),
426
429
  };
427
- return parameters.sse ? Transport.markPrepaidSessionTick(receipt) : receipt;
430
+ return parameters.sse ? markPrepaidReceipt(receipt) : receipt;
428
431
  }
429
432
  return applyVerifiedHttpAccounting({
430
433
  capturedRequest: envelope?.capturedRequest,
@@ -432,9 +435,9 @@ export function session(p) {
432
435
  receipt: sessionReceipt,
433
436
  getRequestAmount: () => BigInt(context.request.amount ?? challenge.request.amount),
434
437
  sseEnabled: Boolean(parameters.sse),
435
- markPrepaidReceipt: Transport.markPrepaidSessionTick,
438
+ markPrepaidReceipt,
436
439
  unitType: context.request.unitType,
437
- charge: (channelId, requestAmount) => chargeSessionChannel({ store, channelId, amount: requestAmount }),
440
+ charge: (channelId, requestAmount) => chargeSessionChannel({ store, channelId, amount: requestAmount, prepaidRefundKey }),
438
441
  settleCharged: settleAcceptedCharge,
439
442
  });
440
443
  };
@@ -282,4 +282,11 @@ export declare function settleBatch(store: SessionStoreInput, client: Chain.Tran
282
282
  export declare function ignoreRetryableSettlementFailure(error: unknown): undefined;
283
283
  /** @internal Reports a settlement failure without letting observer errors replace it. */
284
284
  export declare function reportSessionSettlementFailure(onSessionSettlementFailure: OnSessionSettlementFailure | undefined, context: SessionSettlementFailureContext): Promise<void>;
285
+ /** Wraps a client so a failed close can tell whether its transaction was handed to the node. */
286
+ export declare function trackSendAttempts(client: Chain.TransactionClient): {
287
+ client: Chain.TransactionClient;
288
+ tracked: {
289
+ attempted: boolean;
290
+ };
291
+ };
285
292
  //# sourceMappingURL=Settlement.d.ts.map
@@ -1,5 +1,5 @@
1
- import { BaseError as viem_BaseError, ExecutionRevertedError, HttpRequestError, InternalRpcError, isAddress, isAddressEqual, LimitExceededRpcError, parseUnits, ResourceUnavailableRpcError, RpcRequestError, SocketClosedError, TimeoutError, WaitForTransactionReceiptTimeoutError, WebSocketRequestError, zeroAddress, } from 'viem';
2
- import { BadRequestError, ChannelClosedError, ChannelNotFoundError, InsufficientBalanceError, VerificationFailedError, } from '../../../Errors.js';
1
+ import { BaseError as viem_BaseError, createClient, custom, ExecutionRevertedError, HttpRequestError, InternalRpcError, isAddress, isAddressEqual, LimitExceededRpcError, parseUnits, ResourceUnavailableRpcError, RpcRequestError, SocketClosedError, TimeoutError, WaitForTransactionReceiptTimeoutError, WebSocketRequestError, zeroAddress, } from 'viem';
2
+ import { BadRequestError, ChannelClosedError, ChannelNotFoundError, VerificationFailedError, } from '../../../Errors.js';
3
3
  import { isSessionContentRequest } from '../../server/internal/request-body.js';
4
4
  import * as Chain from '../precompile/Chain.js';
5
5
  import { readSettledReceiptFields } from '../precompile/Chain.js';
@@ -126,6 +126,8 @@ export async function claimScheduledSettlement(parameters) {
126
126
  claimed = false;
127
127
  if (!current || !isSettlementDue(current, schedule))
128
128
  return current;
129
+ if (ChannelStore.hasPendingClose(current, now))
130
+ return current;
129
131
  const lease = current.scheduledSettlementLease;
130
132
  if (lease && lease.expiresAt > now)
131
133
  return current;
@@ -202,11 +204,12 @@ export async function applyVerifiedHttpAccounting(parameters) {
202
204
  }
203
205
  /** Atomically deducts spend from a channel and maps store failures to typed session errors. */
204
206
  export async function chargeSessionChannel(parameters) {
205
- const { store, channelId, amount, idempotencyKey, retention } = parameters;
207
+ const { store, channelId, amount, idempotencyKey, retention, prepaidRefundKey } = parameters;
206
208
  ChannelStore.assertIdempotencyOptions({ idempotencyKey, retention });
207
209
  let result;
208
210
  try {
209
211
  result = await ChannelStore.deductFromChannel(store, channelId, amount, {
212
+ prepaidRefundKey,
210
213
  idempotencyKey,
211
214
  retention,
212
215
  });
@@ -222,9 +225,7 @@ export async function chargeSessionChannel(parameters) {
222
225
  if (result.channel.closeRequestedAt !== 0n)
223
226
  throw new ChannelClosedError({ reason: 'channel has a pending close request' });
224
227
  const available = result.channel.highestVoucherAmount - result.channel.spent;
225
- throw new InsufficientBalanceError({
226
- reason: `requested ${amount}, available ${available}`,
227
- });
228
+ throw ChannelStore.insufficientBalance(result.channel, `requested ${amount}, available ${available}`);
228
229
  }
229
230
  return result.channel;
230
231
  }
@@ -338,6 +339,11 @@ export async function settle(store_, client, channelId_, options) {
338
339
  // Choosing the voucher and raising the credit floor in one update keeps a concurrent credit from
339
340
  // lowering spent below what this transaction captures.
340
341
  await store.updateChannel(channelId, (current) => {
342
+ if (current && ChannelStore.hasPendingClose(current)) {
343
+ claim.channel = undefined;
344
+ claim.voucher = undefined;
345
+ return current;
346
+ }
341
347
  claim.channel = current ?? undefined;
342
348
  claim.voucher = (current && ChannelStore.resolveSettleableVoucher(current)) ?? undefined;
343
349
  if (!current || !claim.voucher)
@@ -520,4 +526,28 @@ async function emitSessionSettlement(onSessionSettlement, context) {
520
526
  // Errors are isolated — observers cannot break the settlement flow.
521
527
  }
522
528
  }
529
+ const sendMethods = new Set([
530
+ 'eth_sendRawTransaction',
531
+ 'eth_sendRawTransactionSync',
532
+ 'eth_sendTransaction',
533
+ ]);
534
+ /** Wraps a client so a failed close can tell whether its transaction was handed to the node. */
535
+ export function trackSendAttempts(client) {
536
+ const tracked = { attempted: false };
537
+ const trackedClient = createClient({
538
+ account: client.account,
539
+ chain: client.chain,
540
+ pollingInterval: client.pollingInterval,
541
+ transport: custom({
542
+ request(parameters) {
543
+ if (sendMethods.has(parameters.method))
544
+ tracked.attempted = true;
545
+ return client.request(parameters);
546
+ },
547
+ },
548
+ // The wrapped client already owns retries.
549
+ { retryCount: 0 }),
550
+ });
551
+ return { client: trackedClient, tracked };
552
+ }
523
553
  //# sourceMappingURL=Settlement.js.map
@@ -29,6 +29,8 @@ export declare class PrepaidRefundError extends Error {
29
29
  }
30
30
  /** Maximum retained automatic refund operations per channel. Never evict live retry keys. */
31
31
  export declare const maxPrepaidRefunds = 128;
32
+ /** Releases a completed prepaid delivery so automatic channel closure can proceed. */
33
+ export declare function clearPrepaidRefund(store: ChannelStore.ChannelStore, channelId: Hex, key: string): Promise<void>;
32
34
  /**
33
35
  * Persist a delivery obligation before returning a managed response. Failed hook deliveries remain
34
36
  * in `channel.prepaidRefunds` for a merchant worker. Pending entries require manual delivery
@@ -14,6 +14,16 @@ export class PrepaidRefundError extends Error {
14
14
  }
15
15
  /** Maximum retained automatic refund operations per channel. Never evict live retry keys. */
16
16
  export const maxPrepaidRefunds = 128;
17
+ /** Releases a completed prepaid delivery so automatic channel closure can proceed. */
18
+ export async function clearPrepaidRefund(store, channelId, key) {
19
+ await store.updateChannel(channelId, (current) => {
20
+ if (!current?.prepaidRefunds?.[key])
21
+ return current;
22
+ const prepaidRefunds = { ...current.prepaidRefunds };
23
+ delete prepaidRefunds[key];
24
+ return { ...current, prepaidRefunds };
25
+ });
26
+ }
17
27
  /**
18
28
  * Persist a delivery obligation before returning a managed response. Failed hook deliveries remain
19
29
  * in `channel.prepaidRefunds` for a merchant worker. Pending entries require manual delivery
@@ -101,20 +111,10 @@ export function serve(options) {
101
111
  const refundIdempotencyKey = options.refundIdempotencyKey ?? `stream:${globalThis.crypto.randomUUID()}`;
102
112
  ChannelStore.assertIdempotencyOptions({ idempotencyKey: refundIdempotencyKey });
103
113
  const refundOptions = { ...options, refundIdempotencyKey };
104
- const clearObligation = async () => {
105
- if (!options.autoCreditPrepaid)
106
- return;
107
- await store.updateChannel(channelId, (current) => {
108
- if (!current?.prepaidRefunds?.[refundIdempotencyKey])
109
- return current;
110
- const prepaidRefunds = { ...current.prepaidRefunds };
111
- delete prepaidRefunds[refundIdempotencyKey];
112
- return { ...current, prepaidRefunds };
113
- });
114
- };
114
+ const clearObligation = () => clearPrepaidRefund(store, channelId, refundIdempotencyKey);
115
115
  const creditFailedDelivery = async () => {
116
116
  if (!options.autoCreditPrepaid)
117
- return;
117
+ return clearObligation();
118
118
  if (undeliveredPrepaidUnits === 0 || tickCost === 0n) {
119
119
  await clearObligation();
120
120
  return;
@@ -175,7 +175,7 @@ export declare function signSubscriptionKeyAuthorization(parameters: {
175
175
  type: 'webAuthn';
176
176
  prehash?: undefined;
177
177
  })[];
178
- type: 'multisig';
178
+ type: 'configurable';
179
179
  inner?: undefined;
180
180
  keyId?: undefined;
181
181
  metadata?: undefined;
@@ -135,7 +135,7 @@ export async function signSubscriptionKeyAuthorization(parameters) {
135
135
  hash: KeyAuthorization.getSignPayload(authorization),
136
136
  });
137
137
  const signatureEnvelope = SignatureEnvelope.from(signature);
138
- if (signatureEnvelope.type === 'keychain' || signatureEnvelope.type === 'multisig') {
138
+ if (signatureEnvelope.type === 'keychain' || signatureEnvelope.type === 'configurable') {
139
139
  throw new VerificationFailedError({
140
140
  reason: 'keyAuthorization must use a primitive signature',
141
141
  });
@@ -1,15 +1,24 @@
1
1
  import type { Token } from 'viem/tokens';
2
+ import * as Currency_ from '../Currency.js';
2
3
  import type { Asset, EvmNetwork, ExactTransfer } from './Types.js';
3
4
  declare const knownAsset: unique symbol;
4
- /** Known x402 asset metadata. */
5
+ /**
6
+ * Known x402 asset metadata: a token resolved to one chain, as `ousd(4217)` is, with the
7
+ * transfer metadata that EIP-3009 and Permit2 signing need.
8
+ */
5
9
  export type KnownAsset = Asset & {
6
10
  readonly [knownAsset]: true;
11
+ /** Chain ID of `network`. */
12
+ chainId: number;
7
13
  network: EvmNetwork;
8
14
  };
9
- /** Viem token metadata from `viem/tokens`. */
15
+ /**
16
+ * Viem token metadata from `viem/tokens`.
17
+ * @deprecated Use `Token` from `viem/tokens`.
18
+ */
10
19
  export type ViemToken = Token;
11
- /** Currency metadata accepted by EVM and x402 payment config. */
12
- export type Currency = `0x${string}` | KnownAsset | ViemToken;
20
+ /** Currency accepted by EVM and x402 payment config: any mppx `Currency`, or a known asset. */
21
+ export type Currency = Currency_.Currency | KnownAsset;
13
22
  /** Creates typed x402 asset metadata for custom tokens. */
14
23
  export declare function define(parameters: define.Parameters): KnownAsset;
15
24
  export declare namespace define {
@@ -55,7 +64,7 @@ export declare const celoSepolia: {
55
64
  /** Returns true when a value is known x402 asset metadata. */
56
65
  export declare function isAsset(value: unknown): value is KnownAsset;
57
66
  /** Returns true when a value is a `viem/tokens` token definition. */
58
- export declare function isToken(value: unknown): value is ViemToken;
67
+ export declare const isToken: (value: unknown) => value is Token;
59
68
  /** Returns true when a currency is a raw address without chain metadata. */
60
69
  export declare function isRawAddress(currency: Currency): currency is `0x${string}`;
61
70
  /** Resolves currency metadata for an EVM network. */
@@ -1,10 +1,12 @@
1
1
  import { getAddress } from 'viem';
2
+ import * as Currency_ from '../Currency.js';
2
3
  const knownAsset = Symbol('mppx.x402.asset');
3
4
  /** Creates typed x402 asset metadata for custom tokens. */
4
5
  export function define(parameters) {
5
6
  return {
6
7
  [knownAsset]: true,
7
8
  address: parameters.address,
9
+ chainId: toChainId(parameters.network),
8
10
  decimals: parameters.decimals,
9
11
  network: parameters.network,
10
12
  transfer: parameters.transfer,
@@ -93,11 +95,7 @@ export function isAsset(value) {
93
95
  return value[knownAsset] === true;
94
96
  }
95
97
  /** Returns true when a value is a `viem/tokens` token definition. */
96
- export function isToken(value) {
97
- return (typeof value === 'function' &&
98
- typeof value.addresses === 'object' &&
99
- typeof value.decimals === 'number');
100
- }
98
+ export const isToken = Currency_.isToken;
101
99
  /** Returns true when a currency is a raw address without chain metadata. */
102
100
  export function isRawAddress(currency) {
103
101
  return typeof currency === 'string';
@@ -113,18 +111,15 @@ export function resolve(currency, network) {
113
111
  transfer: currency.transfer,
114
112
  };
115
113
  }
116
- if (isToken(currency)) {
117
- const address = currency.addresses[toChainId(network)];
118
- if (!address)
119
- return undefined;
120
- return {
121
- address,
122
- decimals: currency.decimals,
123
- name: currency.name,
124
- };
125
- }
114
+ if (typeof currency === 'string')
115
+ return { address: currency };
116
+ const resolved = Currency_.resolve(currency, { chainId: toChainId(network) });
117
+ if (!resolved)
118
+ return undefined;
126
119
  return {
127
- address: currency,
120
+ address: resolved.address,
121
+ decimals: resolved.decimals,
122
+ name: resolved.name,
128
123
  };
129
124
  }
130
125
  /** Returns true when a currency resolves to the accepted address on the network. */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mppx",
3
3
  "type": "module",
4
- "version": "0.18.0",
4
+ "version": "0.19.0",
5
5
  "main": "./dist/index.js",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/wevm/mppx#readme",
@@ -135,6 +135,10 @@
135
135
  "types": "./dist/extensions/identity/attestation/index.d.ts",
136
136
  "default": "./dist/extensions/identity/attestation/index.js"
137
137
  },
138
+ "./extensions/identity/persona": {
139
+ "types": "./dist/extensions/identity/persona/index.d.ts",
140
+ "default": "./dist/extensions/identity/persona/index.js"
141
+ },
138
142
  "./extensions/identity/tap": {
139
143
  "types": "./dist/extensions/identity/tap/index.d.ts",
140
144
  "default": "./dist/extensions/identity/tap/index.js"
@@ -143,10 +147,22 @@
143
147
  "types": "./dist/extensions/identity/email-otp/index.d.ts",
144
148
  "default": "./dist/extensions/identity/email-otp/index.js"
145
149
  },
150
+ "./extensions/identity/link": {
151
+ "types": "./dist/extensions/identity/link/index.d.ts",
152
+ "default": "./dist/extensions/identity/link/index.js"
153
+ },
154
+ "./extensions/identity/tempo": {
155
+ "types": "./dist/extensions/identity/tempo/index.d.ts",
156
+ "default": "./dist/extensions/identity/tempo/index.js"
157
+ },
146
158
  "./extensions/identity/web-bot-auth": {
147
159
  "types": "./dist/extensions/identity/web-bot-auth/index.d.ts",
148
160
  "default": "./dist/extensions/identity/web-bot-auth/index.js"
149
161
  },
162
+ "./extensions/identity/world": {
163
+ "types": "./dist/extensions/identity/world/index.d.ts",
164
+ "default": "./dist/extensions/identity/world/index.js"
165
+ },
150
166
  "./html": {
151
167
  "types": "./dist/Html.d.ts",
152
168
  "default": "./dist/Html.js"
@@ -174,6 +190,7 @@
174
190
  },
175
191
  "peerDependencies": {
176
192
  "@modelcontextprotocol/sdk": ">=1.25.0",
193
+ "@stripe/agent-identity": ">=0.3.0",
177
194
  "@x402/core": ">=2.22.0",
178
195
  "@x402/express": ">=2.22.0",
179
196
  "@x402/hono": ">=2.22.0",
@@ -183,12 +200,15 @@
183
200
  "express": ">=5",
184
201
  "hono": ">=4.12.25",
185
202
  "next": ">=16.2.6",
186
- "viem": ">=2.57.1"
203
+ "viem": ">=2.57.19"
187
204
  },
188
205
  "peerDependenciesMeta": {
189
206
  "@modelcontextprotocol/sdk": {
190
207
  "optional": true
191
208
  },
209
+ "@stripe/agent-identity": {
210
+ "optional": true
211
+ },
192
212
  "@x402/core": {
193
213
  "optional": true
194
214
  },
@@ -218,7 +238,7 @@
218
238
  }
219
239
  },
220
240
  "dependencies": {
221
- "ox": "0.14.45",
241
+ "ox": "0.14.65",
222
242
  "structured-headers": "2.1.0",
223
243
  "zod": "^4.6.7"
224
244
  },