mppx 0.18.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/Currency.d.ts +59 -0
  3. package/dist/Currency.js +60 -0
  4. package/dist/Errors.d.ts +13 -0
  5. package/dist/Errors.js +15 -6
  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/email-otp/client/index.js +4 -4
  23. package/dist/extensions/identity/index.d.ts +4 -0
  24. package/dist/extensions/identity/index.js +4 -0
  25. package/dist/extensions/identity/link/Constants.d.ts +102 -0
  26. package/dist/extensions/identity/link/Constants.js +16 -0
  27. package/dist/extensions/identity/link/client/index.d.ts +80 -0
  28. package/dist/extensions/identity/link/client/index.js +211 -0
  29. package/dist/extensions/identity/link/index.d.ts +12 -0
  30. package/dist/extensions/identity/link/index.js +12 -0
  31. package/dist/extensions/identity/link/server/index.d.ts +124 -0
  32. package/dist/extensions/identity/link/server/index.js +518 -0
  33. package/dist/extensions/identity/persona/Constants.d.ts +24 -0
  34. package/dist/extensions/identity/persona/Constants.js +24 -0
  35. package/dist/extensions/identity/persona/Did.d.ts +24 -0
  36. package/dist/extensions/identity/persona/Did.js +24 -0
  37. package/dist/extensions/identity/persona/Types.d.ts +21 -0
  38. package/dist/extensions/identity/persona/Types.js +2 -0
  39. package/dist/extensions/identity/persona/index.d.ts +10 -0
  40. package/dist/extensions/identity/persona/index.js +9 -0
  41. package/dist/extensions/identity/persona/server/index.d.ts +152 -0
  42. package/dist/extensions/identity/persona/server/index.js +263 -0
  43. package/dist/identity/Headers.d.ts +6 -1
  44. package/dist/identity/Headers.js +6 -1
  45. package/dist/identity/Server.js +2 -0
  46. package/dist/identity/Types.d.ts +5 -0
  47. package/dist/index.d.ts +1 -0
  48. package/dist/index.js +1 -0
  49. package/dist/internal/version.d.ts +2 -2
  50. package/dist/internal/version.js +1 -1
  51. package/dist/proxy/internal/Headers.js +4 -4
  52. package/dist/server/Mppx.js +5 -2
  53. package/dist/stripe/server/internal/html.gen.js +1 -1
  54. package/dist/tempo/client/Charge.d.ts +11 -8
  55. package/dist/tempo/client/Charge.js +53 -6
  56. package/dist/tempo/index.d.ts +4 -0
  57. package/dist/tempo/index.js +4 -0
  58. package/dist/tempo/internal/auto-swap.d.ts +6 -5
  59. package/dist/tempo/internal/auto-swap.js +17 -2
  60. package/dist/tempo/internal/currencies.d.ts +5 -4
  61. package/dist/tempo/internal/currencies.js +13 -9
  62. package/dist/tempo/internal/defaults.d.ts +7 -0
  63. package/dist/tempo/internal/defaults.js +7 -0
  64. package/dist/tempo/internal/fee-payer.js +8 -2
  65. package/dist/tempo/internal/machine-token-charge.d.ts +52 -0
  66. package/dist/tempo/internal/machine-token-charge.js +82 -1
  67. package/dist/tempo/server/Charge.js +59 -2
  68. package/dist/tempo/server/Methods.d.ts +1 -1
  69. package/dist/tempo/server/internal/html.gen.js +1 -1
  70. package/dist/tempo/server/internal/transport.d.ts +1 -1
  71. package/dist/tempo/server/internal/transport.js +9 -16
  72. package/dist/tempo/session/client/CredentialState.js +31 -0
  73. package/dist/tempo/session/client/Session.d.ts +12 -6
  74. package/dist/tempo/session/client/Session.js +64 -18
  75. package/dist/tempo/session/server/ChannelStore.d.ts +22 -1
  76. package/dist/tempo/session/server/ChannelStore.js +58 -8
  77. package/dist/tempo/session/server/CloseSupervisor.d.ts +5 -1
  78. package/dist/tempo/session/server/CloseSupervisor.js +110 -12
  79. package/dist/tempo/session/server/CredentialVerification.d.ts +2 -0
  80. package/dist/tempo/session/server/CredentialVerification.js +6 -32
  81. package/dist/tempo/session/server/Session.js +6 -3
  82. package/dist/tempo/session/server/Settlement.d.ts +7 -0
  83. package/dist/tempo/session/server/Settlement.js +36 -6
  84. package/dist/tempo/session/server/Sse.d.ts +2 -0
  85. package/dist/tempo/session/server/Sse.js +12 -12
  86. package/dist/tempo/subscription/KeyAuthorization.d.ts +1 -1
  87. package/dist/tempo/subscription/KeyAuthorization.js +1 -1
  88. package/dist/x402/Assets.d.ts +14 -5
  89. package/dist/x402/Assets.js +11 -16
  90. package/package.json +15 -3
@@ -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
@@ -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'> & ({