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
@@ -0,0 +1,49 @@
1
+ import type * as Spend from './Spend.js';
2
+ /** A budget's total: an amount in a reference currency, or an amount of one asset. */
3
+ export type Total = Spend.Money | Spend.AssetLimit;
4
+ /** The shape of a budget's amounts: {@link Spend.Money} for a currency total, else {@link Spend.AssetLimit}. */
5
+ export type Amount<total extends Total> = total extends Spend.Money ? Spend.Money : Spend.AssetLimit;
6
+ /**
7
+ * A spending cap shared by concurrent payments, usable as the client's `authorize` option. Each
8
+ * payment reserves its amount before it is signed; mppx commits the reservation once the
9
+ * credential is created and releases it when nothing was signed.
10
+ */
11
+ export type Budget<total extends Total = Total> = {
12
+ /** Reserves the plan's amount, or throws `PaymentLimitExceededError` when it does not fit. */
13
+ (plan: Spend.Plan, context?: Spend.Context | undefined): Spend.Authorization;
14
+ /** The configured total. */
15
+ readonly total: Amount<total>;
16
+ /** Total minus spent and reserved amounts. */
17
+ remaining(): Amount<total>;
18
+ /** Amounts of payments whose credential was created. */
19
+ spent(): Amount<total>;
20
+ /** Amounts held by payments in flight. */
21
+ reserved(): Amount<total>;
22
+ };
23
+ /**
24
+ * Creates a {@link Budget}. Reservations are synchronous, so concurrent payments cannot
25
+ * overspend it.
26
+ *
27
+ * A currency total counts only payments in tokens whose currency and decimals the client
28
+ * configures (`tokens` and Tempo's built-in stablecoins); an asset total counts only payments in
29
+ * that asset. Any other payment is refused.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * import { Budget, Mppx, tempo } from 'mppx/client'
34
+ *
35
+ * const budget = Budget.create({ total: { value: '5', currency: 'USD' } })
36
+ * const mppx = Mppx.create({ methods: [tempo({ account })], authorize: budget })
37
+ *
38
+ * await mppx.fetch('https://api.example.com/resource')
39
+ * budget.remaining() // { value: '4.99', currency: 'USD' }
40
+ * ```
41
+ */
42
+ export declare function create<const total extends Total>(options: create.Options<total>): Budget<total>;
43
+ export declare namespace create {
44
+ type Options<total extends Total = Total> = {
45
+ /** Most the budget lets payments spend. */
46
+ total: total;
47
+ };
48
+ }
49
+ //# sourceMappingURL=Budget.d.ts.map
@@ -0,0 +1,101 @@
1
+ import { PaymentLimitExceededError } from '../Errors.js';
2
+ import * as SpendGate from './internal/SpendGate.js';
3
+ /**
4
+ * Creates a {@link Budget}. Reservations are synchronous, so concurrent payments cannot
5
+ * overspend it.
6
+ *
7
+ * A currency total counts only payments in tokens whose currency and decimals the client
8
+ * configures (`tokens` and Tempo's built-in stablecoins); an asset total counts only payments in
9
+ * that asset. Any other payment is refused.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { Budget, Mppx, tempo } from 'mppx/client'
14
+ *
15
+ * const budget = Budget.create({ total: { value: '5', currency: 'USD' } })
16
+ * const mppx = Mppx.create({ methods: [tempo({ account })], authorize: budget })
17
+ *
18
+ * await mppx.fetch('https://api.example.com/resource')
19
+ * budget.remaining() // { value: '4.99', currency: 'USD' }
20
+ * ```
21
+ */
22
+ export function create(options) {
23
+ const total = { ...options.total };
24
+ const money = !SpendGate.isAssetLimit(total);
25
+ if (money)
26
+ SpendGate.assertMoney(total, 'total');
27
+ // Money amounts are kept as integers at `scale` decimal places, raised to fit each payment.
28
+ let scale = money ? (total.value.split('.')[1]?.length ?? 0) : 0;
29
+ let limit = money ? SpendGate.parseUnits(total.value, scale) : total.amount;
30
+ let spent = 0n;
31
+ let reserved = 0n;
32
+ const rescale = (decimals) => {
33
+ if (decimals <= scale)
34
+ return;
35
+ const factor = 10n ** BigInt(decimals - scale);
36
+ limit *= factor;
37
+ spent *= factor;
38
+ reserved *= factor;
39
+ scale = decimals;
40
+ };
41
+ const amount = (value) => Object.freeze(money
42
+ ? { value: formatUnits(value, scale), currency: total.currency }
43
+ : { network: total.network, asset: total.asset, amount: value });
44
+ const refuse = (reason) => new PaymentLimitExceededError({ limit: 'budget', reason });
45
+ const authorize = (plan) => {
46
+ if (!SpendGate.isIssued(plan))
47
+ throw new TypeError('Budget only accepts plans mppx issued.');
48
+ const { requirement } = plan;
49
+ let decimals = 0;
50
+ if (money) {
51
+ // Set only from client configuration, never from the challenge.
52
+ if (requirement.currency === undefined || requirement.decimals === undefined)
53
+ throw refuse('asset');
54
+ if (requirement.currency.toUpperCase() !== total.currency.toUpperCase())
55
+ throw refuse('asset');
56
+ decimals = requirement.decimals;
57
+ }
58
+ else if (SpendGate.assetKey(requirement.network, requirement.asset) !==
59
+ SpendGate.assetKey(total.network, total.asset))
60
+ throw refuse('asset');
61
+ rescale(decimals);
62
+ // Read at the current scale, which a later payment with more decimals can raise.
63
+ const cost = () => requirement.amount * 10n ** BigInt(scale - decimals);
64
+ if (cost() > limit - spent - reserved)
65
+ throw refuse('amount');
66
+ reserved += cost();
67
+ let open = true;
68
+ const close = () => {
69
+ if (!open)
70
+ return false;
71
+ open = false;
72
+ reserved -= cost();
73
+ return true;
74
+ };
75
+ return Object.freeze({
76
+ commit() {
77
+ if (close())
78
+ spent += cost();
79
+ },
80
+ release() {
81
+ close();
82
+ },
83
+ });
84
+ };
85
+ return Object.freeze(Object.assign(authorize, {
86
+ total: amount(limit),
87
+ remaining: () => amount(limit - spent - reserved),
88
+ spent: () => amount(spent),
89
+ reserved: () => amount(reserved),
90
+ }));
91
+ }
92
+ /** Formats an integer at `decimals` places as a decimal string without trailing zeros. */
93
+ function formatUnits(value, decimals) {
94
+ if (decimals === 0)
95
+ return value.toString();
96
+ const digits = value.toString().padStart(decimals + 1, '0');
97
+ const fraction = digits.slice(-decimals).replace(/0+$/, '');
98
+ const integer = digits.slice(0, -decimals);
99
+ return fraction ? `${integer}.${fraction}` : integer;
100
+ }
101
+ //# sourceMappingURL=Budget.js.map
@@ -4,6 +4,7 @@ import * as AcceptPayment from '../internal/AcceptPayment.js';
4
4
  import type * as Method from '../Method.js';
5
5
  import type * as z from '../zod.js';
6
6
  import * as Fetch from './internal/Fetch.js';
7
+ import * as SpendGate from './internal/SpendGate.js';
7
8
  import * as Transport from './Transport.js';
8
9
  export type Methods = readonly (Method.AnyClient | readonly Method.AnyClient[])[];
9
10
  type EventResponseOf<transport extends Transport.AnyTransport> = Response | Transport.ResponseOf<transport>;
@@ -162,7 +163,7 @@ export declare namespace createCredential {
162
163
  */
163
164
  export declare function restore(): void;
164
165
  export declare namespace create {
165
- type Config<methods extends Methods = Methods, transport extends Transport.AnyTransport = Transport.Transport> = {
166
+ type Config<methods extends Methods = Methods, transport extends Transport.AnyTransport = Transport.Transport> = SpendGate.Config & {
166
167
  /**
167
168
  * Identity provers applied to every in-scope HTTP attempt, in order.
168
169
  * List request signers last so they cover headers added by earlier provers.
@@ -172,10 +173,14 @@ export declare namespace create {
172
173
  acceptPaymentPolicy?: Fetch.from.Config['acceptPaymentPolicy'] | undefined;
173
174
  /** Custom fetch function to wrap. Defaults to `globalThis.fetch`. */
174
175
  fetch?: typeof globalThis.fetch;
175
- /** Called when a 402 challenge is received and no event handler supplies a credential. */
176
+ /**
177
+ * Called when a 402 challenge is received and no event handler supplies a credential, before
178
+ * paying. Return a credential to send it, `undefined` to pay with the method's default
179
+ * credential, or `false` to decline: nothing is paid and the 402 response is returned.
180
+ */
176
181
  onChallenge?: ((challenge: Challenge.Challenge, helpers: {
177
182
  createCredential: (context?: AnyContextFor<FlattenMethods<methods>>) => Promise<string>;
178
- }) => Promise<string | undefined>) | undefined;
183
+ }) => Promise<string | undefined | false>) | undefined;
179
184
  /** Maximum number of payment challenge retries after the initial response. @default 3 */
180
185
  maxPaymentRetries?: Fetch.from.Config['maxPaymentRetries'] | undefined;
181
186
  /** Filters and sorts supported challenges before credential creation. */
@@ -9,8 +9,12 @@ import * as Fetch from './internal/Fetch.js';
9
9
  import * as MethodChallenge from './internal/MethodChallenge.js';
10
10
  import * as MethodResponse from './internal/MethodResponse.js';
11
11
  import * as ProofRealm from './internal/ProofRealm.js';
12
+ import * as SpendGate from './internal/SpendGate.js';
13
+ import * as SpendHooks from './internal/SpendHooks.js';
12
14
  import * as Transport from './Transport.js';
13
15
  const preparedPaymentMethods = new WeakMap();
16
+ /** A prepared payment's spending checks, run once before any of its signing work. */
17
+ const preparedPaymentSpend = new WeakMap();
14
18
  /**
15
19
  * Creates a client-side payment handler from an array of methods.
16
20
  *
@@ -46,10 +50,14 @@ export function create(config) {
46
50
  const methods = config.methods.flat();
47
51
  const acceptPayment = AcceptPayment.resolve(methods, config.paymentPreferences);
48
52
  const events = Fetch.createEventDispatcher();
53
+ // Rewrapping a limited mppx fetch keeps its spending options, so its limits still apply.
54
+ const spendConfig = SpendGate.inherit(config, config.fetch && Fetch.spendConfigOf(config.fetch));
55
+ const spender = SpendGate.from(spendConfig);
49
56
  const resolvedOnChallenge = onChallenge;
50
57
  const config_fetch = {
51
58
  acceptPayment,
52
59
  acceptPaymentPolicy,
60
+ ...spendConfig,
53
61
  ...(config.fetch && { fetch: rawFetch }),
54
62
  ...(identityClient && { identity: identityClient }),
55
63
  eventDispatcher: events,
@@ -128,11 +136,16 @@ export function create(config) {
128
136
  ProofRealm.assertWithoutOrigin(challenge, trustedTempoProofRealms && Object.values(trustedTempoProofRealms));
129
137
  const selectedChallenge = challenge;
130
138
  const selectedMethod = mi;
139
+ // A canceled request starts no authorization, funding or signing for this payment.
140
+ const spend = SpendGate.payment(spender, selectedChallenge, requestSignal(options?.request), selectedMethod);
131
141
  const createPreparedCredential = memoizeCreateCredential(async (context) => {
132
142
  try {
133
143
  if (selectedChallenge.expires)
134
144
  Expires.assert(selectedChallenge.expires, selectedChallenge.id);
135
- const createCredential = memoizeCreateCredential((overrideContext) => createCredentialForMethod(selectedChallenge, selectedMethod, overrideContext ?? context, responseUrl?.origin));
145
+ let checkedCredential;
146
+ const createCredential = memoizeCreateCredential((overrideContext) =>
147
+ // Spending limits, authorization and funding run before signing.
148
+ (checkedCredential = spend.track((constraints) => createCredentialForMethod(selectedChallenge, selectedMethod, overrideContext ?? context, responseUrl?.origin, constraints))));
136
149
  const eventCredential = await events.emit('challenge.received', createChallengeReceivedPayload({
137
150
  challenge: selectedChallenge,
138
151
  challenges,
@@ -142,6 +155,12 @@ export function create(config) {
142
155
  }));
143
156
  const credential = eventCredential ?? (await createCredential());
144
157
  Fetch.validateCredentialHeaderValue(credential);
158
+ // A credential an event handler made itself is checked against the offer it pays
159
+ // before it is returned. For the selected offer it takes the reservation already
160
+ // prepared, so funders run once.
161
+ if (!checkedCredential ||
162
+ (await checkedCredential.catch(() => undefined)) !== credential)
163
+ await spend.commitReplacement(credential, challengeSnapshots);
145
164
  await events.emit('credential.created', createCredentialCreatedPayload({
146
165
  challenge: selectedChallenge,
147
166
  credential,
@@ -151,6 +170,8 @@ export function create(config) {
151
170
  return credential;
152
171
  }
153
172
  catch (error) {
173
+ // A no-op once a credential committed it.
174
+ await spend.release();
154
175
  await events.emit('payment.failed', createPaymentFailedPayload({
155
176
  challenge: selectedChallenge,
156
177
  challenges,
@@ -172,6 +193,8 @@ export function create(config) {
172
193
  },
173
194
  });
174
195
  preparedPaymentMethods.set(prepared, selectedMethod);
196
+ if (spender.prepare)
197
+ preparedPaymentSpend.set(prepared, spend);
175
198
  return prepared;
176
199
  }
177
200
  catch (error) {
@@ -213,19 +236,31 @@ export function create(config) {
213
236
  }));
214
237
  ProofRealm.assert(payment.challenge, new URL(preparedHttp.replayRequest.url), trustedTempoProofRealms);
215
238
  const paymentMethod = preparedPaymentMethods.get(payment) ?? payment.method;
239
+ const spend = preparedPaymentSpend.get(payment);
216
240
  const createRequestCredential = memoizeCreateCredential(async (context) => {
217
241
  await identityClient?.challenge(preparedHttp.response, { challenge: payment.challenge }, preparedHttp.replayRequest.url);
218
- if (MethodChallenge.has(paymentMethod))
219
- await MethodChallenge.handle(paymentMethod, {
220
- challenge: payment.challenge,
221
- context,
222
- fetch: identityClient
223
- ? IdentityClient.wrapFetch(rawFetch, identityClient, { challenge: payment.challenge })
224
- : rawFetch,
225
- input: preparedHttp.replayRequest,
226
- signal: preparedHttp.replayRequest.signal,
227
- });
228
- return payment.createCredential(context);
242
+ // Method preparation can sign (such as opening a channel), so limits run first.
243
+ await spend?.prepare();
244
+ try {
245
+ if (MethodChallenge.has(paymentMethod))
246
+ await MethodChallenge.handle(paymentMethod, {
247
+ challenge: payment.challenge,
248
+ context,
249
+ fetch: identityClient
250
+ ? IdentityClient.wrapFetch(rawFetch, identityClient, {
251
+ challenge: payment.challenge,
252
+ })
253
+ : rawFetch,
254
+ input: preparedHttp.replayRequest,
255
+ signal: preparedHttp.replayRequest.signal,
256
+ });
257
+ return await payment.createCredential(context);
258
+ }
259
+ catch (error) {
260
+ // A no-op once the created credential committed it.
261
+ await spend?.release();
262
+ throw error;
263
+ }
229
264
  });
230
265
  const preparedPayment = Object.freeze({
231
266
  ...payment,
@@ -511,13 +546,20 @@ function resolveChallengePreferences(fallback, override) {
511
546
  async function resolveChallengeOrder(candidates, orderChallenges) {
512
547
  return orderChallenges ? orderChallenges(candidates) : candidates;
513
548
  }
514
- async function createCredentialForMethod(challenge, mi, context, origin) {
549
+ async function createCredentialForMethod(challenge, mi, context, origin, constraints) {
515
550
  const parsedContext = mi.context && context !== undefined ? mi.context.parse(context) : undefined;
516
551
  const parameters = parsedContext !== undefined ? { challenge, context: parsedContext } : { challenge };
552
+ if (constraints)
553
+ SpendHooks.constrain(parameters, constraints);
517
554
  if (origin)
518
555
  MethodResponse.attachOrigin(parameters, origin);
519
556
  return mi.createCredential(parameters);
520
557
  }
558
+ /** Returns the abort signal of an HTTP request init, when it has one. */
559
+ function requestSignal(request) {
560
+ const signal = request?.signal;
561
+ return typeof AbortSignal !== 'undefined' && signal instanceof AbortSignal ? signal : undefined;
562
+ }
521
563
  /** Returns the URL of the HTTP server that sent `response`, or `undefined` when it has none. */
522
564
  function resolveResponseUrl(response) {
523
565
  if (typeof Response !== 'undefined' && response instanceof Response && response.url)
@@ -0,0 +1,134 @@
1
+ import type { ResolvedToken } from 'viem';
2
+ import type { Token as viem_Token } from 'viem/tokens';
3
+ import type * as Challenge from '../Challenge.js';
4
+ /** An amount in a reference currency, such as `{ value: '0.50', currency: 'USD' }`. */
5
+ export type Money = Readonly<{
6
+ /** Non-negative decimal string, such as `'0.50'`. */
7
+ value: string;
8
+ /** Reference currency, such as `'USD'`; compared case-insensitively. */
9
+ currency: string;
10
+ }>;
11
+ /** An amount of one asset on one network, in its atomic units. */
12
+ export type AssetLimit = Readonly<{
13
+ /** Network the asset is paid on: `eip155:<chainId>` for Tempo and EVM, `stripe` for Stripe. */
14
+ network: string;
15
+ /** Asset on `network`: a token address (any case), or a Stripe currency such as `usd`. */
16
+ asset: string;
17
+ /** Atomic amount. */
18
+ amount: bigint;
19
+ }>;
20
+ /**
21
+ * Most a single payment may cost: a {@link Money} limit, or per-asset limits in atomic units.
22
+ *
23
+ * A {@link Money} limit counts only payments in a token whose currency and decimals the client
24
+ * configures itself (`tokens` and Tempo's built-in stablecoins), never values from a challenge.
25
+ * A payment in any other asset is refused.
26
+ */
27
+ export type MaxPayment = Money | readonly AssetLimit[];
28
+ /**
29
+ * A token the client trusts for currency limits: a `viem/tokens` token (such as `usdc`, on every
30
+ * chain it lists) or a token resolved to one chain (such as `usdc(8453)`), with its `currency`.
31
+ */
32
+ export type Token = viem_Token | ResolvedToken;
33
+ /** The payment a selected challenge asks for, normalized across methods and protocols. */
34
+ export type Requirement = Readonly<{
35
+ /** Wire protocol of the challenge. */
36
+ protocol: 'mpp' | 'x402';
37
+ /** Payment method, such as `tempo`, `evm` or `stripe`. */
38
+ method: string;
39
+ /** Payment intent: `charge`, the only intent spending options accept. */
40
+ intent: string;
41
+ /**
42
+ * Network the payment is on: `eip155:<chainId>` when the challenge's `methodDetails.chainId`
43
+ * names the chain the method signs on, otherwise the method name (such as `stripe`).
44
+ */
45
+ network: string;
46
+ /** Asset on `network`: a token address, or a Stripe currency such as `usd`. */
47
+ asset: string;
48
+ /** Atomic amount the credential pays in all, `splits` included. */
49
+ amount: bigint;
50
+ /**
51
+ * Payee the credential pays: the challenge's `recipient`, or for Stripe the Business Network
52
+ * profile (`methodDetails.networkId`) its Shared Payment Token is created for.
53
+ */
54
+ recipient?: string | undefined;
55
+ /**
56
+ * Other payees and their atomic shares, which the credential pays out of `amount`; `recipient`
57
+ * gets the rest.
58
+ */
59
+ splits?: readonly Readonly<{
60
+ recipient: string;
61
+ amount: bigint;
62
+ }>[] | undefined;
63
+ /** Reference currency of `asset`, only when the client configures the token. */
64
+ currency?: string | undefined;
65
+ /** Decimals of `asset`, only when the client configures the token. */
66
+ decimals?: number | undefined;
67
+ }>;
68
+ /** A payment that passed `maxPayment`, handed to `authorize`. mppx issues every plan. */
69
+ export type Plan = Readonly<{
70
+ /** The payment the credential would make. */
71
+ requirement: Requirement;
72
+ }>;
73
+ /** The paid request a hook runs for. */
74
+ export type Context = Readonly<{
75
+ /**
76
+ * A frozen copy of the selected challenge. Server data: never trust it for limits. The
77
+ * credential is signed only if the challenge is unchanged once every hook ran.
78
+ */
79
+ challenge: Challenge.Challenge;
80
+ /** The request's abort signal, when it has one. */
81
+ signal?: AbortSignal | undefined;
82
+ }>;
83
+ /**
84
+ * Settles one authorized payment. mppx calls one of them, once: `commit` when a credential was
85
+ * created (it may reach the server or move funds), `release` when funding or creating the
86
+ * credential failed, so nothing was signed or sent.
87
+ */
88
+ export type Authorization = Readonly<{
89
+ commit(): void;
90
+ release(): void;
91
+ }>;
92
+ /**
93
+ * Approves a payment after `maxPayment` and before funders run and the credential is signed.
94
+ * Throw to refuse it; return an {@link Authorization} to learn how it settled. Pass a `Budget`
95
+ * to cap total spend across payments.
96
+ */
97
+ export type Authorize = (plan: Plan, context: Context) => Authorization | undefined | void | Promise<Authorization | undefined | void>;
98
+ /**
99
+ * Prepares funds for a payment before its credential is signed, such as swapping or bridging
100
+ * into the paying wallet. Funders run in order after `maxPayment` and `authorize`; if one
101
+ * throws, the authorization is released and the payment fails.
102
+ */
103
+ export type Funder = Readonly<{
104
+ fund(requirement: Requirement, context: Context): Promise<void>;
105
+ }>;
106
+ /**
107
+ * A decoded protocol receipt from a paid response: an MPP `Payment-Receipt` or an x402
108
+ * `PAYMENT-RESPONSE` that reports success. Server data, so evidence rather than proof.
109
+ */
110
+ export type PaymentReceipt = Readonly<{
111
+ /** Protocol of the header it came from. */
112
+ protocol: 'mpp' | 'x402';
113
+ /** Settlement reference: the MPP receipt's `reference` or the x402 `transaction`. */
114
+ reference?: string | undefined;
115
+ /** `reference` when it is a 32-byte hex transaction hash. */
116
+ transactionHash?: `0x${string}` | undefined;
117
+ /** The decoded header. */
118
+ raw: Readonly<Record<string, unknown>>;
119
+ }>;
120
+ /**
121
+ * Reads the receipt of a paid response: an MPP `Payment-Receipt` header, else an x402
122
+ * `PAYMENT-RESPONSE` header whose `success` is true. Returns `undefined` when the response
123
+ * carries neither, or the header is malformed or oversized.
124
+ *
125
+ * @example
126
+ * ```ts
127
+ * import { Spend } from 'mppx/client'
128
+ *
129
+ * const receipt = Spend.readReceipt(response)
130
+ * receipt?.transactionHash
131
+ * ```
132
+ */
133
+ export declare function readReceipt(response: Response): PaymentReceipt | undefined;
134
+ //# sourceMappingURL=Spend.d.ts.map
@@ -0,0 +1,58 @@
1
+ import * as Constants from '../Constants.js';
2
+ import * as x402_Types from '../internal/x402/Types.js';
3
+ import * as Receipt_ from '../Receipt.js';
4
+ /** Longest receipt header decoded; a receipt is a small JSON object. */
5
+ const maxReceiptHeaderLength = 8_192;
6
+ /**
7
+ * Reads the receipt of a paid response: an MPP `Payment-Receipt` header, else an x402
8
+ * `PAYMENT-RESPONSE` header whose `success` is true. Returns `undefined` when the response
9
+ * carries neither, or the header is malformed or oversized.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { Spend } from 'mppx/client'
14
+ *
15
+ * const receipt = Spend.readReceipt(response)
16
+ * receipt?.transactionHash
17
+ * ```
18
+ */
19
+ export function readReceipt(response) {
20
+ const mpp = response.headers.get(Constants.Headers.paymentReceipt);
21
+ if (mpp !== null) {
22
+ if (mpp.length > maxReceiptHeaderLength)
23
+ return undefined;
24
+ try {
25
+ const receipt = Receipt_.deserialize(mpp);
26
+ return toReceipt('mpp', receipt.reference, receipt);
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ }
32
+ const x402 = response.headers.get(x402_Types.paymentResponseHeader);
33
+ if (x402 === null || x402.length > maxReceiptHeaderLength)
34
+ return undefined;
35
+ try {
36
+ const binary = atob(x402.trim().replace(/-/g, '+').replace(/_/g, '/'));
37
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
38
+ const json = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
39
+ const parsed = x402_Types.SettleResponseSchema.safeParse(json);
40
+ if (!parsed.success || !parsed.data.success)
41
+ return undefined;
42
+ return toReceipt('x402', parsed.data.transaction, json);
43
+ }
44
+ catch {
45
+ return undefined;
46
+ }
47
+ }
48
+ function toReceipt(protocol, reference, raw) {
49
+ return Object.freeze({
50
+ protocol,
51
+ ...(reference ? { reference } : {}),
52
+ ...(/^0x[\da-fA-F]{64}$/.test(reference)
53
+ ? { transactionHash: reference }
54
+ : {}),
55
+ raw: Object.freeze({ ...raw }),
56
+ });
57
+ }
58
+ //# sourceMappingURL=Spend.js.map
@@ -1,6 +1,8 @@
1
+ export * as Budget from './Budget.js';
1
2
  export * as Constants from '../Constants.js';
2
3
  export * as Expires from '../Expires.js';
3
4
  export * as Fetch from './internal/Fetch.js';
4
5
  export * as Mppx from './Mppx.js';
6
+ export * as Spend from './Spend.js';
5
7
  export * as Transport from './Transport.js';
6
8
  //# sourceMappingURL=core.d.ts.map
@@ -1,6 +1,8 @@
1
+ export * as Budget from './Budget.js';
1
2
  export * as Constants from '../Constants.js';
2
3
  export * as Expires from '../Expires.js';
3
4
  export * as Fetch from './internal/Fetch.js';
4
5
  export * as Mppx from './Mppx.js';
6
+ export * as Spend from './Spend.js';
5
7
  export * as Transport from './Transport.js';
6
8
  //# sourceMappingURL=core.js.map
@@ -4,8 +4,10 @@ import * as AcceptPayment from '../../internal/AcceptPayment.js';
4
4
  import type { MaybePromise } from '../../internal/types.js';
5
5
  import type * as Method from '../../Method.js';
6
6
  import type * as z from '../../zod.js';
7
+ import * as Spend from '../Spend.js';
7
8
  import * as Transport from '../Transport.js';
8
9
  import * as ProofRealm from './ProofRealm.js';
10
+ import * as SpendGate from './SpendGate.js';
9
11
  /** Per-request payment opt-out preserved by forwarding fetch layers. @internal */
10
12
  export declare const skipPayment: unique symbol;
11
13
  /**
@@ -48,11 +50,23 @@ export type CredentialCreatedPayload<methods extends readonly Method.AnyClient[]
48
50
  response?: response | undefined;
49
51
  }>;
50
52
  export type PaymentResponsePayload<methods extends readonly Method.AnyClient[] = readonly Method.AnyClient[], response = Response> = Readonly<{
53
+ /**
54
+ * Atomic amount of the paid `charge` challenge as a decimal string, such as `'25'`, when it
55
+ * names one. A string, so the payload stays JSON-serializable.
56
+ */
57
+ amount?: string | undefined;
51
58
  challenge: Challenge.Challenge;
52
59
  credential: string;
53
60
  init?: from.RequestInit<methods> | undefined;
54
61
  input?: RequestInfo | URL | undefined;
55
62
  method: methods[number];
63
+ /** The response's MPP or x402 receipt, when it carries one. */
64
+ receipt?: Spend.PaymentReceipt | undefined;
65
+ /**
66
+ * The paid `charge` challenge, normalized; see `Spend.Requirement`. Its bigint amounts
67
+ * serialize to decimal strings with `JSON.stringify`.
68
+ */
69
+ requirement?: Spend.Requirement | undefined;
56
70
  response: response;
57
71
  }>;
58
72
  export type PaymentFailedPayload<methods extends readonly Method.AnyClient[] = readonly Method.AnyClient[], response = Response> = Readonly<{
@@ -112,10 +126,14 @@ export declare namespace from {
112
126
  maxPaymentRetries?: number | undefined;
113
127
  /** Array of methods to use. */
114
128
  methods: methods;
115
- /** Called when a 402 challenge is received and no event handler supplies a credential. */
129
+ /**
130
+ * Called when a 402 challenge is received and no event handler supplies a credential, before
131
+ * paying. Return a credential to send it, `undefined` to pay with the method's default
132
+ * credential, or `false` to decline: nothing is paid and the 402 response is returned.
133
+ */
116
134
  onChallenge?: ((challenge: Challenge.Challenge, helpers: {
117
135
  createCredential: (context?: AnyContextFor<methods>) => Promise<string>;
118
- }) => Promise<string | undefined>) | undefined;
136
+ }) => Promise<string | undefined | false>) | undefined;
119
137
  /** Filters and sorts supported challenges before credential creation. */
120
138
  orderChallenges?: AcceptPayment.OrderChallenges<methods> | undefined;
121
139
  /** Transport to use for challenge extraction and credential attachment. */
@@ -125,7 +143,7 @@ export declare namespace from {
125
143
  * hostname, mapped to that realm, such as `{ 'https://api.example.com': 'MPP Payment' }`.
126
144
  */
127
145
  trustedTempoProofRealms?: ProofRealm.TrustedRealms | undefined;
128
- };
146
+ } & SpendGate.Config;
129
147
  type Fetch<methods extends readonly Method.AnyClient[] = readonly Method.AnyClient[]> = (input: RequestInfo | URL, init?: RequestInit<methods>) => Promise<Response>;
130
148
  type RequestInit<methods extends readonly Method.AnyClient[] = readonly Method.AnyClient[]> = globalThis.RequestInit & {
131
149
  /** Context to pass to the method intent's createCredential. */
@@ -186,6 +204,8 @@ export declare function createEventDispatcher<methods extends readonly Method.An
186
204
  /** @internal */
187
205
  /** Returns the identity runner of an mppx fetch wrapper, if it has one. @internal */
188
206
  export declare function identityOf(fetch: typeof globalThis.fetch): IdentityClient.Client | undefined;
207
+ /** Returns the spending options of an mppx fetch wrapper, if it sets any. @internal */
208
+ export declare function spendConfigOf(fetch: typeof globalThis.fetch): SpendGate.Config | undefined;
189
209
  /** @internal */
190
210
  export declare function unwrapFetch(fetch: typeof globalThis.fetch): typeof globalThis.fetch;
191
211
  /** @internal */