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,10 +1,11 @@
1
1
  import { TxEnvelopeTempo } from 'ox/tempo';
2
2
  import { keccak256, parseEventLogs, parseUnits, } from 'viem';
3
- import { prepareTransactionRequest, sendCallsSync, sendRawTransactionSync, sendTransactionSync, signTypedData, signTransaction, waitForTransactionReceipt, } from 'viem/actions';
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
6
  import * as MethodResponse from '../../client/internal/MethodResponse.js';
7
7
  import * as Credential from '../../Credential.js';
8
+ import * as Currency from '../../Currency.js';
8
9
  import * as Errors from '../../Errors.js';
9
10
  import * as Method from '../../Method.js';
10
11
  import * as Account from '../../viem/Account.js';
@@ -55,8 +56,11 @@ export function charge(parameters = {}) {
55
56
  if ((parameters.maxAmount !== undefined || parameters.maxAtomicAmount !== undefined) &&
56
57
  parameters.currencies === undefined)
57
58
  throw new Error('Tempo charge maxAmount and maxAtomicAmount require currencies.');
59
+ // Fail at construction for any accepted currency whose decimals cannot parse `maxAmount`.
60
+ for (const currency of parameters.currencies ?? [])
61
+ parseMaxAmount(parameters.maxAmount, typeof currency === 'string' ? parameters.decimals : currency.decimals);
58
62
  const caps = {
59
- maxAmount: parseMaxAmount(parameters.maxAmount, parameters.decimals),
63
+ maxAmount: parameters.maxAmount,
60
64
  maxAtomicAmount: parameters.maxAtomicAmount === undefined ? undefined : BigInt(parameters.maxAtomicAmount),
61
65
  };
62
66
  const getClient = Client.getResolver({
@@ -93,6 +97,9 @@ export function charge(parameters = {}) {
93
97
  Client.assertAllowedChainId(parameters.allowedChainIds, chainId);
94
98
  if (chainId === undefined)
95
99
  throw new Error('No `chainId` provided. Pass a chain ID in the challenge or client.');
100
+ // A challenge without a chain ID was checked without one: check its currency on this chain.
101
+ if (challengeChainId === undefined)
102
+ assertChallengePolicy(parameters, caps, challenge.request, chainId);
96
103
  const { request } = challenge;
97
104
  const { amount, methodDetails } = request;
98
105
  const supportedModes = methodDetails?.supportedModes ?? ['pull', 'push'];
@@ -180,6 +187,8 @@ export function charge(parameters = {}) {
180
187
  : undefined;
181
188
  let account = defaultAccount;
182
189
  let machineTokenRoute;
190
+ // Whether the account could run the MACH route but lacked the MACH or the route reverted.
191
+ let machineTokenUnpayable = false;
183
192
  if (machineTokenCandidate) {
184
193
  const machineTokenAccount = await (async () => {
185
194
  try {
@@ -203,6 +212,8 @@ export function charge(parameters = {}) {
203
212
  });
204
213
  if (machineTokenRoute)
205
214
  account = machineTokenAccount;
215
+ else
216
+ machineTokenUnpayable = true;
206
217
  }
207
218
  }
208
219
  let swapCalls;
@@ -221,6 +232,17 @@ export function charge(parameters = {}) {
221
232
  maxAmountIn: autoSwap.maxAmountIn,
222
233
  })
223
234
  : undefined;
235
+ // Without MACH or the charge currency the payment can only revert, so say where to buy MACH.
236
+ if (machineTokenUnpayable && !autoSwap) {
237
+ const error = await getMachineTokenFundingError(client, {
238
+ account: account.address,
239
+ amount: BigInt(amount),
240
+ chainId,
241
+ currency,
242
+ });
243
+ if (error)
244
+ throw error;
245
+ }
224
246
  }
225
247
  const calls = machineTokenRoute?.calls ?? [...(swapCalls ?? []), ...transferCalls];
226
248
  const allowedFeeTokens = defaultFeeTokens(chainId);
@@ -346,6 +368,17 @@ export function charge(parameters = {}) {
346
368
  };
347
369
  return MethodResponse.registerTransactionHash({ ...method, createCredential }, transactionHash);
348
370
  }
371
+ /**
372
+ * Returns an error that links to the MACH onramp when a machine-token-enabled charge can't be paid:
373
+ * the account holds less than `amount` of both the charge currency and MACH.
374
+ */
375
+ async function getMachineTokenFundingError(client, parameters) {
376
+ const { account, amount, chainId, currency } = parameters;
377
+ const balance = await readContract(client, Actions.token.getBalance.call(client, { account, token: currency })).catch(() => undefined);
378
+ if (typeof balance !== 'bigint' || balance >= amount)
379
+ return undefined;
380
+ return MachineTokenCharge.getInsufficientBalanceError(client, { account, amount, chainId });
381
+ }
349
382
  /**
350
383
  * Returns the final transaction hash of a credential, when known before settlement.
351
384
  *
@@ -399,12 +432,20 @@ async function createZoneCredential(options) {
399
432
  pending.delete(key);
400
433
  });
401
434
  }
402
- const senderTag = await withdrawalRequest;
403
- let hash;
435
+ const withdrawal = await withdrawalRequest;
436
+ // Derived on every attempt, so a failed read on the Zone is retried without withdrawing again.
437
+ const senderTags = withdrawal.senderTags ??
438
+ (await Zone.senderTagCandidates(zone.client, withdrawal).catch((cause) => {
439
+ 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.`);
440
+ // Defined manually (non-enumerable, like native `cause`) so consumers on pre-ES2022 libs still typecheck.
441
+ Object.defineProperty(error, 'cause', { configurable: true, value: cause, writable: true });
442
+ throw error;
443
+ }));
444
+ let settled;
404
445
  try {
405
- hash = await Zone.waitForSettlement(client, {
446
+ settled = await Zone.waitForSettledWithdrawal(client, {
406
447
  portal: Zone.portalAddress(zoneId),
407
- senderTag,
448
+ senderTags,
408
449
  timeoutMs: settlementTimeoutMs(challenge.expires, zone.settlementTimeoutMs),
409
450
  to: recipient,
410
451
  });
@@ -413,11 +454,12 @@ async function createZoneCredential(options) {
413
454
  throw new Errors.ZoneSettlementPendingError({
414
455
  cause,
415
456
  challengeId: challenge.id,
416
- senderTag,
457
+ senderTags,
417
458
  zoneId,
418
459
  });
419
460
  }
420
461
  pending.delete(key);
462
+ const { hash, senderTag } = settled;
421
463
  return Credential.serialize({
422
464
  challenge,
423
465
  payload: { hash, senderTag, type: 'zone', zoneId },
@@ -467,7 +509,10 @@ function zoneWithdrawalKey(challenge) {
467
509
  }
468
510
  /** How long to look for a withdrawal's receipt on the Zone after its send response fails. */
469
511
  const zoneReceiptRecoveryTimeoutMs = 15_000;
470
- /** Requests a Zone withdrawal of the challenge amount to its recipient, bound to the challenge by its memo. */
512
+ /**
513
+ * Requests a Zone withdrawal of the challenge amount to its recipient, bound to the challenge by its memo.
514
+ * Returns its sender tag, or leaves it to be derived when the Zone RPC hides it from the receipt.
515
+ */
471
516
  async function requestZoneWithdrawal(options, state) {
472
517
  const { challenge, clientId, zone } = options;
473
518
  const request = challenge.request;
@@ -527,13 +572,21 @@ async function requestZoneWithdrawal(options, state) {
527
572
  eventName: 'WithdrawalRequested',
528
573
  logs: receipt.logs,
529
574
  });
530
- if (!requested)
531
- throw new Error('Zone withdrawal request did not emit `WithdrawalRequested`.');
532
- return Zone.senderTag({
533
- fallbackNonce: requested.args.fallbackNonce,
534
- sender: requested.args.sender,
575
+ return {
576
+ blockNumber: receipt.blockNumber,
577
+ sender: account.address,
578
+ // A Zone RPC that redacts logs leaves the outbox's event out of the payer's receipt.
579
+ senderTags: requested
580
+ ? [
581
+ Zone.senderTag({
582
+ fallbackNonce: requested.args.fallbackNonce,
583
+ sender: requested.args.sender,
584
+ transactionHash: receipt.transactionHash,
585
+ }),
586
+ ]
587
+ : undefined,
535
588
  transactionHash: receipt.transactionHash,
536
- });
589
+ };
537
590
  }
538
591
  /** Parses `maxAmount` to base units, rejecting values that cannot be represented exactly. */
539
592
  function parseMaxAmount(maxAmount, decimals) {
@@ -551,7 +604,9 @@ function parseMaxAmount(maxAmount, decimals) {
551
604
  * Rejects a challenge whose chain, currency, recipients, or amount violate the client policy.
552
605
  * Runs during challenge selection and again before any client, account, or signing work.
553
606
  */
554
- function assertChallengePolicy(parameters, caps, request) {
607
+ function assertChallengePolicy(parameters, caps, request,
608
+ /** Chain the client signs on, once resolved, for a challenge that names none. */
609
+ signingChainId) {
555
610
  const { amount, methodDetails, recipient } = request;
556
611
  // Chain pinning: reject a challenge whose chain ID conflicts with the pinned one.
557
612
  const challengeChainId = methodDetails?.chainId;
@@ -561,8 +616,19 @@ function assertChallengePolicy(parameters, caps, request) {
561
616
  throw new Error(`Chain ID mismatch: expected ${parameters.expectedChainId}, got ${challengeChainId}.`);
562
617
  if (challengeChainId !== undefined || parameters.allowedChainIds?.length === 0)
563
618
  Client.assertAllowedChainId(parameters.allowedChainIds, challengeChainId);
564
- if (parameters.currencies &&
565
- !parameters.currencies.some((c) => c.toLowerCase() === request.currency.toLowerCase()))
619
+ // Tokens match on the chain the client signs on: the challenge's, else the pinned or resolved
620
+ // one. Only selection, before a client is resolved, may match a token on any chain it lists,
621
+ // and `createCredential` checks the currency again on the resolved chain before signing.
622
+ const currency = parameters.currencies
623
+ ? Currency.find(parameters.currencies, request.currency, {
624
+ chainId: challengeChainId ??
625
+ signingChainId ??
626
+ parameters.expectedChainId ??
627
+ (parameters.allowedChainIds?.length === 1 ? parameters.allowedChainIds[0] : undefined),
628
+ decimals: parameters.decimals,
629
+ })
630
+ : undefined;
631
+ if (parameters.currencies && !currency)
566
632
  throw new Error(`Tempo charge currency is not allowed: ${request.currency}.`);
567
633
  if (parameters.expectedRecipients) {
568
634
  const allowed = new Set(parameters.expectedRecipients.map((a) => a.toLowerCase()));
@@ -578,7 +644,8 @@ function assertChallengePolicy(parameters, caps, request) {
578
644
  }
579
645
  if (caps.maxAtomicAmount !== undefined && BigInt(amount) > caps.maxAtomicAmount)
580
646
  throw new Error('Tempo charge amount exceeds maxAtomicAmount.');
581
- if (caps.maxAmount !== undefined && BigInt(amount) > caps.maxAmount)
647
+ if (caps.maxAmount !== undefined &&
648
+ BigInt(amount) > parseMaxAmount(caps.maxAmount, currency?.decimals))
582
649
  throw new Error('Tempo charge amount exceeds maxAmount.');
583
650
  }
584
651
  //# sourceMappingURL=Charge.js.map
@@ -6,4 +6,8 @@ export * as SessionLegacy from './legacy/index.js';
6
6
  export * as Subscription from './subscription/index.js';
7
7
  /** Canonical first-party machine-token deployments by Tempo chain ID. */
8
8
  export { machineToken as machineTokenDeployments } from './internal/defaults.js';
9
+ /** Tempo Wallet page that buys MACH on Tempo mainnet. */
10
+ export { machineTokenFundingBaseUrl } from './internal/defaults.js';
11
+ /** Builds the Tempo Wallet link that buys MACH, prefilled with a payer and amount. */
12
+ export { fundingUrl as machineTokenFundingUrl } from './internal/machine-token-charge.js';
9
13
  //# sourceMappingURL=index.d.ts.map
@@ -6,4 +6,8 @@ export * as SessionLegacy from './legacy/index.js';
6
6
  export * as Subscription from './subscription/index.js';
7
7
  /** Canonical first-party machine-token deployments by Tempo chain ID. */
8
8
  export { machineToken as machineTokenDeployments } from './internal/defaults.js';
9
+ /** Tempo Wallet page that buys MACH on Tempo mainnet. */
10
+ export { machineTokenFundingBaseUrl } from './internal/defaults.js';
11
+ /** Builds the Tempo Wallet link that buys MACH, prefilled with a payer and amount. */
12
+ export { fundingUrl as machineTokenFundingUrl } from './internal/machine-token-charge.js';
9
13
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,5 @@
1
1
  import type { Address, Client } from 'viem';
2
+ import * as Currency from '../../Currency.js';
2
3
  /** Default fallback currencies for auto-swap, in priority order. */
3
4
  export declare const defaultCurrencies: readonly Address[];
4
5
  /**
@@ -15,8 +16,8 @@ export declare namespace findCalls {
15
16
  account: Address;
16
17
  /** Amount of the target token needed. */
17
18
  amountOut: bigint;
18
- /** Candidate input tokens to swap from, in priority order. */
19
- tokenIn: readonly Address[];
19
+ /** Candidate input tokens to swap from, in priority order, resolved on the client's chain. */
20
+ tokenIn: readonly Currency.Currency[];
20
21
  /** Maximum input-token units to spend. Defaults to the missing output amount plus slippage (1:1 units). */
21
22
  maxAmountIn?: bigint | undefined;
22
23
  /** Max slippage tolerance as a percentage (e.g. `1` = 1%). */
@@ -33,8 +34,8 @@ export declare namespace resolve {
33
34
  type Options = {
34
35
  /** Maximum input-token units per swap. Defaults to parity with the missing output amount plus slippage; set explicitly for non-parity pairs. */
35
36
  maxAmountIn?: bigint | undefined;
36
- /** Fallback tokens to try swapping from, in priority order. */
37
- tokenIn?: Address[] | undefined;
37
+ /** Fallback tokens to try swapping from, in priority order: addresses or `viem/tokens` tokens. */
38
+ tokenIn?: readonly Currency.Currency[] | undefined;
38
39
  /**
39
40
  * Whether to also try the default currencies after `tokenIn`. Set `false` to swap only from
40
41
  * `tokenIn`, as an allowlist. Ignored without `tokenIn`. @default true
@@ -45,7 +46,7 @@ export declare namespace resolve {
45
46
  };
46
47
  type Value = boolean | Options;
47
48
  type Resolved = {
48
- tokenIn: readonly Address[];
49
+ tokenIn: readonly Currency.Currency[];
49
50
  slippage: number;
50
51
  maxAmountIn?: bigint | undefined;
51
52
  };
@@ -1,5 +1,6 @@
1
1
  import { readContract } from 'viem/actions';
2
2
  import { Actions, Addresses } from 'viem/tempo';
3
+ import * as Currency from '../../Currency.js';
3
4
  import * as TempoAddress from './address.js';
4
5
  import * as defaults from './defaults.js';
5
6
  /** Basis-point denominator (100% = 10 000 bps). */
@@ -23,7 +24,21 @@ export async function findCalls(client, parameters) {
23
24
  throw new Error('Auto-swap slippage must be between 0 and 50 percent.');
24
25
  if (parameters.maxAmountIn !== undefined && parameters.maxAmountIn <= 0n)
25
26
  throw new Error('Auto-swap maxAmountIn must be positive.');
26
- const candidates = tokenIn.filter((t) => !TempoAddress.isEqual(t, tokenOut));
27
+ // Tokens resolve on the client's chain; ones without an address there are skipped.
28
+ const chainId = client.chain?.id;
29
+ const candidates = [];
30
+ for (const currency of tokenIn) {
31
+ const address = typeof currency === 'string'
32
+ ? currency
33
+ : chainId === undefined
34
+ ? undefined
35
+ : Currency.resolve(currency, { chainId })?.address;
36
+ if (!address || TempoAddress.isEqual(address, tokenOut))
37
+ continue;
38
+ if (candidates.some((candidate) => TempoAddress.isEqual(candidate, address)))
39
+ continue;
40
+ candidates.push(address);
41
+ }
27
42
  // Reads never carry the client's account: a node refuses every call from an access key whose
28
43
  // authorization is not yet published, which would hide every route from a new key.
29
44
  const balanceResults = await Promise.allSettled([
@@ -98,7 +113,7 @@ export function resolve(value, defaultCurrencies) {
98
113
  ...value.tokenIn,
99
114
  ...(value.fallback === false
100
115
  ? []
101
- : defaultCurrencies.filter((d) => !value.tokenIn.some((c) => TempoAddress.isEqual(c, d)))),
116
+ : defaultCurrencies.filter((d) => !value.tokenIn.some((c) => typeof c === 'string' && TempoAddress.isEqual(c, d)))),
102
117
  ]
103
118
  : defaultCurrencies;
104
119
  return {
@@ -1,11 +1,12 @@
1
- import type { Token } from 'viem/tokens';
2
- /** An explicit token address or a chain-indexed token definition. */
3
- export type Currency = string | Token;
1
+ import * as Currency_ from '../../Currency.js';
2
+ /** An accepted Tempo currency: an address or a `viem/tokens` token, chain-indexed or resolved. */
3
+ export type Currency = Currency_.Currency;
4
4
  /** Resolves ordered USD offers without expanding acceptance from a live registry. */
5
5
  export declare function resolve(parameters: {
6
6
  chainId?: number | undefined;
7
7
  testnet?: boolean | undefined;
8
- currencies?: readonly Currency[] | undefined;
8
+ /** Accepted currencies. A plain string is a token address (the deprecated `currency` option). */
9
+ currencies?: readonly (Currency | (string & {}))[] | undefined;
9
10
  decimals?: number | undefined;
10
11
  }): [({
11
12
  currency: string;
@@ -1,4 +1,5 @@
1
1
  import { isAddress } from 'viem';
2
+ import * as Currency_ from '../../Currency.js';
2
3
  import * as defaults from './defaults.js';
3
4
  /** Resolves ordered USD offers without expanding acceptance from a live registry. */
4
5
  export function resolve(parameters) {
@@ -7,8 +8,7 @@ export function resolve(parameters) {
7
8
  (chainId === defaults.chainId.mainnet
8
9
  ? [defaults.tokens.ousd, defaults.tokens.usdc]
9
10
  : chainId === defaults.chainId.testnet
10
- ? // TODO: Use viem's chain-specific OUSD definition once it includes Moderato (42431).
11
- [defaults.tokens.ousd, defaults.tokens.pathUsd]
11
+ ? [defaults.tokens.ousd, defaults.tokens.pathUsd]
12
12
  : [defaults.resolveCurrency({ chainId })]);
13
13
  const seen = new Set();
14
14
  const resolved = [];
@@ -16,23 +16,27 @@ export function resolve(parameters) {
16
16
  // A shared USD price cannot also price EUR, BTC, or unknown denominations.
17
17
  if (typeof token !== 'string' && token.currency !== 'USD')
18
18
  continue;
19
- const currency = typeof token === 'string' ? token : token.addresses[chainId];
19
+ const currency = Currency_.resolve(token, {
20
+ chainId,
21
+ decimals: parameters.decimals ?? defaults.decimals,
22
+ });
23
+ // Tokens not on this chain are skipped before their decimals are compared.
20
24
  if (currency === undefined)
21
25
  continue;
22
- if (!isAddress(currency, { strict: false }))
23
- throw new Error(`Invalid Tempo currency address: ${currency}.`);
24
- const decimals = typeof token === 'string' ? (parameters.decimals ?? defaults.decimals) : token.decimals;
25
26
  if (typeof token !== 'string' &&
26
27
  parameters.decimals !== undefined &&
27
- parameters.decimals !== decimals)
28
+ parameters.decimals !== token.decimals)
28
29
  throw new Error('Configured `decimals` must match each token definition.');
30
+ if (!isAddress(currency.address, { strict: false }))
31
+ throw new Error(`Invalid Tempo currency address: ${currency.address}.`);
32
+ const decimals = currency.decimals ?? defaults.decimals;
29
33
  if (!Number.isInteger(decimals) || decimals < 0 || decimals > 255)
30
34
  throw new Error('Token decimals must be an integer between 0 and 255.');
31
- const key = currency.toLowerCase();
35
+ const key = currency.address.toLowerCase();
32
36
  if (seen.has(key))
33
37
  continue;
34
38
  seen.add(key);
35
- resolved.push({ currency, decimals, chainId });
39
+ resolved.push({ currency: currency.address, decimals, chainId });
36
40
  }
37
41
  if (resolved.length === 0)
38
42
  throw new Error(`No accepted USD currencies for chain ${chainId}.`);
@@ -29,6 +29,13 @@ export declare const machineToken: Readonly<{
29
29
  token: "0x20c000000000000000000000f37de3740ADec032";
30
30
  }>;
31
31
  }>;
32
+ /**
33
+ * Tempo Wallet page that buys MACH on Tempo mainnet, the only chain it sells MACH on.
34
+ *
35
+ * Add `address` (the payer) and `amount` (USD, at most two decimals) query parameters to
36
+ * prefill it, or build the link with `machineTokenFundingUrl`.
37
+ */
38
+ export declare const machineTokenFundingBaseUrl = "https://wallet.tempo.xyz/agent?action=fund&intent=mach&chainId=4217";
32
39
  /**
33
40
  * Default token decimals for TIP-20 stablecoins (e.g. pathUSD, USDC).
34
41
  *
@@ -29,6 +29,13 @@ export const machineToken = Object.freeze({
29
29
  token: '0x20c000000000000000000000f37de3740ADec032',
30
30
  }),
31
31
  });
32
+ /**
33
+ * Tempo Wallet page that buys MACH on Tempo mainnet, the only chain it sells MACH on.
34
+ *
35
+ * Add `address` (the payer) and `amount` (USD, at most two decimals) query parameters to
36
+ * prefill it, or build the link with `machineTokenFundingUrl`.
37
+ */
38
+ export const machineTokenFundingBaseUrl = 'https://wallet.tempo.xyz/agent?action=fund&intent=mach&chainId=4217';
32
39
  /**
33
40
  * Default token decimals for TIP-20 stablecoins (e.g. pathUSD, USDC).
34
41
  *
@@ -341,11 +341,17 @@ export async function preflightSponsorship(parameters) {
341
341
  return { feePayerSignature: completed.feePayerSignature, transaction: completed.transaction };
342
342
  // The signature binds the gas limit, so a local fee payer signs a simulation-only copy
343
343
  // with headroom for the node's sponsored `eth_call` overhead. The broadcast keeps its gas.
344
- const padded = gas === undefined
344
+ // The node's `eth_call` recovers the fee payer of an expiring-nonce transaction as if its
345
+ // `nonce` were 0, so the copy zeroes the random discriminator. The broadcast keeps its nonce.
346
+ const expiring = completed.transaction.nonceKey === maxUint256;
347
+ const padded = gas === undefined && !expiring
345
348
  ? completed.transaction
346
349
  : {
347
350
  ...completed.transaction,
348
- gas: sponsoredSimulationGas(completed.transaction, policy),
351
+ ...(gas !== undefined
352
+ ? { gas: sponsoredSimulationGas(completed.transaction, policy) }
353
+ : {}),
354
+ ...(expiring ? { nonce: 0 } : {}),
349
355
  };
350
356
  const feePayerSignature = await signFeePayerSimulation(padded);
351
357
  return feePayerSignature
@@ -1,5 +1,6 @@
1
1
  import type * as Hex from 'ox/Hex';
2
2
  import { type Address, type Client } from 'viem';
3
+ import * as Errors from '../../Errors.js';
3
4
  /** ABI for the first-party machine-token settlement swapper. */
4
5
  export declare const machineTokenSwapperAbi: readonly [{
5
6
  readonly name: "swapTo";
@@ -75,5 +76,56 @@ export declare function matchRoute(parameters: {
75
76
  }): Route | undefined;
76
77
  /** Returns the trusted sender that settles the configured charge route on a chain. */
77
78
  export declare function getSettlementSender(chainId: number | undefined): Address | undefined;
79
+ /**
80
+ * Builds the Tempo Wallet link that buys MACH.
81
+ *
82
+ * Returns `undefined` on chains other than Tempo mainnet (4217), where the wallet sells no MACH.
83
+ * `amount` is in MACH base units (6 decimals) and is rounded up to whole cents.
84
+ *
85
+ * @example
86
+ * ```ts
87
+ * import { Tempo } from 'mppx'
88
+ *
89
+ * Tempo.machineTokenFundingUrl({ address: '0x…', amount: 1_250_000n })
90
+ * // https://wallet.tempo.xyz/agent?action=fund&intent=mach&chainId=4217&address=0x…&amount=1.25
91
+ * ```
92
+ */
93
+ export declare function fundingUrl(parameters?: {
94
+ /** Payer to fund. The wallet asks the user to sign in with this address. */
95
+ address?: Address | undefined;
96
+ /** MACH to buy, in base units. */
97
+ amount?: bigint | undefined;
98
+ /** Chain of the payment. Defaults to Tempo mainnet. */
99
+ chainId?: number | undefined;
100
+ }): string | undefined;
101
+ /**
102
+ * Returns `account`'s MACH balance, or `undefined` when the chain has no machine-token deployment or
103
+ * the balance can't be read.
104
+ */
105
+ export declare function getBalance(client: Client, parameters: {
106
+ account: Address;
107
+ chainId: number | undefined;
108
+ }): Promise<bigint | undefined>;
109
+ /**
110
+ * Returns how far `account`'s MACH balance falls short of `amount`, with a reason and the MACH onramp
111
+ * link (on Tempo mainnet) to report it.
112
+ *
113
+ * Returns `undefined` when the chain has no machine-token deployment, the account holds enough MACH,
114
+ * or its balance can't be read.
115
+ */
116
+ export declare function getShortfall(client: Client, parameters: {
117
+ account: Address;
118
+ amount: bigint;
119
+ chainId: number | undefined;
120
+ }): Promise<{
121
+ fundingUrl: string | undefined;
122
+ reason: string;
123
+ shortfall: bigint;
124
+ } | undefined>;
125
+ /**
126
+ * Returns an `InsufficientBalanceError` that links to the MACH onramp when `account` holds less
127
+ * MACH than `amount`. See `getShortfall`.
128
+ */
129
+ export declare function getInsufficientBalanceError(client: Client, parameters: Parameters<typeof getShortfall>[1]): Promise<Errors.InsufficientBalanceError | undefined>;
78
130
  export {};
79
131
  //# sourceMappingURL=machine-token-charge.d.ts.map
@@ -1,6 +1,7 @@
1
- import { decodeFunctionData, encodeFunctionData, isAddress, isAddressEqual, parseAbi, } from 'viem';
1
+ import { decodeFunctionData, encodeFunctionData, formatUnits, getAddress, isAddress, isAddressEqual, parseAbi, } from 'viem';
2
2
  import { call, readContract } from 'viem/actions';
3
3
  import { Abis, Actions } from 'viem/tempo';
4
+ import * as Errors from '../../Errors.js';
4
5
  import * as defaults from './defaults.js';
5
6
  /** ABI for the first-party machine-token settlement swapper. */
6
7
  export const machineTokenSwapperAbi = parseAbi([
@@ -106,4 +107,84 @@ export function matchRoute(parameters) {
106
107
  export function getSettlementSender(chainId) {
107
108
  return getDeployment(chainId)?.swap;
108
109
  }
110
+ /** MACH base units per cent: MACH has 6 decimals and trades 1:1 with USD. */
111
+ const unitsPerCent = 10n ** BigInt(defaults.decimals - 2);
112
+ /**
113
+ * Builds the Tempo Wallet link that buys MACH.
114
+ *
115
+ * Returns `undefined` on chains other than Tempo mainnet (4217), where the wallet sells no MACH.
116
+ * `amount` is in MACH base units (6 decimals) and is rounded up to whole cents.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * import { Tempo } from 'mppx'
121
+ *
122
+ * Tempo.machineTokenFundingUrl({ address: '0x…', amount: 1_250_000n })
123
+ * // https://wallet.tempo.xyz/agent?action=fund&intent=mach&chainId=4217&address=0x…&amount=1.25
124
+ * ```
125
+ */
126
+ export function fundingUrl(parameters = {}) {
127
+ const { address, amount, chainId = defaults.chainId.mainnet } = parameters;
128
+ if (chainId !== defaults.chainId.mainnet)
129
+ return undefined;
130
+ const url = new URL(defaults.machineTokenFundingBaseUrl);
131
+ if (address && isAddress(address, { strict: false }))
132
+ url.searchParams.set('address', getAddress(address));
133
+ if (amount !== undefined && amount > 0n) {
134
+ const cents = (amount + unitsPerCent - 1n) / unitsPerCent;
135
+ const fraction = cents % 100n;
136
+ const whole = (cents / 100n).toString();
137
+ url.searchParams.set('amount', fraction === 0n
138
+ ? whole
139
+ : `${whole}.${fraction.toString().padStart(2, '0').replace(/0$/, '')}`);
140
+ }
141
+ return url.toString();
142
+ }
143
+ /**
144
+ * Returns `account`'s MACH balance, or `undefined` when the chain has no machine-token deployment or
145
+ * the balance can't be read.
146
+ */
147
+ export async function getBalance(client, parameters) {
148
+ const deployment = getDeployment(parameters.chainId);
149
+ if (!deployment)
150
+ return undefined;
151
+ const balance = await readContract(client, Actions.token.getBalance.call(client, {
152
+ account: parameters.account,
153
+ token: deployment.token,
154
+ })).catch(() => undefined);
155
+ return typeof balance === 'bigint' ? balance : undefined;
156
+ }
157
+ /**
158
+ * Returns how far `account`'s MACH balance falls short of `amount`, with a reason and the MACH onramp
159
+ * link (on Tempo mainnet) to report it.
160
+ *
161
+ * Returns `undefined` when the chain has no machine-token deployment, the account holds enough MACH,
162
+ * or its balance can't be read.
163
+ */
164
+ export async function getShortfall(client, parameters) {
165
+ const { account, amount, chainId } = parameters;
166
+ const balance = await getBalance(client, { account, chainId });
167
+ if (balance === undefined || balance >= amount)
168
+ return undefined;
169
+ const format = (value) => `${formatUnits(value, defaults.decimals)} MACH`;
170
+ const shortfall = amount - balance;
171
+ return {
172
+ fundingUrl: fundingUrl({ address: account, amount: shortfall, chainId }),
173
+ reason: `requested ${format(amount)}, available ${format(balance)}`,
174
+ shortfall,
175
+ };
176
+ }
177
+ /**
178
+ * Returns an `InsufficientBalanceError` that links to the MACH onramp when `account` holds less
179
+ * MACH than `amount`. See `getShortfall`.
180
+ */
181
+ export async function getInsufficientBalanceError(client, parameters) {
182
+ const shortfall = await getShortfall(client, parameters);
183
+ if (!shortfall)
184
+ return undefined;
185
+ return new Errors.InsufficientBalanceError({
186
+ fundingUrl: shortfall.fundingUrl,
187
+ reason: shortfall.reason,
188
+ });
189
+ }
109
190
  //# sourceMappingURL=machine-token-charge.js.map
@@ -66,6 +66,20 @@ export declare function findWithdrawal(calls: readonly {
66
66
  portal: Address;
67
67
  senderTag: Hex;
68
68
  }): Withdrawal | undefined;
69
+ /**
70
+ * Derives the sender tags a withdrawal transaction may carry when its receipt
71
+ * has no `WithdrawalRequested` event, as on a Zone RPC that redacts logs.
72
+ *
73
+ * The outbox numbers each withdrawal with the next `lastFallbackNonce`, so the
74
+ * transaction's withdrawal took one of the nonces its block added. Every
75
+ * candidate hashes the payer's address and transaction, so only the payer's
76
+ * withdrawal can match one.
77
+ */
78
+ export declare function senderTagCandidates(client: Client, parameters: {
79
+ blockNumber: bigint;
80
+ sender: Address;
81
+ transactionHash: Hex;
82
+ }): Promise<readonly Hex[]>;
69
83
  /**
70
84
  * Waits until a portal emits `WithdrawalProcessed` for a sender tag and
71
85
  * returns the Tempo transaction hash that settled it.
@@ -76,4 +90,17 @@ export declare function waitForSettlement(client: Client, parameters: {
76
90
  to?: Address | undefined;
77
91
  timeoutMs?: number | undefined;
78
92
  }): Promise<Hex>;
93
+ /**
94
+ * Waits until a portal emits `WithdrawalProcessed` for any of several sender
95
+ * tags, and returns the tag and the Tempo transaction hash that settled it.
96
+ */
97
+ export declare function waitForSettledWithdrawal(client: Client, parameters: {
98
+ portal: Address;
99
+ senderTags: readonly Hex[];
100
+ to?: Address | undefined;
101
+ timeoutMs?: number | undefined;
102
+ }): Promise<{
103
+ hash: Hex;
104
+ senderTag: Hex;
105
+ }>;
79
106
  //# sourceMappingURL=zone.d.ts.map