mppx 0.21.3 → 0.22.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 (62) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/BodyDigest.d.ts +3 -3
  3. package/dist/BodyDigest.js +5 -3
  4. package/dist/Challenge.js +12 -2
  5. package/dist/Credential.js +9 -1
  6. package/dist/Errors.d.ts +62 -8
  7. package/dist/Errors.js +57 -6
  8. package/dist/Store.d.ts +7 -4
  9. package/dist/Store.js +18 -8
  10. package/dist/cli/cli.js +135 -135
  11. package/dist/cli/internal.js +1 -1
  12. package/dist/cli/plugins/index.js +12 -12
  13. package/dist/client/Budget.d.ts +49 -0
  14. package/dist/client/Budget.js +101 -0
  15. package/dist/client/Mppx.d.ts +8 -3
  16. package/dist/client/Mppx.js +55 -13
  17. package/dist/client/Spend.d.ts +134 -0
  18. package/dist/client/Spend.js +58 -0
  19. package/dist/client/core.d.ts +2 -0
  20. package/dist/client/core.js +2 -0
  21. package/dist/client/internal/Fetch.d.ts +23 -3
  22. package/dist/client/internal/Fetch.js +155 -37
  23. package/dist/client/internal/FundsMoved.d.ts +9 -0
  24. package/dist/client/internal/FundsMoved.js +18 -0
  25. package/dist/client/internal/SpendGate.d.ts +136 -0
  26. package/dist/client/internal/SpendGate.js +608 -0
  27. package/dist/client/internal/SpendHooks.d.ts +42 -0
  28. package/dist/client/internal/SpendHooks.js +36 -0
  29. package/dist/client/internal/protocols/Mcp.d.ts +9 -0
  30. package/dist/client/internal/protocols/Mcp.js +27 -0
  31. package/dist/client/internal/protocols/Mpp.js +20 -3
  32. package/dist/client/internal/protocols/Shared.js +29 -3
  33. package/dist/evm/client/Charge.js +20 -8
  34. package/dist/extensions/identity/erc8004/server/index.d.ts +7 -1
  35. package/dist/extensions/identity/erc8004/server/index.js +13 -1
  36. package/dist/extensions/identity/link/client/index.js +57 -5
  37. package/dist/identity/Client.d.ts +7 -3
  38. package/dist/identity/Client.js +178 -13
  39. package/dist/identity/Types.d.ts +2 -1
  40. package/dist/integrations/x402/Negotiator.js +4 -1
  41. package/dist/integrations/x402/Solana.d.ts +75 -0
  42. package/dist/integrations/x402/Solana.js +143 -0
  43. package/dist/internal/challengeMeta.d.ts +17 -2
  44. package/dist/internal/challengeMeta.js +35 -7
  45. package/dist/internal/version.d.ts +2 -2
  46. package/dist/internal/version.js +1 -1
  47. package/dist/mcp/client/McpClient.d.ts +6 -1
  48. package/dist/mcp/client/McpClient.js +48 -10
  49. package/dist/middlewares/express.d.ts +1 -1
  50. package/dist/server/Mppx.d.ts +12 -1
  51. package/dist/server/Mppx.js +58 -6
  52. package/dist/server/Request.d.ts +1 -1
  53. package/dist/server/Transport.js +46 -2
  54. package/dist/server/internal/host.js +5 -2
  55. package/dist/stripe/server/internal/html.gen.js +1 -1
  56. package/dist/tempo/client/Charge.js +81 -17
  57. package/dist/tempo/server/Charge.d.ts +7 -1
  58. package/dist/tempo/server/Charge.js +98 -12
  59. package/dist/tempo/server/internal/html.gen.js +1 -1
  60. package/dist/tempo/session/client/SessionManager.js +3 -0
  61. package/dist/x402/server/EvmCharge.js +3 -0
  62. package/package.json +1 -1
@@ -6,18 +6,24 @@ import { PaymentOutcomeUnknownError } from '../../Errors.js';
6
6
  import * as Expires from '../../Expires.js';
7
7
  import * as IdentityClient from '../../identity/Client.js';
8
8
  import * as AcceptPayment from '../../internal/AcceptPayment.js';
9
+ import * as Spend from '../Spend.js';
9
10
  import * as Transport from '../Transport.js';
10
11
  import * as MethodChallenge from './MethodChallenge.js';
11
12
  import * as MethodResponse from './MethodResponse.js';
12
13
  import * as PendingSettlement from './PendingSettlement.js';
13
14
  import * as ProofRealm from './ProofRealm.js';
15
+ import * as Mcp_protocol from './protocols/Mcp.js';
14
16
  import { adapterOwnsPayment } from './protocols/Mcp.js';
17
+ import * as SpendGate from './SpendGate.js';
18
+ import * as SpendHooks from './SpendHooks.js';
15
19
  // We tag wrappers with a global symbol so we can recognize wrappers created by mppx,
16
20
  // even across multiple module instances/bundles. This lets restore() avoid clobbering
17
21
  // an unrelated fetch installed by user code or another library.
18
22
  const MPPX_FETCH_WRAPPER = Symbol.for('mppx.fetch.wrapper');
19
23
  /** Identity runner of an mppx fetch wrapper, inherited when that wrapper is wrapped again. */
20
24
  const MPPX_FETCH_IDENTITY = Symbol.for('mppx.fetch.identity');
25
+ /** Spending options of an mppx fetch wrapper, kept when that wrapper is wrapped again. */
26
+ const MPPX_FETCH_SPEND = Symbol.for('mppx.fetch.spend');
21
27
  /** Per-request payment opt-out preserved by forwarding fetch layers. @internal */
22
28
  export const skipPayment = Symbol.for('mppx.fetch.skipPayment');
23
29
  /**
@@ -124,6 +130,9 @@ export function from(config) {
124
130
  const identity = config.identity ?? (config.fetch && identityOf(config.fetch));
125
131
  const events = config.eventDispatcher ?? createEventDispatcher();
126
132
  const resolvedAcceptPayment = acceptPayment ?? AcceptPayment.resolve(methods);
133
+ // Rewrapping an mppx fetch keeps its spending options, so its limits still apply.
134
+ const spendConfig = SpendGate.inherit(config, config.fetch && spendConfigOf(config.fetch));
135
+ const spender = SpendGate.from(spendConfig);
127
136
  // Always operate on the true underlying fetch to avoid wrapper-on-wrapper stacking,
128
137
  // which can duplicate retries and make restore semantics fragile.
129
138
  const baseFetch = unwrapFetch(fetch);
@@ -136,12 +145,24 @@ export function from(config) {
136
145
  const callerHeaders = getCallerHeaders(input, init?.headers);
137
146
  const hasExplicitAcceptPayment = callerHeaders.has(Constants.Headers.acceptPayment);
138
147
  const paymentPreferences = resolvePaymentPreferences(callerHeaders, resolvedAcceptPayment);
139
- const capturedBody = captureRequestBody(input, init, callerHeaders);
148
+ const signal = resolveRequestSignal(input, init);
149
+ // Under spending options the body is read before sending (below), so an abort must stop it.
150
+ const capturedBody = captureRequestBody(input, init, callerHeaders, spender.prepare ? signal : undefined);
140
151
  const initialRequest = prepareInitialRequest(input, init, callerHeaders, paymentPreferences.header, hasExplicitAcceptPayment, acceptPaymentPolicy);
152
+ // `McpClient.wrap` pays the tool calls it tags itself, outside this fetch, so this fetch's
153
+ // spending options would not bound them: refuse to send one instead.
154
+ if (spender.prepare) {
155
+ const body = await capturedBody;
156
+ // A canceled request is never sent, even when its body was cut short to stop reading it.
157
+ signal?.throwIfAborted();
158
+ if (adapterOwnsPayment(withCapturedBody(initialRequest.init, body)))
159
+ throw new TypeError('This fetch has spending options (maxPayment, authorize or funders), but McpClient.wrap pays MCP tool calls itself. Set them on McpClient.wrap and give its transport a fetch without them.');
160
+ }
141
161
  const first = await send(cloneRequestInput(initialRequest.input), initialRequest.init);
142
162
  let response = first.response;
143
- // Retry headers from the unpaid attempt (such as an attestation) go on the paid attempt too.
144
- const identityHeaders = first.headers;
163
+ // Retry headers from the unpaid attempt (such as an attestation) go on the paid attempt too,
164
+ // replaced by those a paid attempt was resent with, so a later paid attempt carries them.
165
+ let identityHeaders = first.headers;
145
166
  const transportRequest = withCapturedBody(initialRequest.init, await capturedBody);
146
167
  if (init?.[skipPayment])
147
168
  return response;
@@ -152,6 +173,9 @@ export function from(config) {
152
173
  // Only extract context for payment handling after confirming 402.
153
174
  const context = init?.context;
154
175
  const { context: _, orderChallenges: requestOrderChallenges, ...fetchInit } = (transportRequest ?? {});
176
+ // Whether the first request already carried a Payment credential the caller attached.
177
+ const initialCredentialSent = hasPaymentCredential(callerHeaders) ||
178
+ Mcp_protocol.hasCredential(transportRequest);
155
179
  let challenge;
156
180
  let challenges;
157
181
  let mi;
@@ -161,6 +185,14 @@ export function from(config) {
161
185
  try {
162
186
  for (let retry = 0; retry < maxPaymentRetries; retry++) {
163
187
  challenges = await transport.getChallenges(response, transportRequest);
188
+ // invalid-challenge answering a sent credential can mean it was already settled
189
+ // (a replay): paying the fresh Challenge would pay twice, so the 402 is final. That
190
+ // holds for a credential the caller attached to the first request too.
191
+ if ((retry > 0 || initialCredentialSent) &&
192
+ (await isInvalidChallengeResponse(response, transportRequest))) {
193
+ await settleAttempt(preparedCredential, { challenges, response, status: 'rejected' });
194
+ return response;
195
+ }
164
196
  const candidates = AcceptPayment.selectChallengeCandidates(challenges, methods, paymentPreferences.entries, context);
165
197
  const orderedCandidates = await resolveChallengeOrder(candidates, requestOrderChallenges ??
166
198
  orderChallenges);
@@ -198,8 +230,12 @@ export function from(config) {
198
230
  canReusePrevious = sameAttempt && !settled;
199
231
  }
200
232
  preparedCredential = canReusePrevious ? previousCredential : undefined;
233
+ // This round's payment, and the credential its spending checks already cover.
234
+ const spend = SpendGate.payment(spender, selectedChallenge, resolveRequestSignal(input, init), selected.method);
235
+ let checkedCredential;
201
236
  const createCredential = memoizeCreateCredential(async (overrideContext) => {
202
237
  if (overrideContext === undefined && canReusePrevious && previousCredential) {
238
+ checkedCredential = previousCredential.promise;
203
239
  return previousCredential.promise;
204
240
  }
205
241
  if (canReusePrevious && previousCredential) {
@@ -209,9 +245,13 @@ export function from(config) {
209
245
  // A new payment must not start for a request the caller already aborted.
210
246
  resolveRequestSignal(input, init)?.throwIfAborted();
211
247
  const credentialContext = overrideContext ?? context;
212
- if (!MethodChallenge.has(selected.method))
248
+ if (!MethodChallenge.has(selected.method)) {
249
+ // Spending limits, authorization and funding run before any signing work.
250
+ checkedCredential = spend.track((constraints) =>
213
251
  // A Zone withdrawal still settling is resumed for this challenge, not paid again.
214
- return PendingSettlement.resume(() => resolveCredential(selectedChallenge, selected.method, credentialContext, requestOrigin(paymentInput)), { attempts: maxPaymentRetries, signal: resolveRequestSignal(input, init) });
252
+ PendingSettlement.resume(() => resolveCredential(selectedChallenge, selected.method, credentialContext, requestOrigin(paymentInput), constraints), { attempts: maxPaymentRetries, signal: resolveRequestSignal(input, init) }));
253
+ return checkedCredential;
254
+ }
215
255
  const attempt = {
216
256
  origin: resolveRequestUrl(paymentInput).origin,
217
257
  prepare: () => MethodChallenge.handle(selected.method, {
@@ -227,9 +267,11 @@ export function from(config) {
227
267
  signal: resolveRequestSignal(input, init),
228
268
  }),
229
269
  };
230
- const promise = attempt
270
+ // Spending limits, authorization and funding run before any signing work.
271
+ const promise = spend.track((constraints) => attempt
231
272
  .prepare()
232
- .then(() => resolveCredential(selectedChallenge, selected.method, credentialContext, attempt));
273
+ .then(() => resolveCredential(selectedChallenge, selected.method, credentialContext, attempt, constraints)));
274
+ checkedCredential = promise;
233
275
  preparedCredential = {
234
276
  context: credentialContext,
235
277
  attempt,
@@ -239,29 +281,57 @@ export function from(config) {
239
281
  };
240
282
  return promise;
241
283
  });
242
- const eventCredential = await events.emit('challenge.received', createChallengeReceivedPayload({
243
- challenge: selectedChallenge,
244
- challenges,
245
- createCredential,
246
- init,
247
- input,
248
- method: selected.method,
249
- response,
250
- }));
251
- const onChallengeCredential = eventCredential ??
252
- (onChallenge
253
- ? await onChallenge(challenge, {
254
- createCredential,
255
- })
256
- : undefined);
257
- const credential = onChallengeCredential ?? (await createCredential());
258
- const prepared = preparedCredential;
259
- if (prepared && (await prepared.promise.catch(() => undefined)) !== credential) {
260
- await settleAttempt(prepared, { status: 'rejected' });
261
- preparedCredential = undefined;
284
+ let credential;
285
+ let prepared;
286
+ // The offer a credential mppx did not create pays, once spending checks bound it.
287
+ let paidOffer;
288
+ // Whether the credential is the one mppx created for the selected offer.
289
+ let ownCredential = false;
290
+ try {
291
+ const eventCredential = await events.emit('challenge.received', createChallengeReceivedPayload({
292
+ challenge: selectedChallenge,
293
+ challenges,
294
+ createCredential,
295
+ init,
296
+ input,
297
+ method: selected.method,
298
+ response,
299
+ }));
300
+ const onChallengeCredential = eventCredential ??
301
+ (onChallenge
302
+ ? await onChallenge(challenge, {
303
+ createCredential,
304
+ })
305
+ : undefined);
306
+ // `onChallenge` declined the payment: pay nothing and hand back the 402.
307
+ if (onChallengeCredential === false) {
308
+ await spend.release();
309
+ await settleAttempt(preparedCredential, { challenges, response, status: 'rejected' });
310
+ preparedCredential = undefined;
311
+ return response;
312
+ }
313
+ credential = onChallengeCredential ?? (await createCredential());
314
+ prepared = preparedCredential;
315
+ if (prepared && (await prepared.promise.catch(() => undefined)) !== credential) {
316
+ await settleAttempt(prepared, { status: 'rejected' });
317
+ preparedCredential = undefined;
318
+ }
319
+ validateCredentialHeaderValue(credential);
320
+ // A credential an event handler or `onChallenge` made itself is checked against the
321
+ // offer it pays before it is sent. For the selected offer it takes the reservation
322
+ // already prepared, so funders run once.
323
+ ownCredential =
324
+ checkedCredential !== undefined &&
325
+ (await checkedCredential.catch(() => undefined)) === credential;
326
+ if (!ownCredential)
327
+ paidOffer = await spend.commitReplacement(credential, challenges);
328
+ }
329
+ catch (error) {
330
+ // A no-op once a credential committed it.
331
+ await spend.release();
332
+ throw error;
262
333
  }
263
334
  const effectiveContext = preparedCredential ? preparedCredential.context : context;
264
- validateCredentialHeaderValue(credential);
265
335
  // Identity proofs bind to the Challenge the credential pays, which can be an earlier one
266
336
  // (a resumed Zone withdrawal) rather than the one just selected.
267
337
  const paidChallenge = credentialChallenge(credential, selectedChallenge);
@@ -281,11 +351,13 @@ export function from(config) {
281
351
  });
282
352
  try {
283
353
  ;
284
- ({ response } = await send(paymentInput, {
354
+ ({ response, headers: identityHeaders } = await send(paymentInput, {
285
355
  ...transport.setCredential({
286
356
  ...fetchInit,
287
357
  headers: initialRequest.headers,
288
- }, credential, { challenge: selectedChallenge }),
358
+ }, credential,
359
+ // Attached in the protocol of the offer it pays, such as an x402 payload.
360
+ { challenge: paidOffer ?? selectedChallenge }),
289
361
  // Runtimes do not strip custom payment headers on cross-origin redirects.
290
362
  redirect: 'manual',
291
363
  }, { challenge: paidChallenge, headers: identityHeaders }));
@@ -308,15 +380,22 @@ export function from(config) {
308
380
  preparedCredential = undefined;
309
381
  }
310
382
  // Cloning an unobserved stream would tee and buffer it indefinitely.
311
- if (response.ok && hasEventObservers(events, 'payment.response'))
383
+ if (response.ok && hasEventObservers(events, 'payment.response')) {
384
+ // A handler's credential can pay another offer than the selected one: report the terms
385
+ // of the offer it pays, and none when it cannot be bound to exactly one.
386
+ const reportedOffer = ownCredential
387
+ ? selectedChallenge
388
+ : (paidOffer ?? SpendGate.replacedChallenge(credential, challenges));
312
389
  await events.emit('payment.response', createPaymentResponsePayload({
313
390
  challenge: selectedChallenge,
314
391
  credential,
315
392
  init,
316
393
  input,
317
394
  method: selected.method,
395
+ requirement: reportedOffer && spender.resolve(reportedOffer),
318
396
  response,
319
397
  }));
398
+ }
320
399
  if (!paymentRequired) {
321
400
  // The server may have settled before failing: report the credential for
322
401
  // reconciliation and return the response. Retrying could pay twice.
@@ -399,6 +478,8 @@ export function from(config) {
399
478
  wrappedFetch[MPPX_FETCH_WRAPPER] = baseFetch;
400
479
  if (identity)
401
480
  wrappedFetch[MPPX_FETCH_IDENTITY] = identity;
481
+ if (SpendGate.configured(spendConfig))
482
+ wrappedFetch[MPPX_FETCH_SPEND] = spendConfig;
402
483
  return wrappedFetch;
403
484
  }
404
485
  /**
@@ -590,7 +671,11 @@ function createCredentialCreatedPayload(parameters) {
590
671
  });
591
672
  }
592
673
  function createPaymentResponsePayload(parameters) {
674
+ const { requirement, response } = parameters;
675
+ const receipt = response instanceof Response ? Spend.readReceipt(response) : undefined;
593
676
  return Object.freeze({
677
+ ...(requirement ? { amount: requirement.amount.toString(), requirement } : {}),
678
+ ...(receipt ? { receipt } : {}),
594
679
  challenge: snapshotValue(parameters.challenge),
595
680
  credential: parameters.credential,
596
681
  init: snapshotInit(parameters.init),
@@ -706,7 +791,7 @@ function prepareInitialRequest(input, init, callerHeaders, header, hasExplicitAc
706
791
  input,
707
792
  };
708
793
  }
709
- function captureRequestBody(input, init, headers) {
794
+ function captureRequestBody(input, init, headers, signal) {
710
795
  if (!(input instanceof Request) || init?.body !== undefined || !input.body || input.bodyUsed)
711
796
  return undefined;
712
797
  if (!headers.has('mcp-method')) {
@@ -715,10 +800,12 @@ function captureRequestBody(input, init, headers) {
715
800
  return undefined;
716
801
  }
717
802
  try {
718
- return input
719
- .clone()
720
- .text()
721
- .catch(() => undefined);
803
+ const copy = input.clone();
804
+ // A stream its producer leaves open never ends: with `signal`, an abort cancels the read.
805
+ const body = signal && copy.body
806
+ ? new Response(copy.body.pipeThrough(new TransformStream(), { signal }))
807
+ : copy;
808
+ return body.text().catch(() => undefined);
722
809
  }
723
810
  catch {
724
811
  return undefined;
@@ -738,6 +825,10 @@ function getCallerHeaders(input, headers) {
738
825
  export function identityOf(fetch) {
739
826
  return fetch[MPPX_FETCH_IDENTITY];
740
827
  }
828
+ /** Returns the spending options of an mppx fetch wrapper, if it sets any. @internal */
829
+ export function spendConfigOf(fetch) {
830
+ return fetch[MPPX_FETCH_SPEND];
831
+ }
741
832
  /** @internal */
742
833
  export function unwrapFetch(fetch) {
743
834
  let current = fetch;
@@ -792,9 +883,11 @@ export function validateCredentialHeaderValue(credential) {
792
883
  }
793
884
  }
794
885
  /** @internal */
795
- async function resolveCredential(challenge, mi, context, attempt) {
886
+ async function resolveCredential(challenge, mi, context, attempt, constraints) {
796
887
  const parsedContext = mi.context && context !== undefined ? mi.context.parse(context) : undefined;
797
888
  const parameters = parsedContext !== undefined ? { challenge, context: parsedContext } : { challenge };
889
+ if (constraints)
890
+ SpendHooks.constrain(parameters, constraints);
798
891
  if (attempt?.origin)
799
892
  MethodResponse.attachOrigin(parameters, attempt.origin);
800
893
  if (attempt && 'prepare' in attempt)
@@ -943,4 +1036,29 @@ export function retryKey(challenge) {
943
1036
  const { description: _description, ...rest } = challenge;
944
1037
  return Json.canonicalize(rest);
945
1038
  }
1039
+ /**
1040
+ * Whether a payment-required response carries an `invalid-challenge` problem, as an HTTP
1041
+ * problem document or in an MCP payment-required error, read without consuming it.
1042
+ */
1043
+ async function isInvalidChallengeResponse(response, request) {
1044
+ if (!(response instanceof globalThis.Response))
1045
+ return false;
1046
+ if (await Mcp_protocol.isInvalidChallenge(response, request))
1047
+ return true;
1048
+ if (!response.headers.get('Content-Type')?.includes('application/problem+json'))
1049
+ return false;
1050
+ try {
1051
+ const problem = (await response.clone().json());
1052
+ return problem.type === 'https://paymentauth.org/problems/invalid-challenge';
1053
+ }
1054
+ catch {
1055
+ return false;
1056
+ }
1057
+ }
1058
+ /** Whether request headers carry a Payment credential (`Authorization: Payment` or `Payment-Authorization`). */
1059
+ function hasPaymentCredential(headers) {
1060
+ if (headers.get(Constants.Headers.paymentAuthorization))
1061
+ return true;
1062
+ return /(^|,)\s*Payment\s+\S/i.test(headers.get(Constants.Headers.authorization) ?? '');
1063
+ }
946
1064
  //# sourceMappingURL=Fetch.js.map
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Marks an error a method throws after it sent or settled a payment, such as a Zone withdrawal
3
+ * whose credential could not be built: funds may have moved, so the client's spending limits keep
4
+ * counting the payment instead of releasing it. The error's type and message are unchanged.
5
+ */
6
+ export declare function mark<const error extends Error>(error: error): error;
7
+ /** Whether {@link mark} marked `error`. */
8
+ export declare function has(error: unknown): boolean;
9
+ //# sourceMappingURL=FundsMoved.d.ts.map
@@ -0,0 +1,18 @@
1
+ // A global symbol, so errors from another copy of mppx in the same bundle are recognized too.
2
+ const fundsMayHaveMoved = Symbol.for('mppx.client.fundsMayHaveMoved');
3
+ /**
4
+ * Marks an error a method throws after it sent or settled a payment, such as a Zone withdrawal
5
+ * whose credential could not be built: funds may have moved, so the client's spending limits keep
6
+ * counting the payment instead of releasing it. The error's type and message are unchanged.
7
+ */
8
+ export function mark(error) {
9
+ Object.defineProperty(error, fundsMayHaveMoved, { value: true });
10
+ return error;
11
+ }
12
+ /** Whether {@link mark} marked `error`. */
13
+ export function has(error) {
14
+ return (typeof error === 'object' &&
15
+ error !== null &&
16
+ error[fundsMayHaveMoved] === true);
17
+ }
18
+ //# sourceMappingURL=FundsMoved.js.map
@@ -0,0 +1,136 @@
1
+ import type * as Challenge from '../../Challenge.js';
2
+ import { PaymentLimitExceededError } from '../../Errors.js';
3
+ import type * as Method from '../../Method.js';
4
+ import type * as Spend from '../Spend.js';
5
+ import * as SpendHooks from './SpendHooks.js';
6
+ /** Spending options shared by `Mppx.create` and `Fetch.from`. */
7
+ export type Config = {
8
+ /**
9
+ * Most a single payment may cost, checked after a challenge is selected and before any
10
+ * credential is created. A `Money` limit counts only tokens the client configures (`tokens`
11
+ * and Tempo's built-in stablecoins); payments in other assets are refused.
12
+ *
13
+ * Setting any of `maxPayment`, `authorize` or `funders` limits payments to `charge`
14
+ * challenges: sessions and subscriptions keep paying after one check, so they are refused.
15
+ */
16
+ maxPayment?: Spend.MaxPayment | undefined;
17
+ /**
18
+ * Approves each payment after `maxPayment` and before funders and signing. Pass
19
+ * `Budget.create({ total })` to cap total spend across payments.
20
+ */
21
+ authorize?: Spend.Authorize | undefined;
22
+ /** Funders run in order before each credential is signed, such as to swap funds into the wallet. */
23
+ funders?: readonly Spend.Funder[] | undefined;
24
+ /**
25
+ * Tokens whose `currency` and `decimals` the client trusts for `Money` limits, beside Tempo's
26
+ * built-in stablecoins (pathUSD, USDC.e, OUSD).
27
+ */
28
+ tokens?: readonly Spend.Token[] | undefined;
29
+ };
30
+ /** Settles one authorized payment, at most once. */
31
+ export type Settlement = Spend.Authorization;
32
+ /** A payment that passed the spending checks, or one they let resume. */
33
+ export type Prepared = Readonly<{
34
+ /** Commits or releases the payment's authorization. */
35
+ settlement: Settlement;
36
+ /** What the method may do for it. */
37
+ constraints: SpendHooks.Constraints;
38
+ }>;
39
+ /** Spending rules resolved from {@link Config}. */
40
+ export type Spender = {
41
+ /** Normalizes a `charge` challenge, or returns `undefined` when it names no checkable payment. */
42
+ resolve(challenge: Challenge.Challenge): Spend.Requirement | undefined;
43
+ /**
44
+ * Checks the intent, expiry and `maxPayment`, runs the method's own policy, `authorize` and the
45
+ * funders, and returns the settlement to commit or release. `undefined` when no spending option
46
+ * is set, so payments run unchanged.
47
+ *
48
+ * With `method`, a payment that method already made and these options already counted, such as
49
+ * an outstanding Zone withdrawal, resumes without a new reservation.
50
+ */
51
+ prepare: ((challenge: Challenge.Challenge, options?: {
52
+ method?: Method.AnyClient | undefined;
53
+ signal?: AbortSignal | undefined;
54
+ }) => Promise<Prepared>) | undefined;
55
+ /** The limit a refused credential names: `maxPayment` when it is set, else `budget`. */
56
+ limit: PaymentLimitExceededError.Limit;
57
+ };
58
+ /** Resolves and validates spending options once, at construction. */
59
+ export declare function from(config: Config): Spender;
60
+ /** Whether a config sets any spending option. */
61
+ export declare function configured(config: Config | undefined): boolean;
62
+ /** The spending options of `config`, without its other fields. */
63
+ export declare function pick(config: Config): Config;
64
+ /**
65
+ * The spending options a fetch built on `inner`'s mppx fetch uses: its own, else the ones
66
+ * `inner` was built with, so rewrapping a limited fetch never drops its limits. Throws when both
67
+ * set some, since neither set may silently replace the other.
68
+ */
69
+ export declare function inherit(config: Config, inner: Config | undefined): Config;
70
+ /** Whether mppx issued `plan`, so its currency and decimals come from client configuration. */
71
+ export declare function isIssued(plan: unknown): plan is Spend.Plan;
72
+ /**
73
+ * Commits `settlement` once `credential` is created, and releases it when creation fails. An
74
+ * error after which funds may have moved commits instead, so limits never undercount.
75
+ */
76
+ export declare function track(credential: Promise<string>, settlement: Settlement | undefined): Promise<string>;
77
+ /** One payment's spending checks while its credential is chosen. */
78
+ export type Payment = {
79
+ /** Runs the spending checks and funders, once. */
80
+ prepare(): Promise<Prepared | undefined>;
81
+ /**
82
+ * Prepares the payment, then tracks the credential mppx creates for it, as {@link track} does,
83
+ * except that a failure keeps the reservation for a credential a handler returns instead.
84
+ * `create` gets the constraints to attach to the method's credential parameters.
85
+ */
86
+ track(create: (constraints: SpendHooks.Constraints | undefined) => Promise<string>): Promise<string>;
87
+ /**
88
+ * Commits the payment for a credential mppx did not create. It reuses the prepared reservation,
89
+ * so funders run once, unless mppx's own credential already committed it.
90
+ */
91
+ commit(): Promise<void>;
92
+ /**
93
+ * Checks and commits a credential mppx did not create against the challenge it pays: the one
94
+ * among `offered`, the challenges of the same response, that its MPP echo names exactly or whose
95
+ * x402 requirements its x402 payload signs. That challenge's terms pass `maxPayment`,
96
+ * `authorize` and the funders, reusing the prepared reservation when it is the selected
97
+ * challenge. Returns that challenge, or `undefined` without spending options. Throws
98
+ * {@link PaymentLimitExceededError} when the credential cannot be read or bound to exactly one
99
+ * offer.
100
+ */
101
+ commitReplacement(credential: string, offered: readonly Challenge.Challenge[]): Promise<Challenge.Challenge | undefined>;
102
+ /**
103
+ * Frees the reservation when no credential is sent. A credential mppx is still creating settles
104
+ * it first, so a payment it makes stays counted. A no-op once committed.
105
+ */
106
+ release(): Promise<void>;
107
+ };
108
+ /**
109
+ * Starts one payment for `challenge`, which `method` signs. Its credential is mppx's own or one
110
+ * an event handler or `onChallenge` returns instead; either way `authorize` and the funders run
111
+ * at most once for it.
112
+ */
113
+ export declare function payment(spender: Spender, challenge: Challenge.Challenge, signal?: AbortSignal | undefined, method?: Method.AnyClient | undefined): Payment;
114
+ /**
115
+ * Identifies a challenge by everything its ID binds (realm, method, intent, request, expiry,
116
+ * digest and opaque data) and the ID itself, so two offers that share an ID stay apart.
117
+ */
118
+ export declare function identity(challenge: Challenge.Challenge): string;
119
+ /**
120
+ * The one offered challenge a credential pays: the MPP challenge its echo repeats exactly, or the
121
+ * x402 offer whose requirements its x402 payload accepts and signs. `undefined` when it cannot be
122
+ * read, or matches no offer or several.
123
+ */
124
+ export declare function replacedChallenge(credential: string, offered: readonly Challenge.Challenge[]): Challenge.Challenge | undefined;
125
+ /** Key identifying an asset on a network; EVM addresses and Stripe currencies match in any case. */
126
+ export declare function assetKey(network: string, asset: string): string;
127
+ /**
128
+ * Parses a non-negative decimal into units at `decimals` places without floating point.
129
+ * Digits beyond `decimals` are dropped, which only lowers a limit.
130
+ */
131
+ export declare function parseUnits(value: string, decimals: number): bigint;
132
+ /** Rejects a `Money` value that is not a non-negative decimal in a named currency. */
133
+ export declare function assertMoney(money: unknown, name: string): asserts money is Spend.Money;
134
+ /** Whether a value is an {@link Spend.AssetLimit}. */
135
+ export declare function isAssetLimit(value: unknown): value is Spend.AssetLimit;
136
+ //# sourceMappingURL=SpendGate.d.ts.map