mppx 0.3.11 → 0.3.12

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 (40) hide show
  1. package/dist/client/Mppx.d.ts +1 -1
  2. package/dist/client/Mppx.d.ts.map +1 -1
  3. package/dist/client/internal/Fetch.d.ts +1 -1
  4. package/dist/client/internal/Fetch.d.ts.map +1 -1
  5. package/dist/client/internal/Fetch.js +23 -4
  6. package/dist/client/internal/Fetch.js.map +1 -1
  7. package/dist/tempo/client/Charge.d.ts +10 -0
  8. package/dist/tempo/client/Charge.d.ts.map +1 -1
  9. package/dist/tempo/client/Charge.js +23 -9
  10. package/dist/tempo/client/Charge.js.map +1 -1
  11. package/dist/tempo/client/Methods.d.ts +1 -0
  12. package/dist/tempo/client/Methods.d.ts.map +1 -1
  13. package/dist/tempo/internal/auto-swap.d.ts +49 -0
  14. package/dist/tempo/internal/auto-swap.d.ts.map +1 -0
  15. package/dist/tempo/internal/auto-swap.js +89 -0
  16. package/dist/tempo/internal/auto-swap.js.map +1 -0
  17. package/dist/tempo/internal/fee-payer.d.ts +15 -0
  18. package/dist/tempo/internal/fee-payer.d.ts.map +1 -0
  19. package/dist/tempo/internal/fee-payer.js +41 -0
  20. package/dist/tempo/internal/fee-payer.js.map +1 -0
  21. package/dist/tempo/internal/selectors.d.ts +5 -0
  22. package/dist/tempo/internal/selectors.d.ts.map +1 -0
  23. package/dist/tempo/internal/selectors.js +7 -0
  24. package/dist/tempo/internal/selectors.js.map +1 -0
  25. package/dist/tempo/server/Charge.d.ts.map +1 -1
  26. package/dist/tempo/server/Charge.js +8 -6
  27. package/dist/tempo/server/Charge.js.map +1 -1
  28. package/package.json +1 -1
  29. package/src/client/Mppx.test-d.ts +28 -0
  30. package/src/client/Mppx.ts +3 -3
  31. package/src/client/internal/Fetch.test.ts +410 -0
  32. package/src/client/internal/Fetch.ts +25 -7
  33. package/src/tempo/client/Charge.ts +40 -9
  34. package/src/tempo/internal/auto-swap.test.ts +113 -0
  35. package/src/tempo/internal/auto-swap.ts +141 -0
  36. package/src/tempo/internal/fee-payer.test.ts +223 -0
  37. package/src/tempo/internal/fee-payer.ts +53 -0
  38. package/src/tempo/internal/selectors.ts +10 -0
  39. package/src/tempo/server/Charge.test.ts +374 -3
  40. package/src/tempo/server/Charge.ts +9 -18
@@ -2,6 +2,8 @@ import type { Account } from 'viem'
2
2
  import { describe, expectTypeOf, test } from 'vitest'
3
3
  import * as Method from '../Method.js'
4
4
  import { charge } from '../tempo/client/Charge.js'
5
+ import { tempo } from '../tempo/client/Methods.js'
6
+ import type * as AutoSwap from '../tempo/internal/auto-swap.js'
5
7
  import * as Methods from '../tempo/Methods.js'
6
8
  import * as z from '../zod.js'
7
9
  import * as Mppx from './Mppx.js'
@@ -88,3 +90,29 @@ describe('Mppx with context', () => {
88
90
  expectTypeOf(mppx.createCredential).returns.toMatchTypeOf<Promise<string>>()
89
91
  })
90
92
  })
93
+
94
+ describe('fetch context', () => {
95
+ test('context has typed account and autoSwap for tempo charge', () => {
96
+ const mppx = Mppx.create({ methods: [charge()] })
97
+
98
+ type FetchInit = NonNullable<Parameters<typeof mppx.fetch>[1]>
99
+ type Context = NonNullable<FetchInit['context']>
100
+
101
+ expectTypeOf<Context>().toHaveProperty('account')
102
+ expectTypeOf<Context>().toHaveProperty('autoSwap')
103
+
104
+ expectTypeOf<Context['autoSwap']>().toEqualTypeOf<AutoSwap.resolve.Value | undefined>()
105
+ })
106
+
107
+ test('context has typed account and autoSwap for tempo()', () => {
108
+ const mppx = Mppx.create({ methods: [tempo()] })
109
+
110
+ type FetchInit = NonNullable<Parameters<typeof mppx.fetch>[1]>
111
+ type Context = NonNullable<FetchInit['context']>
112
+
113
+ // Context is a union of charge and session contexts.
114
+ // `account` exists on both; `autoSwap` only on charge.
115
+ expectTypeOf<Context>().toHaveProperty('account')
116
+ expectTypeOf<Extract<Context, { autoSwap?: unknown }>>().toHaveProperty('autoSwap')
117
+ })
118
+ })
@@ -142,9 +142,9 @@ export declare namespace create {
142
142
  * @internal
143
143
  */
144
144
  type AnyContextFor<methods extends readonly Method.AnyClient[]> = {
145
- [method in keyof methods]: methods[method] extends Method.Client<any, infer context>
146
- ? context extends z.ZodMiniType
147
- ? z.input<context>
145
+ [method in keyof methods]: NonNullable<methods[method]['context']> extends infer ctx
146
+ ? ctx extends z.ZodMiniType
147
+ ? z.input<ctx>
148
148
  : undefined
149
149
  : undefined
150
150
  }[number]
@@ -268,6 +268,374 @@ describe('Fetch.from', () => {
268
268
  })
269
269
  })
270
270
 
271
+ // Minimal mock method — createCredential is only invoked on the 402 retry path.
272
+ const noopMethod = {
273
+ name: 'test',
274
+ intent: 'test',
275
+ context: undefined,
276
+ createCredential: async () => 'credential',
277
+ } as any
278
+
279
+ /** Builds a valid 402 response with a WWW-Authenticate header. */
280
+ function make402(overrides?: { method?: string; intent?: string }) {
281
+ const method = overrides?.method ?? 'test'
282
+ const intent = overrides?.intent ?? 'test'
283
+ const request = btoa(JSON.stringify({ amount: '1' }))
284
+ .replace(/\+/g, '-')
285
+ .replace(/\//g, '_')
286
+ .replace(/=+$/, '')
287
+ const header = `Payment id="abc", realm="test", method="${method}", intent="${intent}", request="${request}"`
288
+ return new Response(null, {
289
+ status: 402,
290
+ headers: { 'WWW-Authenticate': header },
291
+ })
292
+ }
293
+
294
+ describe('Fetch.from: init passthrough (non-402)', () => {
295
+ test('passes unmodified init to underlying fetch for non-402 responses', async () => {
296
+ const receivedInits: (RequestInit | undefined)[] = []
297
+ const mockFetch: typeof globalThis.fetch = async (_input, init) => {
298
+ receivedInits.push(init)
299
+ return new Response('OK', { status: 200 })
300
+ }
301
+
302
+ const fetch = Fetch.from({
303
+ fetch: mockFetch,
304
+ methods: [noopMethod],
305
+ })
306
+
307
+ const customInit = {
308
+ method: 'POST',
309
+ headers: { 'X-Custom': 'value' },
310
+ body: JSON.stringify({ data: 'test' }),
311
+ }
312
+
313
+ await fetch('https://example.com/ws-upgrade', customInit)
314
+
315
+ expect(receivedInits[0]).toBe(customInit)
316
+ })
317
+
318
+ test('preserves extra properties on init for non-402 responses', async () => {
319
+ const receivedInits: (RequestInit | undefined)[] = []
320
+ const mockFetch: typeof globalThis.fetch = async (_input, init) => {
321
+ receivedInits.push(init)
322
+ return new Response('OK', { status: 200 })
323
+ }
324
+
325
+ const fetch = Fetch.from({
326
+ fetch: mockFetch,
327
+ methods: [noopMethod],
328
+ })
329
+
330
+ const customInit = {
331
+ method: 'GET',
332
+ headers: { Authorization: 'Bearer token123' },
333
+ signal: AbortSignal.timeout(5000),
334
+ }
335
+
336
+ await fetch('https://example.com/api', customInit)
337
+
338
+ const received = receivedInits[0]!
339
+ expect(received.method).toBe('GET')
340
+ expect((received.headers as Record<string, string>).Authorization).toBe('Bearer token123')
341
+ expect(received.signal).toBe(customInit.signal)
342
+ })
343
+
344
+ test('passes through undefined init', async () => {
345
+ const receivedInits: (RequestInit | undefined)[] = []
346
+ const mockFetch: typeof globalThis.fetch = async (_input, init) => {
347
+ receivedInits.push(init)
348
+ return new Response('OK', { status: 200 })
349
+ }
350
+
351
+ const fetch = Fetch.from({
352
+ fetch: mockFetch,
353
+ methods: [noopMethod],
354
+ })
355
+
356
+ await fetch('https://example.com/api')
357
+ expect(receivedInits[0]).toBeUndefined()
358
+ })
359
+
360
+ test('passes init with context through untouched', async () => {
361
+ const receivedInits: (RequestInit | undefined)[] = []
362
+ const mockFetch: typeof globalThis.fetch = async (_input, init) => {
363
+ receivedInits.push(init)
364
+ return new Response('OK', { status: 200 })
365
+ }
366
+
367
+ const fetch = Fetch.from({
368
+ fetch: mockFetch,
369
+ methods: [noopMethod],
370
+ })
371
+
372
+ const customInit = { method: 'POST', context: { account: '0xabc' } }
373
+ await fetch('https://example.com/api', customInit as any)
374
+
375
+ expect(receivedInits[0]).toBe(customInit)
376
+ })
377
+
378
+ test('preserves object identity across all non-402 status codes', async () => {
379
+ for (const status of [200, 201, 204, 301, 400, 401, 403, 404, 500, 503]) {
380
+ const receivedInits: (RequestInit | undefined)[] = []
381
+ const mockFetch: typeof globalThis.fetch = async (_input, init) => {
382
+ receivedInits.push(init)
383
+ return new Response(null, { status })
384
+ }
385
+
386
+ const fetch = Fetch.from({
387
+ fetch: mockFetch,
388
+ methods: [noopMethod],
389
+ })
390
+
391
+ const customInit = { method: 'GET' }
392
+ await fetch('https://example.com/api', customInit)
393
+ expect(receivedInits[0]).toBe(customInit)
394
+ }
395
+ })
396
+ })
397
+
398
+ describe('Fetch.from: 402 retry path', () => {
399
+ test('strips context from init on retry', async () => {
400
+ const calls: { init: RequestInit | undefined }[] = []
401
+ let callCount = 0
402
+ const mockFetch: typeof globalThis.fetch = async (_input, init) => {
403
+ calls.push({ init })
404
+ callCount++
405
+ if (callCount === 1) return make402()
406
+ return new Response('OK', { status: 200 })
407
+ }
408
+
409
+ const fetch = Fetch.from({
410
+ fetch: mockFetch,
411
+ methods: [noopMethod],
412
+ })
413
+
414
+ await fetch('https://example.com/api', {
415
+ method: 'POST',
416
+ context: { account: '0xabc' },
417
+ } as any)
418
+
419
+ expect(calls).toHaveLength(2)
420
+ const retryInit = calls[1]!.init as Record<string, unknown>
421
+ expect(retryInit).not.toHaveProperty('context')
422
+ })
423
+
424
+ test('adds Authorization header on retry', async () => {
425
+ let callCount = 0
426
+ const calls: { init: RequestInit | undefined }[] = []
427
+ const mockFetch: typeof globalThis.fetch = async (_input, init) => {
428
+ calls.push({ init })
429
+ callCount++
430
+ if (callCount === 1) return make402()
431
+ return new Response('OK', { status: 200 })
432
+ }
433
+
434
+ const fetch = Fetch.from({
435
+ fetch: mockFetch,
436
+ methods: [noopMethod],
437
+ })
438
+
439
+ await fetch('https://example.com/api')
440
+
441
+ const retryInit = calls[1]!.init as Record<string, unknown>
442
+ const headers = retryInit.headers as Record<string, string>
443
+ expect(headers.Authorization).toBe('credential')
444
+ })
445
+
446
+ test('preserves existing headers on retry', async () => {
447
+ let callCount = 0
448
+ const calls: { init: RequestInit | undefined }[] = []
449
+ const mockFetch: typeof globalThis.fetch = async (_input, init) => {
450
+ calls.push({ init })
451
+ callCount++
452
+ if (callCount === 1) return make402()
453
+ return new Response('OK', { status: 200 })
454
+ }
455
+
456
+ const fetch = Fetch.from({
457
+ fetch: mockFetch,
458
+ methods: [noopMethod],
459
+ })
460
+
461
+ await fetch('https://example.com/api', {
462
+ headers: { 'X-Custom': 'value', 'Content-Type': 'application/json' },
463
+ })
464
+
465
+ const retryInit = calls[1]!.init as Record<string, unknown>
466
+ const headers = retryInit.headers as Record<string, string>
467
+ expect(headers['X-Custom']).toBe('value')
468
+ expect(headers['Content-Type']).toBe('application/json')
469
+ expect(headers.Authorization).toBe('credential')
470
+ })
471
+
472
+ test('preserves method and other init properties on retry', async () => {
473
+ let callCount = 0
474
+ const calls: { init: RequestInit | undefined }[] = []
475
+ const mockFetch: typeof globalThis.fetch = async (_input, init) => {
476
+ calls.push({ init })
477
+ callCount++
478
+ if (callCount === 1) return make402()
479
+ return new Response('OK', { status: 200 })
480
+ }
481
+
482
+ const fetch = Fetch.from({
483
+ fetch: mockFetch,
484
+ methods: [noopMethod],
485
+ })
486
+
487
+ await fetch('https://example.com/api', {
488
+ method: 'PUT',
489
+ body: JSON.stringify({ data: 'test' }),
490
+ credentials: 'include',
491
+ mode: 'cors',
492
+ })
493
+
494
+ const retryInit = calls[1]!.init as Record<string, unknown>
495
+ expect(retryInit.method).toBe('PUT')
496
+ expect(retryInit.body).toBe(JSON.stringify({ data: 'test' }))
497
+ expect(retryInit.credentials).toBe('include')
498
+ expect(retryInit.mode).toBe('cors')
499
+ })
500
+
501
+ test('handles undefined init on 402 retry', async () => {
502
+ let callCount = 0
503
+ const calls: { init: RequestInit | undefined }[] = []
504
+ const mockFetch: typeof globalThis.fetch = async (_input, init) => {
505
+ calls.push({ init })
506
+ callCount++
507
+ if (callCount === 1) return make402()
508
+ return new Response('OK', { status: 200 })
509
+ }
510
+
511
+ const fetch = Fetch.from({
512
+ fetch: mockFetch,
513
+ methods: [noopMethod],
514
+ })
515
+
516
+ await fetch('https://example.com/api')
517
+
518
+ expect(calls).toHaveLength(2)
519
+ const retryInit = calls[1]!.init as Record<string, unknown>
520
+ expect(retryInit.headers).toEqual({ Authorization: 'credential' })
521
+ })
522
+
523
+ test('throws when no matching method for 402 challenge', async () => {
524
+ const mockFetch: typeof globalThis.fetch = async () =>
525
+ make402({ method: 'stripe', intent: 'charge' })
526
+
527
+ const fetch = Fetch.from({
528
+ fetch: mockFetch,
529
+ methods: [noopMethod],
530
+ })
531
+
532
+ await expect(fetch('https://example.com/api')).rejects.toThrow(
533
+ 'No method found for "stripe.charge"',
534
+ )
535
+ })
536
+
537
+ test('retries exactly once — does not loop on repeated 402', async () => {
538
+ let callCount = 0
539
+ const mockFetch: typeof globalThis.fetch = async () => {
540
+ callCount++
541
+ return make402()
542
+ }
543
+
544
+ const fetch = Fetch.from({
545
+ fetch: mockFetch,
546
+ methods: [noopMethod],
547
+ })
548
+
549
+ const response = await fetch('https://example.com/api')
550
+ expect(callCount).toBe(2)
551
+ expect(response.status).toBe(402)
552
+ })
553
+ })
554
+
555
+ describe('Fetch.from: 402 retry headers normalization', () => {
556
+ test('preserves headers when passed as a Headers instance', async () => {
557
+ let callCount = 0
558
+ const calls: { init: RequestInit | undefined }[] = []
559
+ const mockFetch: typeof globalThis.fetch = async (_input, init) => {
560
+ calls.push({ init })
561
+ callCount++
562
+ if (callCount === 1) return make402()
563
+ return new Response('OK', { status: 200 })
564
+ }
565
+
566
+ const fetch = Fetch.from({
567
+ fetch: mockFetch,
568
+ methods: [noopMethod],
569
+ })
570
+
571
+ const headers = new Headers({ 'X-Custom': 'value', 'Content-Type': 'application/json' })
572
+ await fetch('https://example.com/api', { headers })
573
+
574
+ const retryHeaders = (calls[1]!.init as Record<string, unknown>).headers as Record<
575
+ string,
576
+ string
577
+ >
578
+ expect(retryHeaders['x-custom']).toBe('value')
579
+ expect(retryHeaders['content-type']).toBe('application/json')
580
+ expect(retryHeaders.Authorization).toBe('credential')
581
+ })
582
+
583
+ test('preserves headers when passed as array of tuples', async () => {
584
+ let callCount = 0
585
+ const calls: { init: RequestInit | undefined }[] = []
586
+ const mockFetch: typeof globalThis.fetch = async (_input, init) => {
587
+ calls.push({ init })
588
+ callCount++
589
+ if (callCount === 1) return make402()
590
+ return new Response('OK', { status: 200 })
591
+ }
592
+
593
+ const fetch = Fetch.from({
594
+ fetch: mockFetch,
595
+ methods: [noopMethod],
596
+ })
597
+
598
+ await fetch('https://example.com/api', {
599
+ headers: [
600
+ ['X-Custom', 'value'],
601
+ ['Accept', 'application/json'],
602
+ ],
603
+ })
604
+
605
+ const retryHeaders = (calls[1]!.init as Record<string, unknown>).headers as Record<
606
+ string,
607
+ string
608
+ >
609
+ expect(retryHeaders['X-Custom']).toBe('value')
610
+ expect(retryHeaders.Accept).toBe('application/json')
611
+ expect(retryHeaders.Authorization).toBe('credential')
612
+ })
613
+ })
614
+
615
+ describe('Fetch.from: input passthrough', () => {
616
+ test('passes URL input through on both initial and retry calls', async () => {
617
+ let callCount = 0
618
+ const receivedInputs: (RequestInfo | URL)[] = []
619
+ const mockFetch: typeof globalThis.fetch = async (input, _init) => {
620
+ receivedInputs.push(input)
621
+ callCount++
622
+ if (callCount === 1) return make402()
623
+ return new Response('OK', { status: 200 })
624
+ }
625
+
626
+ const fetch = Fetch.from({
627
+ fetch: mockFetch,
628
+ methods: [noopMethod],
629
+ })
630
+
631
+ const url = new URL('https://example.com/resource')
632
+ await fetch(url)
633
+
634
+ expect(receivedInputs[0]).toBe(url)
635
+ expect(receivedInputs[1]).toBe(url)
636
+ })
637
+ })
638
+
271
639
  describe('Fetch.polyfill', () => {
272
640
  test('default', async () => {
273
641
  Fetch.polyfill({
@@ -313,3 +681,45 @@ describe('Fetch.polyfill', () => {
313
681
  Fetch.restore()
314
682
  })
315
683
  })
684
+
685
+ describe('Fetch.polyfill / restore', () => {
686
+ test('restore is a no-op when polyfill was never called', () => {
687
+ const before = globalThis.fetch
688
+ Fetch.restore()
689
+ expect(globalThis.fetch).toBe(before)
690
+ })
691
+
692
+ test('restore reverts to original fetch', () => {
693
+ const originalFetch = globalThis.fetch
694
+
695
+ Fetch.polyfill({ methods: [noopMethod] })
696
+ expect(globalThis.fetch).not.toBe(originalFetch)
697
+
698
+ Fetch.restore()
699
+ expect(globalThis.fetch).toBe(originalFetch)
700
+ })
701
+
702
+ test('stacked polyfill calls preserve the true original fetch', () => {
703
+ const originalFetch = globalThis.fetch
704
+
705
+ Fetch.polyfill({ methods: [noopMethod] })
706
+ const firstPolyfill = globalThis.fetch
707
+
708
+ Fetch.polyfill({ methods: [noopMethod] })
709
+ expect(globalThis.fetch).not.toBe(firstPolyfill)
710
+
711
+ Fetch.restore()
712
+ expect(globalThis.fetch).toBe(originalFetch)
713
+ })
714
+
715
+ test('double restore does not clobber fetch', () => {
716
+ const originalFetch = globalThis.fetch
717
+
718
+ Fetch.polyfill({ methods: [noopMethod] })
719
+ Fetch.restore()
720
+ expect(globalThis.fetch).toBe(originalFetch)
721
+
722
+ Fetch.restore()
723
+ expect(globalThis.fetch).toBe(originalFetch)
724
+ })
725
+ })
@@ -31,11 +31,15 @@ export function from<const methods extends readonly Method.AnyClient[]>(
31
31
  const { fetch = globalThis.fetch, methods, onChallenge } = config
32
32
 
33
33
  return async (input, init) => {
34
- const { context, ...fetchInit } = init ?? {}
35
- const response = await fetch(input, fetchInit)
34
+ // Pass init through untouched to preserve object identity for non-402 responses.
35
+ const response = await fetch(input, init)
36
36
 
37
37
  if (response.status !== 402) return response
38
38
 
39
+ // Only extract context for payment handling after confirming 402.
40
+ const context = (init as Record<string, unknown> | undefined)?.context
41
+ const { context: _, ...fetchInit } = (init ?? {}) as Record<string, unknown>
42
+
39
43
  const challenge = Challenge.fromResponse(response)
40
44
 
41
45
  const mi = methods.find((m) => m.name === challenge.method && m.intent === challenge.intent)
@@ -55,7 +59,7 @@ export function from<const methods extends readonly Method.AnyClient[]>(
55
59
  return fetch(input, {
56
60
  ...fetchInit,
57
61
  headers: {
58
- ...fetchInit.headers,
62
+ ...normalizeHeaders(fetchInit.headers),
59
63
  Authorization: credential,
60
64
  },
61
65
  })
@@ -64,9 +68,9 @@ export function from<const methods extends readonly Method.AnyClient[]>(
64
68
 
65
69
  /** Union of all context types from all methods that have context schemas. */
66
70
  type AnyContextFor<methods extends readonly Method.AnyClient[]> = {
67
- [K in keyof methods]: methods[K] extends Method.Client<any, infer contextSchema>
68
- ? contextSchema extends z.ZodMiniType
69
- ? z.input<contextSchema>
71
+ [K in keyof methods]: NonNullable<methods[K]['context']> extends infer ctx
72
+ ? ctx extends z.ZodMiniType
73
+ ? z.input<ctx>
70
74
  : undefined
71
75
  : undefined
72
76
  }[number]
@@ -123,7 +127,7 @@ export declare namespace from {
123
127
  export function polyfill<const methods extends readonly Method.AnyClient[]>(
124
128
  config: polyfill.Config<methods>,
125
129
  ): void {
126
- originalFetch = globalThis.fetch
130
+ if (!originalFetch) originalFetch = globalThis.fetch
127
131
  globalThis.fetch = from(config) as typeof globalThis.fetch
128
132
  }
129
133
 
@@ -153,6 +157,20 @@ export function restore(): void {
153
157
  }
154
158
  }
155
159
 
160
+ /** @internal Normalizes headers to a plain object for spreading. */
161
+ function normalizeHeaders(headers: unknown): Record<string, string> {
162
+ if (!headers) return {}
163
+ if (headers instanceof Headers) {
164
+ const result: Record<string, string> = {}
165
+ headers.forEach((value, key) => {
166
+ result[key] = value
167
+ })
168
+ return result
169
+ }
170
+ if (Array.isArray(headers)) return Object.fromEntries(headers)
171
+ return headers as Record<string, string>
172
+ }
173
+
156
174
  /** @internal */
157
175
  async function resolveCredential(
158
176
  challenge: Challenge.Challenge,
@@ -1,4 +1,5 @@
1
1
  import type * as Hex from 'ox/Hex'
2
+ import type { Address } from 'viem'
2
3
  import { prepareTransactionRequest, signTransaction } from 'viem/actions'
3
4
  import { tempo as tempo_chain } from 'viem/chains'
4
5
  import { Actions } from 'viem/tempo'
@@ -8,6 +9,7 @@ import * as Account from '../../viem/Account.js'
8
9
  import * as Client from '../../viem/Client.js'
9
10
  import * as z from '../../zod.js'
10
11
  import * as Attribution from '../Attribution.js'
12
+ import * as AutoSwap from '../internal/auto-swap.js'
11
13
  import * as defaults from '../internal/defaults.js'
12
14
  import * as Methods from '../Methods.js'
13
15
 
@@ -36,6 +38,7 @@ export function charge(parameters: charge.Parameters = {}) {
36
38
  return Method.toClient(Methods.charge, {
37
39
  context: z.object({
38
40
  account: z.optional(z.custom<Account.getResolver.Parameters['account']>()),
41
+ autoSwap: z.optional(z.custom<charge.AutoSwap>()),
39
42
  }),
40
43
 
41
44
  async createCredential({ challenge, context }) {
@@ -44,22 +47,41 @@ export function charge(parameters: charge.Parameters = {}) {
44
47
  const account = getAccount(client, context)
45
48
 
46
49
  const { request } = challenge
47
- const { amount, currency, recipient, methodDetails } = request
50
+ const { amount, methodDetails } = request
51
+ const currency = request.currency as Address
52
+ const recipient = request.recipient as Address
48
53
 
49
54
  const memo = methodDetails?.memo
50
55
  ? (methodDetails.memo as Hex.Hex)
51
56
  : Attribution.encode({ serverId: challenge.realm, clientId })
52
57
 
58
+ const transferCall = Actions.token.transfer.call({
59
+ amount: BigInt(amount),
60
+ memo,
61
+ to: recipient,
62
+ token: currency,
63
+ })
64
+
65
+ const autoSwap = AutoSwap.resolve(
66
+ context?.autoSwap ?? parameters.autoSwap,
67
+ AutoSwap.defaultCurrencies,
68
+ )
69
+
70
+ const swapCalls = autoSwap
71
+ ? await AutoSwap.findCalls(client, {
72
+ account: account.address,
73
+ amountOut: BigInt(amount),
74
+ tokenOut: currency,
75
+ tokenIn: autoSwap.tokenIn,
76
+ slippage: autoSwap.slippage,
77
+ })
78
+ : undefined
79
+
80
+ const calls = [...(swapCalls ?? []), transferCall]
81
+
53
82
  const prepared = await prepareTransactionRequest(client, {
54
83
  account,
55
- calls: [
56
- Actions.token.transfer.call({
57
- amount: BigInt(amount),
58
- memo,
59
- to: recipient as Hex.Hex,
60
- token: currency as Hex.Hex,
61
- }),
62
- ],
84
+ calls,
63
85
  ...(methodDetails?.feePayer && { feePayer: true }),
64
86
  nonceKey: 'expiring',
65
87
  } as never)
@@ -77,7 +99,16 @@ export function charge(parameters: charge.Parameters = {}) {
77
99
  }
78
100
 
79
101
  export declare namespace charge {
102
+ type AutoSwap = AutoSwap.resolve.Value
103
+
80
104
  type Parameters = {
105
+ /**
106
+ * Automatically swap from a fallback currency (pathUsd, USDC.e) via the
107
+ * Tempo DEX when the user lacks sufficient balance of the target currency.
108
+ *
109
+ * @default false
110
+ */
111
+ autoSwap?: AutoSwap | undefined
81
112
  /** Client identifier used to derive the client fingerprint in attribution memos. */
82
113
  clientId?: string | undefined
83
114
  } & Account.getResolver.Parameters &