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
@@ -1,12 +1,17 @@
1
1
  import { AbiParameters, Hash } from 'ox';
2
2
  import { decodeFunctionData, getAbiItem, parseEventLogs, } from 'viem';
3
- import { getBlockNumber, getLogs } from 'viem/actions';
3
+ import { getBlockNumber, getLogs, readContract } from 'viem/actions';
4
4
  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
8
  /** Number of Tempo blocks searched back for a settled Zone withdrawal. */
9
9
  const lookbackBlocks = 7200n;
10
+ /**
11
+ * Most sender tags derived for one withdrawal: the withdrawals its Zone block may hold.
12
+ * Each candidate is a topic in every settlement poll's `eth_getLogs` filter.
13
+ */
14
+ const maxSenderTagCandidates = 64n;
10
15
  /** Time between polls for a settled Zone withdrawal. */
11
16
  const pollingIntervalMs = 500;
12
17
  const withdrawalProcessed = getAbiItem({ abi: Abis.zonePortal, name: 'WithdrawalProcessed' });
@@ -95,14 +100,56 @@ export function findWithdrawal(calls, parameters) {
95
100
  }
96
101
  return undefined;
97
102
  }
103
+ /**
104
+ * Derives the sender tags a withdrawal transaction may carry when its receipt
105
+ * has no `WithdrawalRequested` event, as on a Zone RPC that redacts logs.
106
+ *
107
+ * The outbox numbers each withdrawal with the next `lastFallbackNonce`, so the
108
+ * transaction's withdrawal took one of the nonces its block added. Every
109
+ * candidate hashes the payer's address and transaction, so only the payer's
110
+ * withdrawal can match one.
111
+ */
112
+ export async function senderTagCandidates(client, parameters) {
113
+ const { blockNumber, sender, transactionHash } = parameters;
114
+ const lastFallbackNonce = (blockNumber) => readContract(client, {
115
+ abi: Abis.zoneOutbox,
116
+ address: Addresses.zoneOutbox,
117
+ blockNumber,
118
+ functionName: 'lastFallbackNonce',
119
+ });
120
+ const [before, after] = await Promise.all([
121
+ lastFallbackNonce(blockNumber - 1n),
122
+ lastFallbackNonce(blockNumber),
123
+ ]);
124
+ if (after <= before)
125
+ throw new Error(`Zone withdrawal transaction ${transactionHash} did not request a withdrawal from the outbox.`);
126
+ // The nonces come from the Zone RPC, so a range no block could hold is refused rather than hashed.
127
+ if (after - before > maxSenderTagCandidates)
128
+ throw new Error(`Zone withdrawal transaction ${transactionHash} has ${after - before} candidate sender tags, more than ${maxSenderTagCandidates}.`);
129
+ const tags = [];
130
+ for (let fallbackNonce = before + 1n; fallbackNonce <= after; fallbackNonce++)
131
+ tags.push(senderTag({ fallbackNonce, sender, transactionHash }));
132
+ return tags;
133
+ }
98
134
  /**
99
135
  * Waits until a portal emits `WithdrawalProcessed` for a sender tag and
100
136
  * returns the Tempo transaction hash that settled it.
101
137
  */
102
138
  export async function waitForSettlement(client, parameters) {
103
- const { timeoutMs = defaultSettlementTimeoutMs } = parameters;
139
+ const { senderTag, ...rest } = parameters;
140
+ const { hash } = await waitForSettledWithdrawal(client, { ...rest, senderTags: [senderTag] });
141
+ return hash;
142
+ }
143
+ /**
144
+ * Waits until a portal emits `WithdrawalProcessed` for any of several sender
145
+ * tags, and returns the tag and the Tempo transaction hash that settled it.
146
+ */
147
+ export async function waitForSettledWithdrawal(client, parameters) {
148
+ const { senderTags, timeoutMs = defaultSettlementTimeoutMs } = parameters;
104
149
  if (!Number.isFinite(timeoutMs) || timeoutMs < 0)
105
150
  throw new Error('Zone settlement timeout must be a finite, non-negative number.');
151
+ if (senderTags.length === 0)
152
+ throw new Error('Zone settlement needs at least one sender tag.');
106
153
  let latest = await getBlockNumber(client, { cacheTime: 0 });
107
154
  // Scan the lookback window once, then only blocks added since the previous poll.
108
155
  let fromBlock = latest > lookbackBlocks ? latest - lookbackBlocks : 0n;
@@ -113,19 +160,19 @@ export async function waitForSettlement(client, parameters) {
113
160
  address: parameters.portal,
114
161
  event: withdrawalProcessed,
115
162
  args: {
116
- senderTag: parameters.senderTag,
163
+ senderTag: [...senderTags],
117
164
  ...(parameters.to ? { to: parameters.to } : {}),
118
165
  },
119
166
  fromBlock,
120
167
  toBlock: latest,
121
168
  });
122
- const hash = logs[0]?.transactionHash;
123
- if (hash)
124
- return hash;
169
+ const [log] = logs;
170
+ if (log?.transactionHash && log.args.senderTag)
171
+ return { hash: log.transactionHash, senderTag: log.args.senderTag };
125
172
  fromBlock = latest + 1n;
126
173
  }
127
174
  if (Date.now() + pollingIntervalMs > deadline)
128
- throw new Error(`Zone withdrawal ${parameters.senderTag} did not settle on Tempo within ${timeoutMs}ms.`);
175
+ throw new Error(`Zone withdrawal ${senderTags.join(' or ')} did not settle on Tempo within ${timeoutMs}ms.`);
129
176
  await new Promise((resolve) => setTimeout(resolve, pollingIntervalMs));
130
177
  latest = await getBlockNumber(client, { cacheTime: 0 });
131
178
  }
@@ -305,7 +305,25 @@ export function charge(parameters = {}) {
305
305
  FeePayer.assertAllowedFeeToken(transaction, context.allowedFeeTokens);
306
306
  }
307
307
  else {
308
- await viem_call(client, FeePayer.simulationTransaction(transaction, { feePayer: false }));
308
+ await viem_call(client, FeePayer.simulationTransaction(transaction, { feePayer: false })).catch(async (error) => {
309
+ // A settled transaction that is sent again fails simulation too: answer it as the
310
+ // replay it is, before any MACH shortfall is read off the payer's spent balance.
311
+ // The chain is checked too: replay-sharded stores keep markers that `get` can't read.
312
+ // Settlement broadcasts the canonical envelope (below), so the chain knows that hash.
313
+ const hash = keccak256(serializedTransaction);
314
+ const canonicalHash = keccak256(await Transaction.serialize(Transaction.deserialize(serializedTransaction)));
315
+ if ((await isHashUsed(store, hash)) ||
316
+ (await isHashUsed(store, canonicalHash)) ||
317
+ (await getTransactionReceipt(client, { hash: canonicalHash }).then(() => true, () => false)))
318
+ throw new CredentialReplayedError({ reason: 'Transaction hash has already been used' });
319
+ throw await explainMachineTokenFailure(error, {
320
+ amount,
321
+ chainId: chainId ?? client.chain?.id,
322
+ client,
323
+ fundingCurrency,
324
+ payer: transaction.from,
325
+ });
326
+ });
309
327
  }
310
328
  return {
311
329
  fundingCurrency,
@@ -789,7 +807,15 @@ export function charge(parameters = {}) {
789
807
  if (claimedFinalHash)
790
808
  await releaseHashUse(store, claimedFinalHash);
791
809
  await releaseHashUse(store, hash);
792
- throw error;
810
+ if (broadcastAttempted)
811
+ throw error;
812
+ throw await explainMachineTokenFailure(error, {
813
+ amount,
814
+ chainId: chainId ?? client.chain?.id,
815
+ client,
816
+ fundingCurrency,
817
+ payer: transaction.from,
818
+ });
793
819
  }
794
820
  }
795
821
  }
@@ -797,6 +823,29 @@ export function charge(parameters = {}) {
797
823
  });
798
824
  return relay ? Relay.configure(method, relay) : method;
799
825
  }
826
+ /**
827
+ * Explains why a MACH-route payment failed before broadcast. When the payer holds too little MACH,
828
+ * returns a `VerificationFailedError` that links to the MACH onramp (on Tempo mainnet); otherwise
829
+ * returns `error` unchanged. Typed payment errors are kept as they are.
830
+ */
831
+ async function explainMachineTokenFailure(error, parameters) {
832
+ const { amount, chainId, client, fundingCurrency, payer } = parameters;
833
+ if (error instanceof PaymentError || !payer || !fundingCurrency)
834
+ return error;
835
+ if (!MachineTokenCharge.isMachineToken({ chainId, currency: fundingCurrency }))
836
+ return error;
837
+ const shortfall = await MachineTokenCharge.getShortfall(client, {
838
+ account: payer,
839
+ amount: BigInt(amount),
840
+ chainId,
841
+ });
842
+ if (!shortfall)
843
+ return error;
844
+ return new VerificationFailedError({
845
+ fundingUrl: shortfall.fundingUrl,
846
+ reason: `insufficient MACH balance (${shortfall.reason})`,
847
+ });
848
+ }
800
849
  function chargeBinding(request) {
801
850
  // Exhaustively destructure so new charge request fields require an explicit binding decision.
802
851
  const { amount, currency, description, externalId, methodDetails, recipient, ...requestRest } = request;
@@ -1054,6 +1103,14 @@ async function tryClaimZoneWithdrawal(store, portal, senderTag, expires) {
1054
1103
  async function tryClaimHash(store, hash, expires) {
1055
1104
  return Store.tryClaim(store, getHashStoreKey(hash), expires);
1056
1105
  }
1106
+ /** Whether a live replay marker holds `hash`, read without claiming it. */
1107
+ async function isHashUsed(store, hash) {
1108
+ const current = await store.get(getHashStoreKey(hash));
1109
+ if (current === null || current === undefined)
1110
+ return false;
1111
+ const expires = typeof current === 'object' && 'expires' in current ? current.expires : undefined;
1112
+ return typeof expires !== 'number' || expires > Date.now();
1113
+ }
1057
1114
  /** @internal */
1058
1115
  async function releaseHashUse(store, hash) {
1059
1116
  await store.delete(getHashStoreKey(hash));
@@ -2415,7 +2415,7 @@ type SharedParameters = Omit<charge_.Parameters, 'machineTokenEnabled'> & sessio
2415
2415
  machineTokenEnabled?: boolean | undefined;
2416
2416
  };
2417
2417
  export declare namespace tempo {
2418
- /** An accepted address or chain-indexed USD token definition from `viem/tokens`. */
2418
+ /** An accepted address or USD token from `viem/tokens`, chain-indexed or resolved to one chain. */
2419
2419
  type Currency = Currencies.Currency;
2420
2420
  /** Shared charge/session configuration with mutually exclusive currency options. */
2421
2421
  type Parameters = Omit<SharedParameters, 'currency'> & ({