mppx 0.17.6 → 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 (144) hide show
  1. package/CHANGELOG.md +43 -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 +138 -138
  7. package/dist/cli/plugins/index.js +12 -12
  8. package/dist/cli/plugins/tempo.js +13 -1
  9. package/dist/client/Mppx.js +13 -4
  10. package/dist/client/internal/Fetch.d.ts +5 -0
  11. package/dist/client/internal/Fetch.js +16 -5
  12. package/dist/cloudflare/ChannelStore.d.ts +1 -2
  13. package/dist/cloudflare/ChannelStore.js +14 -20
  14. package/dist/cloudflare/Channels.d.ts +20 -2
  15. package/dist/cloudflare/Channels.js +47 -4
  16. package/dist/cloudflare/index.d.ts +1 -1
  17. package/dist/cloudflare/index.js +1 -1
  18. package/dist/discovery/Discovery.d.ts +116 -9
  19. package/dist/discovery/Discovery.js +169 -0
  20. package/dist/evm/server/Charge.js +2 -3
  21. package/dist/evm/server/Methods.d.ts +1 -1
  22. package/dist/evm/server/Methods.js +3 -2
  23. package/dist/extensions/identity/{email-otp/internal → attestation}/Constants.d.ts +4 -1
  24. package/dist/extensions/identity/{email-otp/internal → attestation}/Constants.js +4 -1
  25. package/dist/extensions/identity/{email-otp/internal → attestation}/Jwks.d.ts +5 -5
  26. package/dist/extensions/identity/{email-otp/internal → attestation}/Jwks.js +1 -1
  27. package/dist/extensions/identity/{email-otp/internal/Attestation.d.ts → attestation/Token.d.ts} +40 -26
  28. package/dist/extensions/identity/{email-otp/internal/Attestation.js → attestation/Token.js} +18 -3
  29. package/dist/extensions/identity/{email-otp/internal → attestation}/Types.d.ts +14 -14
  30. package/dist/extensions/identity/attestation/client/index.d.ts +66 -0
  31. package/dist/extensions/identity/attestation/client/index.js +273 -0
  32. package/dist/extensions/identity/attestation/index.d.ts +20 -0
  33. package/dist/extensions/identity/attestation/index.js +18 -0
  34. package/dist/extensions/identity/attestation/internal/Cache.d.ts +120 -0
  35. package/dist/extensions/identity/attestation/internal/Cache.js +90 -0
  36. package/dist/extensions/identity/attestation/server/index.d.ts +66 -0
  37. package/dist/extensions/identity/attestation/server/index.js +119 -0
  38. package/dist/extensions/identity/email-otp/Constants.d.ts +5 -5
  39. package/dist/extensions/identity/email-otp/Constants.js +6 -5
  40. package/dist/extensions/identity/email-otp/Types.d.ts +4 -4
  41. package/dist/extensions/identity/email-otp/client/index.d.ts +22 -15
  42. package/dist/extensions/identity/email-otp/client/index.js +21 -9
  43. package/dist/extensions/identity/email-otp/index.d.ts +3 -8
  44. package/dist/extensions/identity/email-otp/index.js +3 -8
  45. package/dist/extensions/identity/email-otp/server/index.d.ts +16 -16
  46. package/dist/extensions/identity/email-otp/server/index.js +17 -14
  47. package/dist/extensions/identity/index.d.ts +6 -0
  48. package/dist/extensions/identity/index.js +6 -0
  49. package/dist/extensions/identity/internal/Verification.js +9 -5
  50. package/dist/extensions/identity/link/Constants.d.ts +102 -0
  51. package/dist/extensions/identity/link/Constants.js +16 -0
  52. package/dist/extensions/identity/link/client/index.d.ts +80 -0
  53. package/dist/extensions/identity/link/client/index.js +211 -0
  54. package/dist/extensions/identity/link/index.d.ts +12 -0
  55. package/dist/extensions/identity/link/index.js +12 -0
  56. package/dist/extensions/identity/link/server/index.d.ts +124 -0
  57. package/dist/extensions/identity/link/server/index.js +518 -0
  58. package/dist/extensions/identity/persona/Constants.d.ts +24 -0
  59. package/dist/extensions/identity/persona/Constants.js +24 -0
  60. package/dist/extensions/identity/persona/Did.d.ts +24 -0
  61. package/dist/extensions/identity/persona/Did.js +24 -0
  62. package/dist/extensions/identity/persona/Types.d.ts +21 -0
  63. package/dist/extensions/identity/persona/Types.js +2 -0
  64. package/dist/extensions/identity/persona/index.d.ts +10 -0
  65. package/dist/extensions/identity/persona/index.js +9 -0
  66. package/dist/extensions/identity/persona/server/index.d.ts +152 -0
  67. package/dist/extensions/identity/persona/server/index.js +263 -0
  68. package/dist/identity/Callback.d.ts +24 -5
  69. package/dist/identity/Callback.js +35 -11
  70. package/dist/identity/Client.d.ts +78 -5
  71. package/dist/identity/Client.js +165 -48
  72. package/dist/identity/Headers.d.ts +21 -0
  73. package/dist/identity/Headers.js +24 -0
  74. package/dist/identity/Server.d.ts +159 -37
  75. package/dist/identity/Server.js +309 -138
  76. package/dist/identity/Status.d.ts +14 -0
  77. package/dist/identity/Status.js +19 -0
  78. package/dist/identity/Types.d.ts +166 -65
  79. package/dist/identity/index.d.ts +2 -0
  80. package/dist/identity/index.js +2 -0
  81. package/dist/identity/internal/Requirements.d.ts +28 -0
  82. package/dist/identity/internal/Requirements.js +78 -0
  83. package/dist/index.d.ts +1 -0
  84. package/dist/index.js +1 -0
  85. package/dist/integrations/x402/Evm.d.ts +1 -0
  86. package/dist/internal/env.d.ts +14 -0
  87. package/dist/internal/env.js +38 -0
  88. package/dist/internal/version.d.ts +2 -2
  89. package/dist/internal/version.js +1 -1
  90. package/dist/proxy/internal/Headers.d.ts +1 -1
  91. package/dist/proxy/internal/Headers.js +11 -7
  92. package/dist/server/Mppx.d.ts +14 -6
  93. package/dist/server/Mppx.js +256 -149
  94. package/dist/server/internal/challengeMeta.d.ts +0 -6
  95. package/dist/server/internal/challengeMeta.js +3 -17
  96. package/dist/stripe/server/internal/html.gen.js +1 -1
  97. package/dist/tempo/client/Charge.d.ts +11 -8
  98. package/dist/tempo/client/Charge.js +53 -6
  99. package/dist/tempo/index.d.ts +4 -0
  100. package/dist/tempo/index.js +4 -0
  101. package/dist/tempo/internal/auto-swap.d.ts +6 -5
  102. package/dist/tempo/internal/auto-swap.js +17 -2
  103. package/dist/tempo/internal/currencies.d.ts +5 -4
  104. package/dist/tempo/internal/currencies.js +13 -9
  105. package/dist/tempo/internal/defaults.d.ts +7 -0
  106. package/dist/tempo/internal/defaults.js +7 -0
  107. package/dist/tempo/internal/fee-payer.js +8 -2
  108. package/dist/tempo/internal/machine-token-charge.d.ts +52 -0
  109. package/dist/tempo/internal/machine-token-charge.js +82 -1
  110. package/dist/tempo/server/Charge.d.ts +14 -9
  111. package/dist/tempo/server/Charge.js +64 -3
  112. package/dist/tempo/server/Methods.d.ts +1 -1
  113. package/dist/tempo/server/Methods.js +4 -1
  114. package/dist/tempo/server/Subscription.d.ts +8 -0
  115. package/dist/tempo/server/internal/fallback-store.d.ts +7 -2
  116. package/dist/tempo/server/internal/fallback-store.js +12 -3
  117. package/dist/tempo/server/internal/html.gen.js +1 -1
  118. package/dist/tempo/server/internal/transport.d.ts +1 -1
  119. package/dist/tempo/server/internal/transport.js +9 -16
  120. package/dist/tempo/session/client/CredentialState.js +31 -0
  121. package/dist/tempo/session/client/Session.d.ts +12 -6
  122. package/dist/tempo/session/client/Session.js +64 -18
  123. package/dist/tempo/session/server/ChannelStore.d.ts +22 -1
  124. package/dist/tempo/session/server/ChannelStore.js +58 -8
  125. package/dist/tempo/session/server/CloseSupervisor.d.ts +5 -1
  126. package/dist/tempo/session/server/CloseSupervisor.js +110 -12
  127. package/dist/tempo/session/server/CredentialVerification.d.ts +2 -0
  128. package/dist/tempo/session/server/CredentialVerification.js +6 -32
  129. package/dist/tempo/session/server/Session.d.ts +5 -1
  130. package/dist/tempo/session/server/Session.js +6 -3
  131. package/dist/tempo/session/server/Settlement.d.ts +7 -0
  132. package/dist/tempo/session/server/Settlement.js +36 -6
  133. package/dist/tempo/session/server/Sse.d.ts +2 -0
  134. package/dist/tempo/session/server/Sse.js +12 -12
  135. package/dist/tempo/subscription/KeyAuthorization.d.ts +1 -1
  136. package/dist/tempo/subscription/KeyAuthorization.js +1 -1
  137. package/dist/x402/Assets.d.ts +14 -5
  138. package/dist/x402/Assets.js +11 -16
  139. package/package.json +19 -3
  140. package/dist/extensions/identity/email-otp/internal/Prover.d.ts +0 -46
  141. package/dist/extensions/identity/email-otp/internal/Prover.js +0 -168
  142. package/dist/extensions/identity/email-otp/internal/Verifier.d.ts +0 -56
  143. package/dist/extensions/identity/email-otp/internal/Verifier.js +0 -116
  144. /package/dist/extensions/identity/{email-otp/internal → attestation}/Types.js +0 -0
@@ -13,7 +13,7 @@ export type PrepaidSessionReceipt = SessionReceipt & {
13
13
  [prepaidRefundKey]?: string | undefined;
14
14
  };
15
15
  /** Marks a session receipt as already charged for the current request. */
16
- export declare function markPrepaidSessionTick(receipt: SessionReceipt): SessionReceipt;
16
+ export declare function markPrepaidSessionTick(receipt: SessionReceipt, refundKey?: string): SessionReceipt;
17
17
  /**
18
18
  * Creates a Tempo-metered SSE transport.
19
19
  *
@@ -1,13 +1,5 @@
1
- /**
2
- * Tempo-specific SSE transport that wraps the base HTTP transport
3
- * with metering logic (context capture from verified credentials, per-token
4
- * charging via Sse.serve).
5
- *
6
- * @internal
7
- */
8
1
  import * as Challenge from '../../../Challenge.js';
9
2
  import * as Constants from '../../../Constants.js';
10
- import * as Errors from '../../../Errors.js';
11
3
  import * as Transport from '../../../server/Transport.js';
12
4
  import { requireSessionCredentialContext } from '../../session/precompile/Protocol.js';
13
5
  import * as ChannelStore from '../../session/server/ChannelStore.js';
@@ -17,11 +9,11 @@ const prepaidSessionTick = Symbol('mppx.prepaidSessionTick');
17
9
  const consumedPrepaidReceipts = new WeakSet();
18
10
  const prepaidRefundKey = Symbol('mppx.prepaidRefundKey');
19
11
  /** Marks a session receipt as already charged for the current request. */
20
- export function markPrepaidSessionTick(receipt) {
12
+ export function markPrepaidSessionTick(receipt, refundKey) {
21
13
  if (hasPrepaidSessionTick(receipt))
22
14
  return receipt;
23
15
  Object.defineProperty(receipt, prepaidRefundKey, {
24
- value: `stream:${globalThis.crypto.randomUUID()}`,
16
+ value: refundKey ?? `stream:${globalThis.crypto.randomUUID()}`,
25
17
  });
26
18
  Object.defineProperty(receipt, prepaidSessionTick, {
27
19
  configurable: false,
@@ -118,6 +110,9 @@ export function sse(options) {
118
110
  await Sse_core.preparePrepaidRefund(streamOptions);
119
111
  return Sse_core.toResponse(Sse_core.serve(streamOptions));
120
112
  }
113
+ const deliveryKey = receipt[prepaidRefundKey];
114
+ if (deliveryKey)
115
+ await Sse_core.clearPrepaidRefund(store, channelId, deliveryKey);
121
116
  const baseResponse = base.respondReceipt({
122
117
  credential: verifiedCredential,
123
118
  envelope,
@@ -134,10 +129,10 @@ export function sse(options) {
134
129
  if (hasPrepaidSessionTick(currentReceipt)) {
135
130
  return baseResponse;
136
131
  }
132
+ const sessionRequest = verifiedCredential.challenge.request;
133
+ const insufficientBalance = (available) => ChannelStore.insufficientBalance({ chainId: sessionRequest.methodDetails?.chainId, token: sessionRequest.currency }, `requested ${tickCost}, available ${available}`);
137
134
  const paymentRequired = (available) => {
138
- const error = new Errors.InsufficientBalanceError({
139
- reason: `requested ${tickCost}, available ${available}`,
140
- });
135
+ const error = insufficientBalance(available);
141
136
  return new Response(JSON.stringify(error.toProblemDetails(verifiedCredential.challenge.id)), {
142
137
  status: error.status,
143
138
  headers: {
@@ -184,9 +179,7 @@ export function sse(options) {
184
179
  // deduction completes before consumer reads
185
180
  const result = await chargePlainResponse();
186
181
  if (!result.ok) {
187
- controller.error(new Errors.InsufficientBalanceError({
188
- reason: `requested ${tickCost}, available ${result.channel.highestVoucherAmount - result.channel.spent}`,
189
- }));
182
+ controller.error(insufficientBalance(result.channel.highestVoucherAmount - result.channel.spent));
190
183
  return;
191
184
  }
192
185
  if (!chargedResponse.body) {
@@ -3,6 +3,7 @@ import * as Constants from '../../../Constants.js';
3
3
  import { assertAllowedChainId, assertChainId } from '../../../viem/Client.js';
4
4
  import * as z from '../../../zod.js';
5
5
  import * as AutoSwap from '../../internal/auto-swap.js';
6
+ import * as MachineTokenCharge from '../../internal/machine-token-charge.js';
6
7
  import * as Chain from '../precompile/Chain.js';
7
8
  import * as Channel from '../precompile/Channel.js';
8
9
  import * as Voucher from '../precompile/Voucher.js';
@@ -343,6 +344,22 @@ async function resolveAutoSwapCalls(autoSwap, parameters) {
343
344
  maxAmountIn: autoSwap.maxAmountIn,
344
345
  }));
345
346
  }
347
+ /**
348
+ * Throws an error that links to the MACH onramp when a MACH channel deposit exceeds the
349
+ * account's MACH balance, rather than signing a transaction that can only revert.
350
+ */
351
+ async function assertMachineTokenDeposit(autoSwap, parameters) {
352
+ const { account, amount, chainId, client, token } = parameters;
353
+ if (autoSwap || !MachineTokenCharge.isMachineToken({ chainId, currency: token }))
354
+ return;
355
+ const error = await MachineTokenCharge.getInsufficientBalanceError(client, {
356
+ account,
357
+ amount,
358
+ chainId,
359
+ });
360
+ if (error)
361
+ throw error;
362
+ }
346
363
  async function open(plan, sink, autoSwap) {
347
364
  const { account, resolved } = plan;
348
365
  const deposit = resolveOpeningDeposit({
@@ -351,6 +368,13 @@ async function open(plan, sink, autoSwap) {
351
368
  requestAmount: resolved.amount,
352
369
  suggestedDepositRaw: resolved.suggestedDepositRaw,
353
370
  });
371
+ await assertMachineTokenDeposit(autoSwap, {
372
+ account: account.address,
373
+ amount: deposit,
374
+ chainId: resolved.chainId,
375
+ client: resolved.client,
376
+ token: resolved.token,
377
+ });
354
378
  const payload = await createOpenPayload(resolved.client, account, {
355
379
  chainId: resolved.chainId,
356
380
  deposit,
@@ -500,6 +524,13 @@ async function manualTopUp(parameters, autoSwap) {
500
524
  additionalDeposit: additionalDeposit.toString(),
501
525
  };
502
526
  }
527
+ await assertMachineTokenDeposit(autoSwap, {
528
+ account: account.address,
529
+ amount: additionalDeposit,
530
+ chainId: resolved.chainId,
531
+ client: resolved.client,
532
+ token: resolved.token,
533
+ });
503
534
  return createTopUpPayload(resolved.client, account, descriptor, additionalDeposit, resolved.chainId, resolved.feePayer, resolved.escrow, await resolveAutoSwapCalls(autoSwap, {
504
535
  account: account.address,
505
536
  amountOut: additionalDeposit,
@@ -1,4 +1,5 @@
1
1
  import { type Address } from 'viem';
2
+ import * as Currency from '../../../Currency.js';
2
3
  import * as Method from '../../../Method.js';
3
4
  import * as Account from '../../../viem/Account.js';
4
5
  import * as Client from '../../../viem/Client.js';
@@ -145,19 +146,24 @@ export declare namespace session {
145
146
  */
146
147
  channelStore?: ChannelStore | undefined;
147
148
  /**
148
- * Allowlist of TIP-20 currency addresses this client will pay sessions in, compared
149
- * case-insensitively. Offers in other currencies are skipped during selection and
150
- * rejected before signing; an empty list rejects all. Required with `maxAmount` or
151
- * `maxAtomicAmount`, which are denominated in the challenge currency.
149
+ * Allowlist of currencies this client will pay sessions in: TIP-20 addresses, compared
150
+ * case-insensitively, or `viem/tokens` tokens, matched on the challenge's chain. Offers
151
+ * in other currencies are skipped during selection and rejected before signing; an empty
152
+ * list rejects all. Required with `maxAmount` or `maxAtomicAmount`, which are
153
+ * denominated in the challenge currency.
152
154
  */
153
- currencies?: readonly Address[] | undefined;
155
+ currencies?: readonly Currency.Currency[] | undefined;
154
156
  /**
155
157
  * Allowlist of session recipients (the channel payee), compared case-insensitively. Offers
156
158
  * to other recipients, or without one, are skipped during selection and rejected before
157
159
  * signing, as for charge. Explicit closes are exempt.
158
160
  */
159
161
  expectedRecipients?: readonly Address[] | undefined;
160
- /** Token decimals for parsing human-readable amounts (default: 6). `maxAmount` requires it explicitly. */
162
+ /**
163
+ * Decimals of address `currencies` (default: 6), used to parse human-readable amounts.
164
+ * Tokens carry their own: `maxDeposit` and `topUpAmount` use the decimals of the currency
165
+ * each challenge matched. `maxAmount` requires decimals for every address currency.
166
+ */
161
167
  decimals?: number | undefined;
162
168
  /** Exact TIP20EscrowChannel address pin. Takes precedence over `allowCustomEscrow`. */
163
169
  escrow?: Address | undefined;
@@ -4,6 +4,7 @@ import * as MethodChallenge from '../../../client/internal/MethodChallenge.js';
4
4
  import * as MethodResponse from '../../../client/internal/MethodResponse.js';
5
5
  import * as Constants from '../../../Constants.js';
6
6
  import * as Credential from '../../../Credential.js';
7
+ import * as Currency from '../../../Currency.js';
7
8
  import * as AcceptPayment from '../../../internal/AcceptPayment.js';
8
9
  import * as Method from '../../../Method.js';
9
10
  import * as Account from '../../../viem/Account.js';
@@ -72,16 +73,21 @@ function acknowledgesOpen(outcome, challenge, opened) {
72
73
  }
73
74
  /** Validates and parses the client's session spending options once, at construction. */
74
75
  function resolveSpendingPolicy(parameters) {
75
- const { currencies, decimals, expectedRecipients, maxAmount, maxAtomicAmount } = parameters;
76
+ const { allowedChainIds, currencies, decimals, expectedRecipients, maxAmount, maxAtomicAmount } = parameters;
76
77
  // Caps are denominated in the challenge currency, so they require a currency pin.
77
78
  if ((maxAmount !== undefined || maxAtomicAmount !== undefined) && currencies === undefined)
78
79
  throw new Error('Tempo session maxAmount and maxAtomicAmount require currencies.');
80
+ // Fail at construction for any accepted currency whose decimals cannot parse `maxAmount`.
81
+ for (const currency of currencies ?? [])
82
+ parseMaxAmount(maxAmount, typeof currency === 'string' ? decimals : currency.decimals);
79
83
  return {
80
- currencies: currencies?.map((currency) => currency.toLowerCase()),
84
+ chainId: allowedChainIds?.length === 1 ? allowedChainIds[0] : undefined,
85
+ currencies,
86
+ decimals,
81
87
  expectedRecipients: expectedRecipients
82
88
  ? new Set(expectedRecipients.map((recipient) => recipient.toLowerCase()))
83
89
  : undefined,
84
- maxAmount: parseMaxAmount(maxAmount, decimals),
90
+ maxAmount,
85
91
  maxAtomicAmount: maxAtomicAmount === undefined ? undefined : BigInt(maxAtomicAmount),
86
92
  };
87
93
  }
@@ -100,8 +106,19 @@ function parseMaxAmount(maxAmount, decimals) {
100
106
  * Rejects a session challenge whose currency, recipient or per-unit amount violates the client
101
107
  * policy. Runs during challenge selection, in the automatic top-up hook, and before any signing work.
102
108
  */
103
- function assertSpendingPolicy(policy, request) {
104
- if (policy.currencies && !policy.currencies.includes(request.currency.toLowerCase()))
109
+ function assertSpendingPolicy(policy, request,
110
+ /** Chain the client signs on, once resolved, for a challenge that names none. */
111
+ signingChainId) {
112
+ // Tokens match on the chain the client signs on: the challenge's, else the pinned or resolved
113
+ // one. Only selection, before a client is resolved, may match a token on any chain it lists,
114
+ // and `createCredential` checks the currency again on the resolved chain before signing.
115
+ const currency = policy.currencies
116
+ ? Currency.find(policy.currencies, request.currency, {
117
+ chainId: request.methodDetails?.chainId ?? signingChainId ?? policy.chainId,
118
+ decimals: policy.decimals,
119
+ })
120
+ : undefined;
121
+ if (policy.currencies && !currency)
105
122
  throw new Error(`Tempo session currency is not allowed: ${request.currency}.`);
106
123
  // The recipient is the channel payee, so it must be one the client expects, as for charge.
107
124
  if (policy.expectedRecipients &&
@@ -110,7 +127,8 @@ function assertSpendingPolicy(policy, request) {
110
127
  const amount = BigInt(request.amount);
111
128
  if (policy.maxAtomicAmount !== undefined && amount > policy.maxAtomicAmount)
112
129
  throw new Error('Tempo session amount exceeds maxAtomicAmount.');
113
- if (policy.maxAmount !== undefined && amount > policy.maxAmount)
130
+ if (policy.maxAmount !== undefined &&
131
+ amount > parseMaxAmount(policy.maxAmount, currency?.decimals))
114
132
  throw new Error('Tempo session amount exceeds maxAmount.');
115
133
  }
116
134
  /** Returns whether a session challenge satisfies the client policy. */
@@ -137,7 +155,7 @@ function isExplicitClose(context) {
137
155
  * channel descriptor).
138
156
  */
139
157
  export function session(parameters = {}) {
140
- const { account, allowCustomEscrow = false, autoSwap: autoSwapParameter, channelStore, decimals = defaults.decimals, escrow: escrowOverride, allowedChainIds, getClient: getClientParameter, maxDeposit: maxDepositParameter, topUpAmount: topUpAmountParameter, onChannelUpdate, resolveAccount, } = parameters;
158
+ const { account, allowCustomEscrow = false, autoSwap: autoSwapParameter, channelStore, decimals: decimalsParameter, escrow: escrowOverride, allowedChainIds, getClient: getClientParameter, maxDeposit: maxDepositParameter, topUpAmount: topUpAmountParameter, onChannelUpdate, resolveAccount, } = parameters;
141
159
  const policy = resolveSpendingPolicy(parameters);
142
160
  const getClient = Client.getResolver({
143
161
  chain: tempo_chain,
@@ -145,8 +163,29 @@ export function session(parameters = {}) {
145
163
  rpcUrl: defaults.rpcUrl,
146
164
  });
147
165
  const getAccount = Account.getResolver({ account });
148
- const maxDeposit = maxDepositParameter !== undefined ? parseUnits(maxDepositParameter, decimals) : undefined;
149
- const topUpAmount = topUpAmountParameter !== undefined ? parseUnits(topUpAmountParameter, decimals) : undefined;
166
+ /**
167
+ * Parses human-readable amounts in the decimals of the currency a challenge matched: a token's
168
+ * own, else the configured `decimals`, else 6. A token on another chain never sets the scale.
169
+ */
170
+ const resolveAmounts = (request, chainId) => {
171
+ const matched = policy.currencies
172
+ ? Currency.find(policy.currencies, request.currency, {
173
+ chainId: request.methodDetails?.chainId ?? chainId ?? policy.chainId,
174
+ decimals: decimalsParameter,
175
+ })
176
+ : undefined;
177
+ const decimals = matched?.decimals ?? decimalsParameter ?? defaults.decimals;
178
+ return {
179
+ decimals,
180
+ maxDeposit: maxDepositParameter !== undefined ? parseUnits(maxDepositParameter, decimals) : undefined,
181
+ topUpAmount: topUpAmountParameter !== undefined ? parseUnits(topUpAmountParameter, decimals) : undefined,
182
+ };
183
+ };
184
+ // Reject malformed amounts at construction rather than at the first challenge.
185
+ if (maxDepositParameter !== undefined)
186
+ parseUnits(maxDepositParameter, defaults.decimals);
187
+ if (topUpAmountParameter !== undefined)
188
+ parseUnits(topUpAmountParameter, defaults.decimals);
150
189
  const configuredOrigin = parameters.origin === undefined ? undefined : new URL(parameters.origin);
151
190
  if (configuredOrigin && !['http:', 'https:'].includes(configuredOrigin.protocol))
152
191
  throw new Error('Session origins require HTTP or HTTPS');
@@ -167,14 +206,17 @@ export function session(parameters = {}) {
167
206
  },
168
207
  })) ?? defaultAccount);
169
208
  };
170
- const resolveCredentialPlan = async (resolved, context, entry) => planCredential({
171
- account: await resolveCredentialAccount(resolved, context, entry),
172
- entry,
173
- context,
174
- decimals,
175
- maxDeposit,
176
- resolved,
177
- });
209
+ const resolveCredentialPlan = async (resolved, context, entry) => {
210
+ const { decimals, maxDeposit } = resolveAmounts(resolved.challenge.request, resolved.chainId);
211
+ return planCredential({
212
+ account: await resolveCredentialAccount(resolved, context, entry),
213
+ entry,
214
+ context,
215
+ decimals,
216
+ maxDeposit,
217
+ resolved,
218
+ });
219
+ };
178
220
  const method = Method.toClient(Methods.session, {
179
221
  // Skip offers that violate client policy so an acceptable offer can be chosen. An explicit
180
222
  // close, when the caller supplies it before selection, stays available for any offer. Flows
@@ -196,6 +238,9 @@ export function session(parameters = {}) {
196
238
  allowedChainIds,
197
239
  getClient,
198
240
  });
241
+ // A challenge without a chain ID was checked without one: check its currency on this chain.
242
+ if (context?.action !== 'close' && challenge.request.methodDetails?.chainId === undefined)
243
+ assertSpendingPolicy(policy, challenge.request, resolved.chainId);
199
244
  const attempt = MethodResponse.getAttempt(parameters);
200
245
  const origin = MethodResponse.getOrigin(parameters) ?? configuredOrigin?.origin;
201
246
  if (origin !== undefined &&
@@ -295,6 +340,7 @@ export function session(parameters = {}) {
295
340
  if (channel.uncertainTopUp)
296
341
  throw new Error('Session funding outcome is unknown; reconcile the pending payment before another top-up.');
297
342
  const knownDeposit = channel.deposit > deposit ? channel.deposit : deposit;
343
+ const { maxDeposit, topUpAmount } = resolveAmounts(challenge.request, channel.chainId);
298
344
  const additionalDeposit = resolveAutomaticTopUp({
299
345
  deposit: knownDeposit,
300
346
  maxDeposit,
@@ -401,7 +447,7 @@ export function session(parameters = {}) {
401
447
  })).key;
402
448
  let channel = await store.get(channelKey);
403
449
  const driver = {
404
- assertVoucherWithinLocalLimit: (cumulativeAmount) => assertWithinMaxDeposit(cumulativeAmount, maxDeposit),
450
+ assertVoucherWithinLocalLimit: (cumulativeAmount) => assertWithinMaxDeposit(cumulativeAmount, resolveAmounts(challenge.request, channel?.chainId).maxDeposit),
405
451
  createSessionCredential: (challenge, context) => createSessionCredential(challenge, context, input),
406
452
  fetch,
407
453
  getChannel: () => channel ?? null,
@@ -45,7 +45,7 @@ export type OnChainChannelState = {
45
45
  closeRequestedAt: number | bigint;
46
46
  };
47
47
  /** Persisted fields that mirror authoritative on-chain channel state. */
48
- export type ActiveOnChainStateFields = Pick<State, 'closeRequestedAt' | 'deposit' | 'settledOnChain'>;
48
+ export type ActiveOnChainStateFields = Pick<State, 'closeRequestedAt' | 'onChainCloseRequestedAt' | 'deposit' | 'settledOnChain'>;
49
49
  /** Parameters for selecting the persisted highest accepted voucher. */
50
50
  export type HighestVoucherParameters = {
51
51
  /** Channel ID used when constructing a new voucher record. */
@@ -203,6 +203,8 @@ export type VerifyAndAcceptVoucherParameters = {
203
203
  voucher: SignedVoucher;
204
204
  /** Request price to charge in the same store update that accepts the voucher. */
205
205
  chargeAmount?: bigint | undefined;
206
+ /** Durable delivery key for an SSE request charged before its first item. */
207
+ prepaidRefundKey?: string | undefined;
206
208
  /** Called with the stored channel after `chargeAmount` was charged. */
207
209
  onCharged?: ((channel: State) => void) | undefined;
208
210
  };
@@ -301,11 +303,15 @@ export interface BaseState {
301
303
  }> | undefined;
302
304
  /** First block at which the close supervisor read this channel open on-chain. */
303
305
  closeSupervisedFromBlock?: bigint | undefined;
306
+ /** Next close-event log range to retry after an interrupted search. */
307
+ closeSearchFromBlock?: bigint | undefined;
304
308
  /**
305
309
  * The `closeRequestedAt` this server wrote as its own cooperative-close marker before
306
310
  * broadcasting a close, to tell that marker from a payer's close request on-chain.
307
311
  */
308
312
  pendingCloseAt?: bigint | undefined;
313
+ /** Observed payer close timestamp, separate from a server marker that may hide it. */
314
+ onChainCloseRequestedAt?: bigint | undefined;
309
315
  }
310
316
  /** Expiring ownership claim for one server-scheduled settlement attempt. */
311
317
  export type ScheduledSettlementLease = {
@@ -398,6 +404,8 @@ export declare function resolveCloseCaptureAmount(parameters: ResolveCloseCaptur
398
404
  export declare const pendingCloseValiditySeconds = 25;
399
405
  /** Extra seconds allowed for clock differences between the server and the chain. */
400
406
  export declare const pendingCloseClockSkewSeconds = 30;
407
+ /** Whether a server close transaction may still land and capture spend. */
408
+ export declare function hasPendingClose(state: State, now?: number): boolean;
401
409
  /** Clears a server pending-close marker whose close transaction expired without closing the channel. */
402
410
  export declare function reconcileExpiredPendingClose(parameters: {
403
411
  current: State | null;
@@ -429,10 +437,21 @@ export declare function assertVoucherAmounts(parameters: {
429
437
  export declare function planVoucherAcceptance(parameters: {
430
438
  accepted: State;
431
439
  chargeAmount?: bigint | undefined;
440
+ /** Durable delivery key for an SSE request charged before its first item. */
441
+ prepaidRefundKey?: string | undefined;
432
442
  }): {
433
443
  channel: State;
434
444
  charged: boolean;
435
445
  };
446
+ /**
447
+ * Reports a channel balance that can't cover a charge. On a MACH channel on Tempo mainnet, the
448
+ * error also links to the MACH onramp, where the payer can get MACH to top up the channel.
449
+ */
450
+ export declare function insufficientBalance(channel: {
451
+ chainId: number | undefined;
452
+ payer?: Address | undefined;
453
+ token: Address;
454
+ }, reason: string): InsufficientBalanceError;
436
455
  /** Reports a request charge that the channel's available balance could not cover. */
437
456
  export declare function insufficientBalanceForCharge(channel: State, chargeAmount: bigint): InsufficientBalanceError;
438
457
  /** Verifies a cumulative voucher and returns a session receipt after store reconciliation. */
@@ -497,6 +516,8 @@ export declare function fromStore(store: Store.Store | Store.AtomicStore): Chann
497
516
  export declare const defaultIdempotencyRetention: number;
498
517
  /** Options for charging a channel at most once per key. */
499
518
  export type ChargeOptions = {
519
+ /** Durable delivery key for an SSE request charged before its first item. */
520
+ prepaidRefundKey?: string | undefined;
500
521
  /**
501
522
  * Key of the operation being charged. A retry with the same key and amount returns the recorded
502
523
  * charge without charging again; the same key with a different amount throws
@@ -1,4 +1,5 @@
1
1
  import { AmountExceedsDepositError, ChannelClosedError, ChannelNotFoundError, DeltaTooSmallError, InsufficientBalanceError, InvalidSignatureError, VerificationFailedError, } from '../../../Errors.js';
2
+ import * as MachineTokenCharge from '../../internal/machine-token-charge.js';
2
3
  import { createSessionReceipt } from '../precompile/Protocol.js';
3
4
  import { uint96 } from '../precompile/Protocol.js';
4
5
  import * as Voucher from '../precompile/Voucher.js';
@@ -19,6 +20,11 @@ export function keepGreaterTimestamp(current, next) {
19
20
  export function mergeActiveOnChainState(current, state) {
20
21
  return {
21
22
  closeRequestedAt: keepGreaterTimestamp(current?.closeRequestedAt ?? 0n, state.closeRequestedAt),
23
+ ...(BigInt(state.closeRequestedAt) !== 0n
24
+ ? {
25
+ onChainCloseRequestedAt: keepGreater(current?.onChainCloseRequestedAt ?? 0n, BigInt(state.closeRequestedAt)),
26
+ }
27
+ : {}),
22
28
  deposit: keepGreater(current?.deposit ?? 0n, state.deposit),
23
29
  settledOnChain: keepGreater(current?.settledOnChain ?? 0n, state.settled),
24
30
  };
@@ -227,6 +233,16 @@ export function resolveCloseCaptureAmount(parameters) {
227
233
  export const pendingCloseValiditySeconds = 25;
228
234
  /** Extra seconds allowed for clock differences between the server and the chain. */
229
235
  export const pendingCloseClockSkewSeconds = 30;
236
+ /** Whether a server close transaction may still land and capture spend. */
237
+ export function hasPendingClose(state, now = Date.now()) {
238
+ if (state.pendingCloseAt === undefined || state.finalized)
239
+ return false;
240
+ const requestedAt = BigInt(state.closeRequestedAt ?? 0n);
241
+ if (requestedAt === 0n || requestedAt !== BigInt(state.pendingCloseAt))
242
+ return false;
243
+ return (Math.floor(now / 1000) <=
244
+ Number(state.pendingCloseAt) + pendingCloseValiditySeconds + pendingCloseClockSkewSeconds);
245
+ }
230
246
  /** Clears a server pending-close marker whose close transaction expired without closing the channel. */
231
247
  export function reconcileExpiredPendingClose(parameters) {
232
248
  const { current, now, state } = parameters;
@@ -238,7 +254,12 @@ export function reconcileExpiredPendingClose(parameters) {
238
254
  const expiresAt = current.closeRequestedAt + BigInt(pendingCloseValiditySeconds);
239
255
  if (BigInt(now) <= expiresAt + BigInt(pendingCloseClockSkewSeconds))
240
256
  return current;
241
- return { ...current, closeRequestedAt: 0n, pendingCloseAt: undefined };
257
+ return {
258
+ ...current,
259
+ closeRequestedAt: 0n,
260
+ pendingCloseAt: undefined,
261
+ onChainCloseRequestedAt: undefined,
262
+ };
242
263
  }
243
264
  /** Marks local channel state as pending close and returns the bounded capture amount. */
244
265
  export function markPendingClose(parameters) {
@@ -354,16 +375,27 @@ export function planVoucherAcceptance(parameters) {
354
375
  const { accepted, chargeAmount } = parameters;
355
376
  if (chargeAmount === undefined)
356
377
  return { channel: accepted, charged: false };
357
- const deduction = planDeduction(accepted, chargeAmount);
378
+ const deduction = planDeduction(accepted, chargeAmount, parameters.prepaidRefundKey);
358
379
  if (deduction.op !== 'set')
359
380
  return { channel: accepted, charged: false };
360
381
  return { channel: deduction.value, charged: true };
361
382
  }
383
+ /**
384
+ * Reports a channel balance that can't cover a charge. On a MACH channel on Tempo mainnet, the
385
+ * error also links to the MACH onramp, where the payer can get MACH to top up the channel.
386
+ */
387
+ export function insufficientBalance(channel, reason) {
388
+ const fundingUrl = MachineTokenCharge.isMachineToken({
389
+ chainId: channel.chainId,
390
+ currency: channel.token,
391
+ })
392
+ ? MachineTokenCharge.fundingUrl({ address: channel.payer, chainId: channel.chainId })
393
+ : undefined;
394
+ return new InsufficientBalanceError({ fundingUrl, reason });
395
+ }
362
396
  /** Reports a request charge that the channel's available balance could not cover. */
363
397
  export function insufficientBalanceForCharge(channel, chargeAmount) {
364
- return new InsufficientBalanceError({
365
- reason: `requested ${chargeAmount}, available ${channel.highestVoucherAmount - channel.spent - reservedStreamAmount(channel)}`,
366
- });
398
+ return insufficientBalance(channel, `requested ${chargeAmount}, available ${channel.highestVoucherAmount - channel.spent - reservedStreamAmount(channel)}`);
367
399
  }
368
400
  /** Verifies a cumulative voucher and returns a session receipt after store reconciliation. */
369
401
  export async function verifyAndAcceptVoucher(parameters) {
@@ -388,6 +420,7 @@ export async function verifyAndAcceptVoucher(parameters) {
388
420
  const acceptance = planVoucherAcceptance({
389
421
  accepted: acceptVoucherStateUpdate({ channelState, current, verifiedAt, voucher }),
390
422
  chargeAmount,
423
+ prepaidRefundKey: parameters.prepaidRefundKey,
391
424
  });
392
425
  charged = acceptance.charged;
393
426
  return acceptance.channel;
@@ -608,6 +641,8 @@ function liveMarkers(state, now) {
608
641
  */
609
642
  export async function deductFromChannel(store, channelId, amount, options) {
610
643
  const idempotencyKey = options?.idempotencyKey;
644
+ if (idempotencyKey !== undefined && options?.prepaidRefundKey !== undefined)
645
+ throw new Error('Prepaid deliveries cannot use a replayable charge key');
611
646
  if (idempotencyKey !== undefined) {
612
647
  assertIdempotencyOptions(options);
613
648
  const now = Date.now();
@@ -620,14 +655,14 @@ export async function deductFromChannel(store, channelId, amount, options) {
620
655
  return result;
621
656
  }
622
657
  if (store.updateChannelResult) {
623
- const result = await store.updateChannelResult(channelId, (current) => planDeduction(current, amount));
658
+ const result = await store.updateChannelResult(channelId, (current) => planDeduction(current, amount, options?.prepaidRefundKey));
624
659
  if (!result)
625
660
  throw new Error('channel not found');
626
661
  return result;
627
662
  }
628
663
  let result = null;
629
664
  const channel = await store.updateChannel(channelId, (current) => {
630
- const change = planDeduction(current, amount);
665
+ const change = planDeduction(current, amount, options?.prepaidRefundKey);
631
666
  result = change.result;
632
667
  if (change.op === 'set')
633
668
  return change.value;
@@ -657,7 +692,7 @@ function planKeyedDeduction(current, amount, idempotencyKey, expiresAt, now) {
657
692
  };
658
693
  return { op: 'set', value: channel, result: { ok: true, channel } };
659
694
  }
660
- function planDeduction(current, amount) {
695
+ function planDeduction(current, amount, prepaidRefundKey) {
661
696
  if (!current)
662
697
  return { op: 'noop', result: null };
663
698
  if (current.finalized)
@@ -667,6 +702,21 @@ function planDeduction(current, amount) {
667
702
  if (current.highestVoucherAmount - current.spent - reservedStreamAmount(current) < amount)
668
703
  return { op: 'noop', result: { ok: false, channel: current } };
669
704
  const next = { ...current, spent: current.spent + amount, units: current.units + 1 };
705
+ if (prepaidRefundKey && amount > 0n) {
706
+ const liveMarkers = Object.values(current.idempotencyMarkers ?? {}).filter((marker) => marker.expiresAt > Date.now()).length;
707
+ if (current.prepaidRefunds?.[prepaidRefundKey] ||
708
+ Object.keys(current.prepaidRefunds ?? {}).length + liveMarkers >= 128)
709
+ throw new Error('Prepaid delivery capacity reached; reconcile outstanding deliveries');
710
+ next.prepaidRefunds = {
711
+ ...current.prepaidRefunds,
712
+ [prepaidRefundKey]: {
713
+ amount: amount.toString(),
714
+ units: 1,
715
+ status: 'pending',
716
+ createdAt: Date.now(),
717
+ },
718
+ };
719
+ }
670
720
  return { op: 'set', value: next, result: { ok: true, channel: next } };
671
721
  }
672
722
  /**
@@ -15,7 +15,7 @@ export declare const defaultCloseSearchMarginBlocks = 2000n;
15
15
  export type CloseSupervisionOutcome =
16
16
  /** Open with no close request, or not yet open at the pinned block. */
17
17
  'open'
18
- /** Open, and settled because its spend crossed `settlementSchedule`. */
18
+ /** Open and settled, including reconciliation of an already completed settlement. */
19
19
  | 'settled'
20
20
  /** Close requested, with nothing above the settled amount to capture; the payer's withdrawal finalizes it. */
21
21
  | 'closing'
@@ -76,6 +76,10 @@ export type SuperviseClosesParameters = Pick<SettlementTransactionOptions, 'acco
76
76
  client: Chain.TransactionClient;
77
77
  /** Blocks searched before `previousBlock` for a channel no supervision has read open. @default 2_000n */
78
78
  closeSearchMarginBlocks?: bigint | undefined;
79
+ /** Closes open channels with unpaid spend but no settleable voucher, bounded by spend and deposit. @default false */
80
+ closeUnsettled?: boolean | undefined;
81
+ /** Existing settlement lease owned by this caller, when closing unsettled channels. */
82
+ settlementLeaseOwner?: string | undefined;
79
83
  /** Widest block range of one log query. @default 100_000n */
80
84
  logBlockRange?: bigint | undefined;
81
85
  /** Callback invoked when a payee close fails. Observer errors are ignored. */