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,608 @@
1
+ import { ousd, pathusd, usdce } from 'viem/tokens';
2
+ import * as Credential from '../../Credential.js';
3
+ import { BroadcastOutcomeUnknownError, PaymentLimitExceededError, ZoneSettlementPendingError, } from '../../Errors.js';
4
+ import * as Expires from '../../Expires.js';
5
+ import * as x402_ChallengeBrand from '../../internal/x402/ChallengeBrand.js';
6
+ import * as x402_Header from '../../internal/x402/Header.js';
7
+ import * as x402_Types from '../../internal/x402/Types.js';
8
+ import * as PaymentRequest from '../../PaymentRequest.js';
9
+ import * as FundsMoved from './FundsMoved.js';
10
+ import * as SpendHooks from './SpendHooks.js';
11
+ const tempoChainIds = [4217, 42431];
12
+ const builtinTokens = [ousd, pathusd, usdce];
13
+ /** Stripe charges USD in cents. */
14
+ const stripeTokens = [{ network: 'stripe', asset: 'usd', currency: 'USD', decimals: 2 }];
15
+ /** The only intent spending options can bound: one payment of a known amount. */
16
+ const chargeIntent = 'charge';
17
+ const issued = new WeakSet();
18
+ /**
19
+ * The `authorize` each payment's constraints were issued under, so a signing that payments under
20
+ * one authorization share is counted once.
21
+ */
22
+ const scopes = new WeakMap();
23
+ /** Constraints of payments whose credential committed a reservation, so their signing is counted. */
24
+ const counted = new WeakSet();
25
+ const decimalPattern = /^(\d+)(?:\.(\d+))?$/;
26
+ const maxDecimalLength = 1_024;
27
+ /** Resolves and validates spending options once, at construction. */
28
+ export function from(config) {
29
+ const { authorize, funders = [], maxPayment, tokens } = config;
30
+ if (maxPayment !== undefined)
31
+ assertMaxPayment(maxPayment);
32
+ if (authorize !== undefined && typeof authorize !== 'function')
33
+ throw new TypeError('authorize must be a function.');
34
+ if (!Array.isArray(funders) || funders.some((funder) => typeof funder?.fund !== 'function'))
35
+ throw new TypeError('funders must be an array of objects with a fund function.');
36
+ const metadata = tokenMetadata(tokens);
37
+ const resolve = (challenge) => requirement(challenge, metadata);
38
+ const enabled = maxPayment !== undefined || authorize !== undefined || funders.length > 0;
39
+ const limit = maxPayment === undefined ? 'budget' : 'maxPayment';
40
+ return {
41
+ limit,
42
+ resolve(challenge) {
43
+ if (challenge.intent !== chargeIntent)
44
+ return undefined;
45
+ try {
46
+ return resolve(challenge);
47
+ }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ },
52
+ prepare: enabled
53
+ ? async (challenge, { method, signal } = {}) => {
54
+ // A canceled request starts no authorization or funding.
55
+ signal?.throwIfAborted();
56
+ // A limit bounds one payment. Sessions and subscriptions keep paying after this check,
57
+ // so only charges pass, before any method, hook or funder runs.
58
+ if (challenge.intent !== chargeIntent)
59
+ throw new PaymentLimitExceededError({ limit, reason: 'intent' });
60
+ // An expired challenge cannot be paid, so nothing is authorized or funded for it.
61
+ if (challenge.expires)
62
+ Expires.assert(challenge.expires, challenge.id);
63
+ const hooks = method && SpendHooks.get(method);
64
+ // A payment the method already made was counted when it started: resume it as is.
65
+ if (hooks?.resumes?.(challenge))
66
+ return Object.freeze({
67
+ settlement: once(undefined),
68
+ constraints: constraints(true),
69
+ });
70
+ const key = identity(challenge);
71
+ const requirement = resolve(challenge);
72
+ if (maxPayment !== undefined)
73
+ assertWithin(requirement, maxPayment);
74
+ // Refuse what the method would refuse before anything is reserved or funded.
75
+ hooks?.assert?.(challenge);
76
+ // Hooks get a frozen copy, so they cannot change what is signed.
77
+ const context = Object.freeze({
78
+ challenge: snapshot(challenge),
79
+ ...(signal ? { signal } : {}),
80
+ });
81
+ const plan = Object.freeze({ requirement });
82
+ issued.add(plan);
83
+ const settlement = once((await authorize?.(plan, context)) ?? undefined);
84
+ try {
85
+ for (const funder of funders) {
86
+ signal?.throwIfAborted();
87
+ await funder.fund(requirement, context);
88
+ }
89
+ signal?.throwIfAborted();
90
+ if (identity(challenge) !== key)
91
+ throw new Error('Cannot check spending limits: the challenge changed while checked.');
92
+ // `authorize` and the funders can outlast the challenge: never sign an expired one.
93
+ if (challenge.expires)
94
+ Expires.assert(challenge.expires, challenge.id);
95
+ }
96
+ catch (error) {
97
+ settlement.release();
98
+ throw error;
99
+ }
100
+ return Object.freeze({
101
+ settlement,
102
+ constraints: constraints(false),
103
+ });
104
+ }
105
+ : undefined,
106
+ };
107
+ function constraints(resume) {
108
+ const value = Object.freeze({ limit, resume });
109
+ scopes.set(value, authorize);
110
+ return value;
111
+ }
112
+ }
113
+ /**
114
+ * Whether a credential checked under `constraints` shares a signing that a payment under the
115
+ * same `authorize` started and already counted, such as concurrent requests for one Tempo
116
+ * challenge. A payment that resumed, or released its reservation, counted nothing, so a
117
+ * credential sharing its signing is counted itself.
118
+ */
119
+ function sharesSigning(constraints) {
120
+ const owner = SpendHooks.owner(constraints);
121
+ return (owner !== undefined &&
122
+ counted.has(owner) &&
123
+ scopes.has(owner) &&
124
+ scopes.get(owner) === scopes.get(constraints));
125
+ }
126
+ /** Whether a config sets any spending option. */
127
+ export function configured(config) {
128
+ return (config !== undefined &&
129
+ (config.maxPayment !== undefined ||
130
+ config.authorize !== undefined ||
131
+ (config.funders !== undefined && config.funders.length > 0) ||
132
+ config.tokens !== undefined));
133
+ }
134
+ /** The spending options of `config`, without its other fields. */
135
+ export function pick(config) {
136
+ const { authorize, funders, maxPayment, tokens } = config;
137
+ return {
138
+ ...(authorize !== undefined && { authorize }),
139
+ ...(funders !== undefined && { funders }),
140
+ ...(maxPayment !== undefined && { maxPayment }),
141
+ ...(tokens !== undefined && { tokens }),
142
+ };
143
+ }
144
+ /**
145
+ * The spending options a fetch built on `inner`'s mppx fetch uses: its own, else the ones
146
+ * `inner` was built with, so rewrapping a limited fetch never drops its limits. Throws when both
147
+ * set some, since neither set may silently replace the other.
148
+ */
149
+ export function inherit(config, inner) {
150
+ if (!configured(inner))
151
+ return pick(config);
152
+ if (configured(config))
153
+ throw new TypeError('The fetch passed in already has spending options (maxPayment, authorize, funders or tokens). Set them on one fetch only.');
154
+ return inner;
155
+ }
156
+ /** Whether mppx issued `plan`, so its currency and decimals come from client configuration. */
157
+ export function isIssued(plan) {
158
+ return typeof plan === 'object' && plan !== null && issued.has(plan);
159
+ }
160
+ /**
161
+ * Commits `settlement` once `credential` is created, and releases it when creation fails. An
162
+ * error after which funds may have moved commits instead, so limits never undercount.
163
+ */
164
+ export function track(credential, settlement) {
165
+ if (!settlement)
166
+ return credential;
167
+ return credential.then((value) => {
168
+ settlement.commit();
169
+ return value;
170
+ }, (error) => {
171
+ if (error instanceof ZoneSettlementPendingError ||
172
+ error instanceof BroadcastOutcomeUnknownError ||
173
+ FundsMoved.has(error))
174
+ settlement.commit();
175
+ else
176
+ settlement.release();
177
+ throw error;
178
+ });
179
+ }
180
+ /**
181
+ * Starts one payment for `challenge`, which `method` signs. Its credential is mppx's own or one
182
+ * an event handler or `onChallenge` returns instead; either way `authorize` and the funders run
183
+ * at most once for it.
184
+ */
185
+ export function payment(spender, challenge, signal, method) {
186
+ let prepared;
187
+ // Whether mppx's own credential committed the reservation.
188
+ let used = false;
189
+ // Settles when the credential mppx is creating does.
190
+ let creating;
191
+ const prepare = () => (prepared ??= Promise.resolve(spender.prepare?.(challenge, { method, signal })));
192
+ const commit = async () => {
193
+ if (!spender.prepare)
194
+ return;
195
+ // A canceled request sends nothing, so its reservation is released instead.
196
+ signal?.throwIfAborted();
197
+ const own = used ? undefined : await prepare();
198
+ if (own && !own.constraints.resume)
199
+ return own.settlement.commit();
200
+ (await spender.prepare(challenge, { signal })).settlement.commit();
201
+ };
202
+ const release = async () => {
203
+ await creating;
204
+ (await prepared?.catch(() => undefined))?.settlement.release();
205
+ };
206
+ return {
207
+ prepare,
208
+ async track(create) {
209
+ const own = await prepare();
210
+ // The request may have been canceled since its payment was prepared: sign nothing.
211
+ if (own && signal?.aborted) {
212
+ own.settlement.release();
213
+ signal.throwIfAborted();
214
+ }
215
+ // A prepared payment can be signed long after its checks: never sign an expired challenge.
216
+ if (own && !own.constraints.resume && challenge.expires)
217
+ try {
218
+ Expires.assert(challenge.expires, challenge.id);
219
+ }
220
+ catch (error) {
221
+ own.settlement.release();
222
+ throw error;
223
+ }
224
+ const credential = track(create(own?.constraints), own && {
225
+ commit() {
226
+ used = true;
227
+ // A signing another payment under this authorization started is counted there.
228
+ if (sharesSigning(own.constraints))
229
+ own.settlement.release();
230
+ else {
231
+ own.settlement.commit();
232
+ if (!own.constraints.resume)
233
+ counted.add(own.constraints);
234
+ }
235
+ },
236
+ release() { },
237
+ });
238
+ creating = credential.then(() => { }, () => { });
239
+ return credential;
240
+ },
241
+ commit,
242
+ async commitReplacement(credential, offered) {
243
+ if (!spender.prepare)
244
+ return undefined;
245
+ const paid = replacedChallenge(credential, offered);
246
+ if (!paid)
247
+ throw unbound(spender);
248
+ if (tryIdentity(paid) === tryIdentity(challenge)) {
249
+ await commit();
250
+ return paid;
251
+ }
252
+ // It pays another offer: free the selected one's reservation and check that offer instead.
253
+ await release();
254
+ await payment(spender, paid, signal).commit();
255
+ return paid;
256
+ },
257
+ release,
258
+ };
259
+ }
260
+ /**
261
+ * Identifies a challenge by everything its ID binds (realm, method, intent, request, expiry,
262
+ * digest and opaque data) and the ID itself, so two offers that share an ID stay apart.
263
+ */
264
+ export function identity(challenge) {
265
+ const { digest, expires, id, intent, meta, method, opaque, realm, request } = challenge;
266
+ return JSON.stringify([
267
+ x402_ChallengeBrand.is(challenge),
268
+ id,
269
+ realm,
270
+ method,
271
+ intent,
272
+ PaymentRequest.serialize(request),
273
+ expires ?? null,
274
+ digest ?? null,
275
+ opaque ?? (meta !== undefined ? PaymentRequest.serialize(meta) : null),
276
+ ]);
277
+ }
278
+ function tryIdentity(challenge) {
279
+ try {
280
+ return identity(challenge);
281
+ }
282
+ catch {
283
+ return undefined;
284
+ }
285
+ }
286
+ /**
287
+ * The one offered challenge a credential pays: the MPP challenge its echo repeats exactly, or the
288
+ * x402 offer whose requirements its x402 payload accepts and signs. `undefined` when it cannot be
289
+ * read, or matches no offer or several.
290
+ */
291
+ export function replacedChallenge(credential, offered) {
292
+ const matches = mppOffers(credential, offered) ?? x402Offers(credential, offered);
293
+ return matches?.length === 1 ? matches[0] : undefined;
294
+ }
295
+ /** MPP offers an MPP credential echoes, or `undefined` when it is no MPP credential. */
296
+ function mppOffers(credential, offered) {
297
+ let echoed;
298
+ try {
299
+ echoed = Credential.deserialize(credential).challenge;
300
+ }
301
+ catch {
302
+ return undefined;
303
+ }
304
+ const key = tryIdentity(echoed);
305
+ if (key === undefined)
306
+ return [];
307
+ return offered.filter((challenge) => tryIdentity(challenge) === key);
308
+ }
309
+ /** x402 offers an x402 `PAYMENT-SIGNATURE` payload pays, or `undefined` when it is none. */
310
+ function x402Offers(credential, offered) {
311
+ let payload;
312
+ try {
313
+ payload = x402_Header.decodePaymentSignature(credential);
314
+ }
315
+ catch {
316
+ return undefined;
317
+ }
318
+ return offered.filter((challenge) => x402_ChallengeBrand.is(challenge) && paysX402(payload, challenge));
319
+ }
320
+ /**
321
+ * Whether an x402 payload pays an x402 offer: it accepts exactly the offer's requirements, and
322
+ * its signed transfer moves the required amount of the required asset to the required payee.
323
+ */
324
+ function paysX402(payload, challenge) {
325
+ const parsed = x402_Types.PaymentRequirementsSchema.safeParse(challenge.request);
326
+ if (!parsed.success)
327
+ return false;
328
+ const required = parsed.data;
329
+ try {
330
+ if (PaymentRequest.serialize(required) !== PaymentRequest.serialize(payload.accepted))
331
+ return false;
332
+ const amount = BigInt(required.amount);
333
+ const signed = payload.payload;
334
+ if ('authorization' in signed)
335
+ return (sameAddress(signed.authorization.to, required.payTo) &&
336
+ BigInt(signed.authorization.value) === amount);
337
+ const { permitted, witness } = signed.permit2Authorization;
338
+ return (sameAddress(permitted.token, required.asset) &&
339
+ BigInt(permitted.amount) === amount &&
340
+ sameAddress(witness.to, required.payTo));
341
+ }
342
+ catch {
343
+ return false;
344
+ }
345
+ }
346
+ function sameAddress(a, b) {
347
+ return a.toLowerCase() === b.toLowerCase();
348
+ }
349
+ /** Refuses a credential whose payment cannot be bound to an offered challenge. */
350
+ function unbound(spender) {
351
+ return new PaymentLimitExceededError({
352
+ limit: spender.limit,
353
+ reason: 'credential',
354
+ });
355
+ }
356
+ /** A deeply frozen copy of `challenge`, keeping its x402 origin. */
357
+ function snapshot(challenge) {
358
+ let copy;
359
+ try {
360
+ copy = structuredClone(challenge);
361
+ }
362
+ catch {
363
+ copy = JSON.parse(JSON.stringify(challenge));
364
+ }
365
+ if (x402_ChallengeBrand.is(challenge))
366
+ x402_ChallengeBrand.mark(copy);
367
+ return deepFreeze(copy);
368
+ }
369
+ function deepFreeze(value) {
370
+ if (!value || typeof value !== 'object' || Object.isFrozen(value))
371
+ return value;
372
+ Object.freeze(value);
373
+ for (const child of Object.values(value))
374
+ deepFreeze(child);
375
+ return value;
376
+ }
377
+ /** Key identifying an asset on a network; EVM addresses and Stripe currencies match in any case. */
378
+ export function assetKey(network, asset) {
379
+ const canonical = /^0x[\da-fA-F]{40}$/.test(asset) || network === 'stripe' ? asset.toLowerCase() : asset;
380
+ return JSON.stringify([network, canonical]);
381
+ }
382
+ /**
383
+ * Parses a non-negative decimal into units at `decimals` places without floating point.
384
+ * Digits beyond `decimals` are dropped, which only lowers a limit.
385
+ */
386
+ export function parseUnits(value, decimals) {
387
+ const [, integer = '0', fraction = ''] = decimalPattern.exec(value) ?? [];
388
+ return BigInt(`${integer}${fraction.slice(0, decimals).padEnd(decimals, '0')}`);
389
+ }
390
+ /** Rejects a `Money` value that is not a non-negative decimal in a named currency. */
391
+ export function assertMoney(money, name) {
392
+ const { currency, value } = (money ?? {});
393
+ if (typeof currency !== 'string' || !currency.trim())
394
+ throw new TypeError(`${name} currency must be a non-empty string.`);
395
+ if (typeof value !== 'string' || value.length > maxDecimalLength || !decimalPattern.test(value))
396
+ throw new TypeError(`${name} value must be a non-negative decimal string.`);
397
+ }
398
+ /** Whether a value is an {@link Spend.AssetLimit}. */
399
+ export function isAssetLimit(value) {
400
+ if (typeof value !== 'object' || value === null)
401
+ return false;
402
+ const { amount, asset, network } = value;
403
+ return (typeof network === 'string' &&
404
+ network.length > 0 &&
405
+ typeof asset === 'string' &&
406
+ asset.length > 0 &&
407
+ typeof amount === 'bigint' &&
408
+ amount >= 0n);
409
+ }
410
+ function assertMaxPayment(maxPayment) {
411
+ if (!Array.isArray(maxPayment))
412
+ return assertMoney(maxPayment, 'maxPayment');
413
+ const keys = new Set();
414
+ for (const limit of maxPayment) {
415
+ if (!isAssetLimit(limit))
416
+ throw new TypeError('Each maxPayment limit needs a network, an asset and a bigint amount.');
417
+ const key = assetKey(limit.network, limit.asset);
418
+ if (keys.has(key))
419
+ throw new TypeError(`Duplicate maxPayment limit for ${limit.asset}.`);
420
+ keys.add(key);
421
+ }
422
+ }
423
+ function assertWithin(requirement, maxPayment) {
424
+ const refuse = (reason) => new PaymentLimitExceededError({ limit: 'maxPayment', reason });
425
+ if (Array.isArray(maxPayment)) {
426
+ const key = assetKey(requirement.network, requirement.asset);
427
+ const limit = maxPayment.find((limit) => assetKey(limit.network, limit.asset) === key);
428
+ if (!limit)
429
+ throw refuse('asset');
430
+ if (requirement.amount > limit.amount)
431
+ throw refuse('amount');
432
+ return;
433
+ }
434
+ const money = maxPayment;
435
+ // Set only from client configuration, never from the challenge.
436
+ const { currency, decimals } = requirement;
437
+ if (currency === undefined || decimals === undefined)
438
+ throw refuse('asset');
439
+ if (currency.toUpperCase() !== money.currency.toUpperCase())
440
+ throw refuse('asset');
441
+ if (requirement.amount > parseUnits(money.value, decimals))
442
+ throw refuse('amount');
443
+ }
444
+ /**
445
+ * Normalizes a selected challenge. Currency and decimals come only from `tokens`: a server
446
+ * that names another currency, or sends fewer decimals, cannot change what a limit counts.
447
+ */
448
+ function requirement(challenge, tokens) {
449
+ const fields = x402_ChallengeBrand.is(challenge) ? x402Fields(challenge) : mppFields(challenge);
450
+ const token = tokens.get(assetKey(fields.network, fields.asset));
451
+ const value = {
452
+ method: challenge.method,
453
+ intent: challenge.intent,
454
+ ...fields,
455
+ ...(token ? { currency: token.currency, decimals: token.decimals } : {}),
456
+ };
457
+ // Amounts are bigints, which JSON cannot hold: serialize them as decimal strings.
458
+ Object.defineProperty(value, 'toJSON', { value: requirementJson });
459
+ return Object.freeze(value);
460
+ }
461
+ function requirementJson() {
462
+ return {
463
+ ...this,
464
+ amount: this.amount.toString(),
465
+ ...(this.splits && {
466
+ splits: this.splits.map((split) => ({ ...split, amount: split.amount.toString() })),
467
+ }),
468
+ };
469
+ }
470
+ function x402Fields(challenge) {
471
+ const parsed = x402_Types.PaymentRequirementsSchema.safeParse(challenge.request);
472
+ if (!parsed.success)
473
+ throw new Error('Cannot check spending limits: invalid x402 requirements.');
474
+ const { amount, asset, network, payTo } = parsed.data;
475
+ return {
476
+ protocol: 'x402',
477
+ network,
478
+ asset,
479
+ amount: atomicAmount(amount),
480
+ recipient: payTo,
481
+ };
482
+ }
483
+ function mppFields(challenge) {
484
+ const request = challenge.request;
485
+ const details = (typeof request.methodDetails === 'object' && request.methodDetails !== null
486
+ ? request.methodDetails
487
+ : {});
488
+ // Methods sign on `methodDetails.chainId` and ignore a top-level `chainId`, so only the former
489
+ // names the network. A top-level one it does not match could mean another chain: refuse it.
490
+ const chainId = details.chainId;
491
+ if (chainId !== undefined && (!Number.isSafeInteger(chainId) || chainId <= 0))
492
+ throw new Error('Cannot check spending limits: invalid challenge chain ID.');
493
+ if (request.chainId !== undefined && request.chainId !== chainId)
494
+ throw new Error('Cannot check spending limits: challenge names a chain outside methodDetails.chainId.');
495
+ const asset = request.currency;
496
+ if (typeof asset !== 'string' || !asset)
497
+ throw new Error('Cannot check spending limits: challenge names no currency.');
498
+ const amount = atomicAmount(request.amount);
499
+ const recipient = payee(challenge.method, request, details);
500
+ const splits = paymentSplits(details.splits, amount);
501
+ return {
502
+ protocol: 'mpp',
503
+ network: chainId === undefined ? challenge.method : `eip155:${chainId}`,
504
+ asset,
505
+ amount,
506
+ ...(recipient !== undefined ? { recipient } : {}),
507
+ ...(splits ? { splits } : {}),
508
+ };
509
+ }
510
+ /**
511
+ * The payee a credential authorizes. Stripe creates its Shared Payment Token for
512
+ * `methodDetails.networkId` and ignores `recipient`, so for Stripe that is the payee.
513
+ */
514
+ function payee(method, request, details) {
515
+ if (method === 'stripe') {
516
+ if (typeof details.networkId !== 'string' || !details.networkId)
517
+ throw new Error('Cannot check spending limits: Stripe challenge names no networkId.');
518
+ return details.networkId;
519
+ }
520
+ return typeof request.recipient === 'string' ? request.recipient : undefined;
521
+ }
522
+ /** Split payees and their shares, which a Tempo charge pays out of `amount`. */
523
+ function paymentSplits(value, amount) {
524
+ if (value === undefined)
525
+ return undefined;
526
+ if (!Array.isArray(value) || value.length === 0)
527
+ throw new Error('Cannot check spending limits: invalid payment splits.');
528
+ let total = 0n;
529
+ const splits = value.map((split) => {
530
+ const { amount, recipient } = (split ?? {});
531
+ if (typeof recipient !== 'string' || !recipient)
532
+ throw new Error('Cannot check spending limits: payment split names no recipient.');
533
+ const share = atomicAmount(amount);
534
+ total += share;
535
+ return Object.freeze({ recipient, amount: share });
536
+ });
537
+ // The signer refuses splits that leave the primary recipient nothing.
538
+ if (total >= amount)
539
+ throw new Error('Cannot check spending limits: payment splits are not less than the amount.');
540
+ return Object.freeze(splits);
541
+ }
542
+ /** Parses an atomic amount as the signers do: any string of digits, leading zeroes included. */
543
+ function atomicAmount(value) {
544
+ if (typeof value !== 'string' || !/^\d+$/.test(value))
545
+ throw new Error('Cannot check spending limits: challenge amount is not an atomic integer.');
546
+ return BigInt(value);
547
+ }
548
+ /** Built-in tokens, then configured ones, keyed by {@link assetKey}; configured ones win. */
549
+ function tokenMetadata(tokens) {
550
+ const metadata = new Map();
551
+ for (const token of builtinTokens)
552
+ for (const chainId of tempoChainIds) {
553
+ const address = token.addresses[chainId];
554
+ if (address)
555
+ metadata.set(assetKey(`eip155:${chainId}`, address), {
556
+ currency: token.currency,
557
+ decimals: token.decimals,
558
+ });
559
+ }
560
+ for (const { asset, currency, decimals, network } of stripeTokens)
561
+ metadata.set(assetKey(network, asset), { currency, decimals });
562
+ if (tokens === undefined)
563
+ return metadata;
564
+ if (!Array.isArray(tokens))
565
+ throw new TypeError('tokens must be an array.');
566
+ const configured = new Map();
567
+ for (const token of tokens) {
568
+ const { currency, decimals } = (token ?? {});
569
+ if (typeof currency !== 'string' || !currency.trim())
570
+ throw new TypeError('Each token needs a currency, such as USD.');
571
+ if (typeof decimals !== 'number' ||
572
+ !Number.isInteger(decimals) ||
573
+ decimals < 0 ||
574
+ decimals > 255)
575
+ throw new TypeError('Token decimals must be an integer from 0 to 255.');
576
+ const entries = typeof token === 'function'
577
+ ? Object.entries(token.addresses).map(([chainId, address]) => [Number(chainId), address])
578
+ : [[token.chainId, token.address]];
579
+ for (const [chainId, address] of entries) {
580
+ if (!Number.isSafeInteger(chainId) || chainId <= 0 || typeof address !== 'string' || !address)
581
+ throw new TypeError('Each token needs an address and a chain ID.');
582
+ const key = assetKey(`eip155:${chainId}`, address);
583
+ const existing = configured.get(key);
584
+ if (existing &&
585
+ (existing.currency.toUpperCase() !== currency.toUpperCase() ||
586
+ existing.decimals !== decimals))
587
+ throw new TypeError(`tokens configure conflicting metadata for ${address}.`);
588
+ configured.set(key, Object.freeze({ currency, decimals }));
589
+ }
590
+ }
591
+ for (const [key, value] of configured)
592
+ metadata.set(key, value);
593
+ return metadata;
594
+ }
595
+ function once(authorization) {
596
+ let open = true;
597
+ const close = (settle) => {
598
+ if (!open)
599
+ return;
600
+ open = false;
601
+ settle?.call(authorization);
602
+ };
603
+ return Object.freeze({
604
+ commit: () => close(authorization?.commit),
605
+ release: () => close(authorization?.release),
606
+ });
607
+ }
608
+ //# sourceMappingURL=SpendGate.js.map
@@ -0,0 +1,42 @@
1
+ import type * as Challenge from '../../Challenge.js';
2
+ import type * as Method from '../../Method.js';
3
+ /** Checks a client method adds to the client's spending options, without changing its shape. */
4
+ export type Hooks = {
5
+ /**
6
+ * Throws when the method's own policy refuses `challenge`, so authorization and funders never
7
+ * run for an offer the method would not sign.
8
+ */
9
+ assert?: ((challenge: Challenge.Challenge) => void) | undefined;
10
+ /**
11
+ * Whether a credential for `challenge` resumes a payment the method already made, such as an
12
+ * outstanding Zone withdrawal, which the spending options counted when it started.
13
+ */
14
+ resumes?: ((challenge: Challenge.Challenge) => boolean) | undefined;
15
+ };
16
+ /** How the client's spending options constrain one credential the method creates. */
17
+ export type Constraints = Readonly<{
18
+ /** The limit a refusal names: `maxPayment` when it is set, else `budget`. */
19
+ limit: 'maxPayment' | 'budget';
20
+ /**
21
+ * Whether the credential may only resume the payment {@link Hooks.resumes} found. Its spending
22
+ * checks were skipped, so a new payment must not start.
23
+ */
24
+ resume: boolean;
25
+ }>;
26
+ /** Registers a method's spending hooks. */
27
+ export declare function register<const method extends Method.AnyClient>(method: method, value: Hooks): method;
28
+ /** Returns a method's spending hooks, when it registered any. */
29
+ export declare function get(method: Method.AnyClient): Hooks | undefined;
30
+ /** Marks credential parameters as created under the client's spending options. */
31
+ export declare function constrain(parameters: object, value: Constraints): void;
32
+ /** Returns the spending constraints of credential parameters, when spending options apply. */
33
+ export declare function of(parameters: object): Constraints | undefined;
34
+ /**
35
+ * Records which in-flight signing the latest call checked under `joiner` returns: one another
36
+ * call, checked under `owner`, started, which the client's spending options count once, or, with
37
+ * no `owner`, one it started itself, such as when it resumes a Zone payment, which it counts.
38
+ */
39
+ export declare function join(joiner: Constraints, owner: Constraints | undefined): void;
40
+ /** The constraints of the credential whose signing one checked under `joiner` shares, if any. */
41
+ export declare function owner(joiner: Constraints): Constraints | undefined;
42
+ //# sourceMappingURL=SpendHooks.d.ts.map
@@ -0,0 +1,36 @@
1
+ const hooks = new WeakMap();
2
+ const constraints = new WeakMap();
3
+ const owners = new WeakMap();
4
+ /** Registers a method's spending hooks. */
5
+ export function register(method, value) {
6
+ hooks.set(method, value);
7
+ return method;
8
+ }
9
+ /** Returns a method's spending hooks, when it registered any. */
10
+ export function get(method) {
11
+ return hooks.get(method);
12
+ }
13
+ /** Marks credential parameters as created under the client's spending options. */
14
+ export function constrain(parameters, value) {
15
+ constraints.set(parameters, value);
16
+ }
17
+ /** Returns the spending constraints of credential parameters, when spending options apply. */
18
+ export function of(parameters) {
19
+ return constraints.get(parameters);
20
+ }
21
+ /**
22
+ * Records which in-flight signing the latest call checked under `joiner` returns: one another
23
+ * call, checked under `owner`, started, which the client's spending options count once, or, with
24
+ * no `owner`, one it started itself, such as when it resumes a Zone payment, which it counts.
25
+ */
26
+ export function join(joiner, owner) {
27
+ if (owner === undefined || owner === joiner)
28
+ owners.delete(joiner);
29
+ else
30
+ owners.set(joiner, owner);
31
+ }
32
+ /** The constraints of the credential whose signing one checked under `joiner` shares, if any. */
33
+ export function owner(joiner) {
34
+ return owners.get(joiner);
35
+ }
36
+ //# sourceMappingURL=SpendHooks.js.map