viem 2.57.15 → 2.57.16

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 (111) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/_cjs/errors/version.js +1 -1
  3. package/_cjs/tempo/Gateway.js +195 -0
  4. package/_cjs/tempo/Gateway.js.map +1 -0
  5. package/_cjs/tempo/GatewayDecorator.js +168 -0
  6. package/_cjs/tempo/GatewayDecorator.js.map +1 -0
  7. package/_cjs/tempo/actions/ai.js +69 -0
  8. package/_cjs/tempo/actions/ai.js.map +1 -0
  9. package/_cjs/tempo/actions/bucket.js +85 -0
  10. package/_cjs/tempo/actions/bucket.js.map +1 -0
  11. package/_cjs/tempo/actions/compute.js +165 -0
  12. package/_cjs/tempo/actions/compute.js.map +1 -0
  13. package/_cjs/tempo/actions/gateway.js +8 -0
  14. package/_cjs/tempo/actions/gateway.js.map +1 -0
  15. package/_cjs/tempo/actions/index.js +6 -1
  16. package/_cjs/tempo/actions/index.js.map +1 -1
  17. package/_cjs/tempo/actions/kv.js +44 -0
  18. package/_cjs/tempo/actions/kv.js.map +1 -0
  19. package/_cjs/tempo/index.js +4 -1
  20. package/_cjs/tempo/index.js.map +1 -1
  21. package/_cjs/tempo/internal/ndjson.js +43 -0
  22. package/_cjs/tempo/internal/ndjson.js.map +1 -0
  23. package/_cjs/utils/buildRequest.js +4 -0
  24. package/_cjs/utils/buildRequest.js.map +1 -1
  25. package/_cjs/utils/hash/toSignatureHash.js +10 -1
  26. package/_cjs/utils/hash/toSignatureHash.js.map +1 -1
  27. package/_cjs/utils/rpc/http.js +6 -3
  28. package/_cjs/utils/rpc/http.js.map +1 -1
  29. package/_cjs/utils/rpc/socket.js +20 -9
  30. package/_cjs/utils/rpc/socket.js.map +1 -1
  31. package/_cjs/zksync/actions/finalizeWithdrawal.js +4 -2
  32. package/_cjs/zksync/actions/finalizeWithdrawal.js.map +1 -1
  33. package/_cjs/zksync/actions/isWithdrawalFinalized.js +4 -5
  34. package/_cjs/zksync/actions/isWithdrawalFinalized.js.map +1 -1
  35. package/_esm/errors/version.js +1 -1
  36. package/_esm/tempo/Gateway.js +294 -0
  37. package/_esm/tempo/Gateway.js.map +1 -0
  38. package/_esm/tempo/GatewayDecorator.js +207 -0
  39. package/_esm/tempo/GatewayDecorator.js.map +1 -0
  40. package/_esm/tempo/actions/ai.js +132 -0
  41. package/_esm/tempo/actions/ai.js.map +1 -0
  42. package/_esm/tempo/actions/bucket.js +181 -0
  43. package/_esm/tempo/actions/bucket.js.map +1 -0
  44. package/_esm/tempo/actions/compute.js +424 -0
  45. package/_esm/tempo/actions/compute.js.map +1 -0
  46. package/_esm/tempo/actions/gateway.js +22 -0
  47. package/_esm/tempo/actions/gateway.js.map +1 -0
  48. package/_esm/tempo/actions/index.js +10 -0
  49. package/_esm/tempo/actions/index.js.map +1 -1
  50. package/_esm/tempo/actions/kv.js +124 -0
  51. package/_esm/tempo/actions/kv.js.map +1 -0
  52. package/_esm/tempo/index.js +9 -0
  53. package/_esm/tempo/index.js.map +1 -1
  54. package/_esm/tempo/internal/ndjson.js +45 -0
  55. package/_esm/tempo/internal/ndjson.js.map +1 -0
  56. package/_esm/utils/buildRequest.js +6 -0
  57. package/_esm/utils/buildRequest.js.map +1 -1
  58. package/_esm/utils/hash/toSignatureHash.js +11 -1
  59. package/_esm/utils/hash/toSignatureHash.js.map +1 -1
  60. package/_esm/utils/rpc/http.js +11 -3
  61. package/_esm/utils/rpc/http.js.map +1 -1
  62. package/_esm/utils/rpc/socket.js +24 -9
  63. package/_esm/utils/rpc/socket.js.map +1 -1
  64. package/_esm/zksync/actions/finalizeWithdrawal.js +5 -2
  65. package/_esm/zksync/actions/finalizeWithdrawal.js.map +1 -1
  66. package/_esm/zksync/actions/isWithdrawalFinalized.js +5 -5
  67. package/_esm/zksync/actions/isWithdrawalFinalized.js.map +1 -1
  68. package/_types/errors/version.d.ts +1 -1
  69. package/_types/tempo/Gateway.d.ts +337 -0
  70. package/_types/tempo/Gateway.d.ts.map +1 -0
  71. package/_types/tempo/GatewayDecorator.d.ts +635 -0
  72. package/_types/tempo/GatewayDecorator.d.ts.map +1 -0
  73. package/_types/tempo/actions/ai.d.ts +145 -0
  74. package/_types/tempo/actions/ai.d.ts.map +1 -0
  75. package/_types/tempo/actions/bucket.d.ts +210 -0
  76. package/_types/tempo/actions/bucket.d.ts.map +1 -0
  77. package/_types/tempo/actions/compute.d.ts +628 -0
  78. package/_types/tempo/actions/compute.d.ts.map +1 -0
  79. package/_types/tempo/actions/gateway.d.ts +25 -0
  80. package/_types/tempo/actions/gateway.d.ts.map +1 -0
  81. package/_types/tempo/actions/index.d.ts +10 -0
  82. package/_types/tempo/actions/index.d.ts.map +1 -1
  83. package/_types/tempo/actions/kv.d.ts +167 -0
  84. package/_types/tempo/actions/kv.d.ts.map +1 -0
  85. package/_types/tempo/index.d.ts +11 -0
  86. package/_types/tempo/index.d.ts.map +1 -1
  87. package/_types/tempo/internal/ndjson.d.ts +9 -0
  88. package/_types/tempo/internal/ndjson.d.ts.map +1 -0
  89. package/_types/utils/buildRequest.d.ts.map +1 -1
  90. package/_types/utils/hash/toSignatureHash.d.ts +1 -1
  91. package/_types/utils/hash/toSignatureHash.d.ts.map +1 -1
  92. package/_types/utils/rpc/http.d.ts.map +1 -1
  93. package/_types/utils/rpc/socket.d.ts.map +1 -1
  94. package/errors/version.ts +1 -1
  95. package/package.json +5 -1
  96. package/tempo/Gateway.ts +477 -0
  97. package/tempo/GatewayDecorator.ts +909 -0
  98. package/tempo/actions/ai.ts +250 -0
  99. package/tempo/actions/bucket.ts +324 -0
  100. package/tempo/actions/compute.ts +894 -0
  101. package/tempo/actions/gateway.ts +33 -0
  102. package/tempo/actions/index.ts +10 -0
  103. package/tempo/actions/kv.ts +229 -0
  104. package/tempo/index.ts +12 -0
  105. package/tempo/internal/ndjson.ts +51 -0
  106. package/utils/buildRequest.ts +4 -0
  107. package/utils/hash/toSignatureHash.ts +12 -2
  108. package/utils/rpc/http.ts +11 -3
  109. package/utils/rpc/socket.ts +28 -15
  110. package/zksync/actions/finalizeWithdrawal.ts +5 -2
  111. package/zksync/actions/isWithdrawalFinalized.ts +5 -5
@@ -0,0 +1,909 @@
1
+ import type { Address } from 'abitype'
2
+ import type { Account } from '../accounts/types.js'
3
+ import { readContract } from '../actions/public/readContract.js'
4
+ import type { Client } from '../clients/createClient.js'
5
+ import type { Transport } from '../clients/transports/createTransport.js'
6
+ import { erc20Abi } from '../constants/abis.js'
7
+ import type { Chain } from '../types/chain.js'
8
+ import * as aiActions from './actions/ai.js'
9
+ import * as bucketActions from './actions/bucket.js'
10
+ import * as computeActions from './actions/compute.js'
11
+ import * as gatewayActions from './actions/gateway.js'
12
+ import * as kvActions from './actions/kv.js'
13
+ import * as Gateway from './Gateway.js'
14
+
15
+ /**
16
+ * Gateway actions added to a Client by {@link decorator}.
17
+ *
18
+ * @experimental
19
+ */
20
+ export type Decorator = {
21
+ /** Inference. */
22
+ ai: {
23
+ /**
24
+ * Embeds text with a Gateway model. Paid per request.
25
+ *
26
+ * @experimental
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * import { createClient, gatewayActions } from 'viem/tempo'
31
+ *
32
+ * const client = createClient({ account }).extend(
33
+ * gatewayActions(),
34
+ * )
35
+ *
36
+ * const { embeddings } = await client.ai.embed({
37
+ * input: ['hello world'],
38
+ * model: '@cf/baai/bge-m3',
39
+ * })
40
+ * ```
41
+ *
42
+ * @param parameters - Parameters.
43
+ * @returns The embeddings and their shape.
44
+ */
45
+ embed: (
46
+ parameters: aiActions.embed.Parameters,
47
+ ) => Promise<aiActions.embed.ReturnValue>
48
+ /**
49
+ * Generates text with a Gateway model. Paid per request.
50
+ *
51
+ * @experimental
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * import { createClient, gatewayActions } from 'viem/tempo'
56
+ *
57
+ * const client = createClient({ account }).extend(
58
+ * gatewayActions(),
59
+ * )
60
+ *
61
+ * const { text } = await client.ai.generateText({
62
+ * model: '@cf/meta/llama-3.3-70b-instruct-fp8-fast',
63
+ * prompt: 'Describe this app in one sentence.',
64
+ * })
65
+ * ```
66
+ *
67
+ * @param parameters - Parameters.
68
+ * @returns The generated text and token usage.
69
+ */
70
+ generateText: (
71
+ parameters: aiActions.generateText.Parameters,
72
+ ) => Promise<aiActions.generateText.ReturnValue>
73
+ /**
74
+ * Generates text with a Gateway model and yields it as it is produced.
75
+ * Paid per request.
76
+ *
77
+ * @experimental
78
+ *
79
+ * @example
80
+ * ```ts
81
+ * import { createClient, gatewayActions } from 'viem/tempo'
82
+ *
83
+ * const client = createClient({ account }).extend(
84
+ * gatewayActions(),
85
+ * )
86
+ *
87
+ * for await (const event of client.ai.streamText({
88
+ * model: '@cf/zai-org/glm-5.3',
89
+ * prompt: 'Write a haiku about Tempo.',
90
+ * })) {
91
+ * if (event.type === 'text') process.stdout.write(event.delta)
92
+ * }
93
+ * ```
94
+ *
95
+ * @param parameters - Parameters.
96
+ * @returns Text and reasoning deltas, then usage.
97
+ */
98
+ streamText: (
99
+ parameters: aiActions.streamText.Parameters,
100
+ ) => AsyncGenerator<aiActions.streamText.Event>
101
+ }
102
+ /** Object storage, private to the payer and app. */
103
+ bucket: {
104
+ /**
105
+ * Deletes an object from the app's bucket. Paid per request.
106
+ *
107
+ * @experimental
108
+ *
109
+ * @example
110
+ * ```ts
111
+ * import { createClient, gatewayActions } from 'viem/tempo'
112
+ *
113
+ * const client = createClient({ account }).extend(
114
+ * gatewayActions(),
115
+ * )
116
+ *
117
+ * await client.bucket.delete({ key: 'notes/today.txt' })
118
+ * ```
119
+ *
120
+ * @param parameters - Parameters.
121
+ * @returns Whether the request succeeded.
122
+ */
123
+ delete: (
124
+ parameters: bucketActions.delete.Parameters,
125
+ ) => Promise<bucketActions.delete.ReturnValue>
126
+ /**
127
+ * Reads an object from the app's bucket as a stream. Returns `null` when the
128
+ * object does not exist or expired. Paid per request.
129
+ *
130
+ * @experimental
131
+ *
132
+ * @example
133
+ * ```ts
134
+ * import { createClient, gatewayActions } from 'viem/tempo'
135
+ *
136
+ * const client = createClient({ account }).extend(
137
+ * gatewayActions(),
138
+ * )
139
+ *
140
+ * const object = await client.bucket.get({ key: 'notes/today.txt' })
141
+ * ```
142
+ *
143
+ * @param parameters - Parameters.
144
+ * @returns The object body and metadata, or `null`.
145
+ */
146
+ get: (
147
+ parameters: bucketActions.get.Parameters,
148
+ ) => Promise<bucketActions.get.ReturnValue>
149
+ /**
150
+ * Reads the metadata of an object in the app's bucket. Returns `null` when
151
+ * the object does not exist or expired. Paid per request.
152
+ *
153
+ * @experimental
154
+ *
155
+ * @example
156
+ * ```ts
157
+ * import { createClient, gatewayActions } from 'viem/tempo'
158
+ *
159
+ * const client = createClient({ account }).extend(
160
+ * gatewayActions(),
161
+ * )
162
+ *
163
+ * const metadata = await client.bucket.head({ key: 'notes/today.txt' })
164
+ * ```
165
+ *
166
+ * @param parameters - Parameters.
167
+ * @returns The object metadata, or `null`.
168
+ */
169
+ head: (
170
+ parameters: bucketActions.head.Parameters,
171
+ ) => Promise<bucketActions.head.ReturnValue>
172
+ /**
173
+ * Lists objects in the app's bucket by key prefix. Paid per request.
174
+ *
175
+ * @experimental
176
+ *
177
+ * @example
178
+ * ```ts
179
+ * import { createClient, gatewayActions } from 'viem/tempo'
180
+ *
181
+ * const client = createClient({ account }).extend(
182
+ * gatewayActions(),
183
+ * )
184
+ *
185
+ * const { objects } = await client.bucket.list({ prefix: 'notes/' })
186
+ * ```
187
+ *
188
+ * @param parameters - Parameters.
189
+ * @returns A page of object metadata and the next cursor.
190
+ */
191
+ list: (
192
+ parameters?: bucketActions.list.Parameters,
193
+ ) => Promise<bucketActions.list.ReturnValue>
194
+ /**
195
+ * Writes an object to the app's bucket for a retention period. Paid per
196
+ * request.
197
+ *
198
+ * @experimental
199
+ *
200
+ * @example
201
+ * ```ts
202
+ * import { createClient, gatewayActions } from 'viem/tempo'
203
+ *
204
+ * const client = createClient({ account }).extend(
205
+ * gatewayActions(),
206
+ * )
207
+ *
208
+ * const metadata = await client.bucket.put({
209
+ * key: 'notes/today.txt',
210
+ * retention: 86_400,
211
+ * value: new Blob(['hello'], { type: 'text/plain' }),
212
+ * })
213
+ * ```
214
+ *
215
+ * @param parameters - Parameters.
216
+ * @returns The object metadata.
217
+ */
218
+ put: (
219
+ parameters: bucketActions.put.Parameters,
220
+ ) => Promise<bucketActions.put.ReturnValue>
221
+ }
222
+ /** Sandboxed CPU and GPU compute, private to the payer and app. */
223
+ compute: {
224
+ /**
225
+ * Starts a sandbox that can live up to `timeout` seconds, from a container
226
+ * image with optional `apt/pip` layers or from a snapshot. Compute is
227
+ * metered: creation pays for `lease` seconds at the sandbox's GPU, CPU, and
228
+ * memory rate, and `renew` pays for more. `ports` are served over public
229
+ * HTTPS tunnels.
230
+ *
231
+ * @experimental
232
+ *
233
+ * @example
234
+ * ```ts
235
+ * import { createClient, gatewayActions } from 'viem/tempo'
236
+ *
237
+ * const client = createClient({ account }).extend(
238
+ * gatewayActions(),
239
+ * )
240
+ *
241
+ * const sandbox = await client.compute.create({
242
+ * gpu: 'T4',
243
+ * image: 'pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime',
244
+ * timeout: 1200,
245
+ * })
246
+ * ```
247
+ *
248
+ * @param parameters - Parameters.
249
+ * @returns The sandbox and its tunnels.
250
+ */
251
+ create: <const ports extends readonly number[] = readonly []>(
252
+ parameters?: computeActions.create.Parameters<ports>,
253
+ ) => Promise<computeActions.create.ReturnValue<ports>>
254
+ /**
255
+ * Runs a command in a sandbox and waits up to `timeout` seconds (at most
256
+ * 120). Use `spawn` for longer jobs. Paid per request.
257
+ *
258
+ * @experimental
259
+ *
260
+ * @example
261
+ * ```ts
262
+ * import { createClient, gatewayActions } from 'viem/tempo'
263
+ *
264
+ * const client = createClient({ account }).extend(
265
+ * gatewayActions(),
266
+ * )
267
+ *
268
+ * const { stdout } = await client.compute.exec({
269
+ * command: ['nvidia-smi'],
270
+ * sandboxId: sandbox.sandboxId,
271
+ * })
272
+ * ```
273
+ *
274
+ * @param parameters - Parameters.
275
+ * @returns The command's output and exit code.
276
+ */
277
+ exec: (
278
+ parameters: computeActions.exec.Parameters,
279
+ ) => Promise<computeActions.exec.ReturnValue>
280
+ /**
281
+ * Lists the app's sandboxes that have not ended. Paid per request.
282
+ *
283
+ * @experimental
284
+ *
285
+ * @example
286
+ * ```ts
287
+ * import { createClient, gatewayActions } from 'viem/tempo'
288
+ *
289
+ * const client = createClient({ account }).extend(
290
+ * gatewayActions(),
291
+ * )
292
+ *
293
+ * const { sandboxes } = await client.compute.list()
294
+ * ```
295
+ *
296
+ * @param parameters - Parameters.
297
+ * @returns A page of sandboxes and the next cursor.
298
+ */
299
+ list: (
300
+ parameters?: computeActions.list.Parameters,
301
+ ) => Promise<computeActions.list.ReturnValue>
302
+ /**
303
+ * Reads a file from a sandbox from `offset`, up to 8 MiB per request. Returns
304
+ * `null` when the file does not exist. Paid per request.
305
+ *
306
+ * @experimental
307
+ *
308
+ * @example
309
+ * ```ts
310
+ * import { createClient, gatewayActions } from 'viem/tempo'
311
+ *
312
+ * const client = createClient({ account }).extend(
313
+ * gatewayActions(),
314
+ * )
315
+ *
316
+ * const log = await client.compute.read({
317
+ * path: job.logPath,
318
+ * sandboxId: sandbox.sandboxId,
319
+ * })
320
+ * ```
321
+ *
322
+ * @param parameters - Parameters.
323
+ * @returns The bytes read and the whole file size, or `null`.
324
+ */
325
+ read: (
326
+ parameters: computeActions.read.Parameters,
327
+ ) => Promise<computeActions.read.ReturnValue>
328
+ /**
329
+ * Saves a sandbox's filesystem as a snapshot kept for 30 days. Paid per
330
+ * request.
331
+ *
332
+ * @experimental
333
+ *
334
+ * @example
335
+ * ```ts
336
+ * import { createClient, gatewayActions } from 'viem/tempo'
337
+ *
338
+ * const client = createClient({ account }).extend(
339
+ * gatewayActions(),
340
+ * )
341
+ *
342
+ * const { snapshot } = await client.compute.snapshot({
343
+ * sandboxId: sandbox.sandboxId,
344
+ * })
345
+ * ```
346
+ *
347
+ * @param parameters - Parameters.
348
+ * @returns The snapshot ID and its expiry.
349
+ */
350
+ snapshot: (
351
+ parameters: computeActions.snapshot.Parameters,
352
+ ) => Promise<computeActions.snapshot.ReturnValue>
353
+ /**
354
+ * Starts a command in the background; its output goes to `logPath` and its
355
+ * exit code to `exitPath`. Paid per request.
356
+ *
357
+ * @experimental
358
+ *
359
+ * @example
360
+ * ```ts
361
+ * import { createClient, gatewayActions } from 'viem/tempo'
362
+ *
363
+ * const client = createClient({ account }).extend(
364
+ * gatewayActions(),
365
+ * )
366
+ *
367
+ * const job = await client.compute.spawn({
368
+ * command: ['python', 'train.py'],
369
+ * sandboxId: sandbox.sandboxId,
370
+ * })
371
+ * ```
372
+ *
373
+ * @param parameters - Parameters.
374
+ * @returns The process ID and the paths of its log and exit code.
375
+ */
376
+ spawn: (
377
+ parameters: computeActions.spawn.Parameters,
378
+ ) => Promise<computeActions.spawn.ReturnValue>
379
+ /**
380
+ * Reads whether a sandbox is running. Paid per request.
381
+ *
382
+ * @experimental
383
+ *
384
+ * @example
385
+ * ```ts
386
+ * import { createClient, gatewayActions } from 'viem/tempo'
387
+ *
388
+ * const client = createClient({ account }).extend(
389
+ * gatewayActions(),
390
+ * )
391
+ *
392
+ * const { status } = await client.compute.status({
393
+ * sandboxId: sandbox.sandboxId,
394
+ * })
395
+ * ```
396
+ *
397
+ * @param parameters - Parameters.
398
+ * @returns The sandbox and its status.
399
+ */
400
+ status: (
401
+ parameters: computeActions.status.Parameters,
402
+ ) => Promise<computeActions.status.ReturnValue>
403
+ /**
404
+ * Terminates a sandbox. The Gateway credits the unused rest of its lease back to the payment channel. Paid per request.
405
+ *
406
+ * @experimental
407
+ *
408
+ * @example
409
+ * ```ts
410
+ * import { createClient, gatewayActions } from 'viem/tempo'
411
+ *
412
+ * const client = createClient({ account }).extend(
413
+ * gatewayActions(),
414
+ * )
415
+ *
416
+ * await client.compute.terminate({ sandboxId: sandbox.sandboxId })
417
+ * ```
418
+ *
419
+ * @param parameters - Parameters.
420
+ * @returns The final status.
421
+ */
422
+ terminate: (
423
+ parameters: computeActions.terminate.Parameters,
424
+ ) => Promise<computeActions.terminate.ReturnValue>
425
+ /**
426
+ * Writes a file into a sandbox, up to 8 MiB. Paid per request.
427
+ *
428
+ * @experimental
429
+ *
430
+ * @example
431
+ * ```ts
432
+ * import { createClient, gatewayActions } from 'viem/tempo'
433
+ *
434
+ * const client = createClient({ account }).extend(
435
+ * gatewayActions(),
436
+ * )
437
+ *
438
+ * await client.compute.write({
439
+ * path: '/root/train.py',
440
+ * sandboxId: sandbox.sandboxId,
441
+ * value: 'print("training")',
442
+ * })
443
+ * ```
444
+ *
445
+ * @param parameters - Parameters.
446
+ * @returns The path and size written.
447
+ */
448
+ write: (
449
+ parameters: computeActions.write.Parameters,
450
+ ) => Promise<computeActions.write.ReturnValue>
451
+ /**
452
+ * Pays for more seconds of a sandbox at its per-second rate, up to its
453
+ * `timeout`. Paid per request.
454
+ *
455
+ * @experimental
456
+ *
457
+ * @example
458
+ * ```ts
459
+ * import { createClient, gatewayActions } from 'viem/tempo'
460
+ *
461
+ * const client = createClient({ account }).extend(
462
+ * gatewayActions(),
463
+ * )
464
+ *
465
+ * await client.compute.renew({ sandboxId: sandbox.sandboxId, seconds: 300 })
466
+ * ```
467
+ *
468
+ * @param parameters - Parameters.
469
+ * @returns The sandbox with its new `paidUntil`.
470
+ */
471
+ renew: (
472
+ parameters: computeActions.renew.Parameters,
473
+ ) => Promise<computeActions.renew.ReturnValue>
474
+ /**
475
+ * Runs a command and yields its output as it is written, then its exit.
476
+ * Paid per request.
477
+ *
478
+ * @experimental
479
+ *
480
+ * @example
481
+ * ```ts
482
+ * import { createClient, gatewayActions } from 'viem/tempo'
483
+ *
484
+ * const client = createClient({ account }).extend(
485
+ * gatewayActions(),
486
+ * )
487
+ *
488
+ * for await (const event of client.compute.stream({
489
+ * command: ['python', 'train.py'],
490
+ * sandboxId: sandbox.sandboxId,
491
+ * })) {
492
+ * if (event.type !== 'exit') process.stdout.write(event.data)
493
+ * }
494
+ * ```
495
+ *
496
+ * @param parameters - Parameters.
497
+ * @returns Output and exit events.
498
+ */
499
+ stream: (
500
+ parameters: computeActions.stream.Parameters,
501
+ ) => AsyncGenerator<computeActions.stream.Event>
502
+ /**
503
+ * Follows the log of a command started with `spawn` and yields it as it
504
+ * grows, then the exit code. Paid per request.
505
+ *
506
+ * @experimental
507
+ *
508
+ * @example
509
+ * ```ts
510
+ * import { createClient, gatewayActions } from 'viem/tempo'
511
+ *
512
+ * const client = createClient({ account }).extend(
513
+ * gatewayActions(),
514
+ * )
515
+ *
516
+ * for await (const event of client.compute.logs({
517
+ * logPath: job.logPath,
518
+ * sandboxId: sandbox.sandboxId,
519
+ * })) {
520
+ * if (event.type === 'log') process.stdout.write(event.data)
521
+ * }
522
+ * ```
523
+ *
524
+ * @param parameters - Parameters.
525
+ * @returns Log, exit, and end events.
526
+ */
527
+ logs: (
528
+ parameters: computeActions.logs.Parameters,
529
+ ) => AsyncGenerator<computeActions.logs.Event>
530
+ }
531
+ /** Gateway discovery. */
532
+ gateway: {
533
+ /**
534
+ * Reads the Gateway's free discovery document: chain, currencies, prices,
535
+ * limits, and models.
536
+ *
537
+ * @experimental
538
+ *
539
+ * @example
540
+ * ```ts
541
+ * import { createClient, gatewayActions } from 'viem/tempo'
542
+ *
543
+ * const client = createClient().extend(gatewayActions())
544
+ *
545
+ * const capabilities = await client.gateway.getCapabilities()
546
+ * ```
547
+ *
548
+ * @param parameters - Parameters.
549
+ * @returns The Gateway capabilities.
550
+ */
551
+ getCapabilities: (
552
+ parameters?: gatewayActions.getCapabilities.Parameters | undefined,
553
+ ) => Promise<gatewayActions.getCapabilities.ReturnValue>
554
+ }
555
+ /** Key-value state, private to the payer and app. */
556
+ kv: {
557
+ /**
558
+ * Deletes a key from the app's key-value store. Paid per request.
559
+ *
560
+ * @experimental
561
+ *
562
+ * @example
563
+ * ```ts
564
+ * import { createClient, gatewayActions } from 'viem/tempo'
565
+ *
566
+ * const client = createClient({ account }).extend(
567
+ * gatewayActions(),
568
+ * )
569
+ *
570
+ * const { deleted } = await client.kv.delete({ key: 'counter' })
571
+ * ```
572
+ *
573
+ * @param parameters - Parameters.
574
+ * @returns Whether the key existed.
575
+ */
576
+ delete: (
577
+ parameters: kvActions.delete.Parameters,
578
+ ) => Promise<kvActions.delete.ReturnValue>
579
+ /**
580
+ * Reads a key from the app's key-value store. Returns `null` when the key
581
+ * does not exist or expired. Paid per request.
582
+ *
583
+ * @experimental
584
+ *
585
+ * @example
586
+ * ```ts
587
+ * import { createClient, gatewayActions } from 'viem/tempo'
588
+ *
589
+ * const client = createClient({ account }).extend(
590
+ * gatewayActions(),
591
+ * )
592
+ *
593
+ * const entry = await client.kv.get({ key: 'counter' })
594
+ * ```
595
+ *
596
+ * @param parameters - Parameters.
597
+ * @returns The entry, or `null`.
598
+ */
599
+ get: (
600
+ parameters: kvActions.get.Parameters,
601
+ ) => Promise<kvActions.get.ReturnValue>
602
+ /**
603
+ * Lists entries in the app's key-value store by key prefix, in key order.
604
+ * Paid per request.
605
+ *
606
+ * @experimental
607
+ *
608
+ * @example
609
+ * ```ts
610
+ * import { createClient, gatewayActions } from 'viem/tempo'
611
+ *
612
+ * const client = createClient({ account }).extend(
613
+ * gatewayActions(),
614
+ * )
615
+ *
616
+ * const { entries } = await client.kv.list({ prefix: 'settings/' })
617
+ * ```
618
+ *
619
+ * @param parameters - Parameters.
620
+ * @returns A page of entries and the next cursor.
621
+ */
622
+ list: (
623
+ parameters?: kvActions.list.Parameters,
624
+ ) => Promise<kvActions.list.ReturnValue>
625
+ /**
626
+ * Writes a JSON value to the app's key-value store. Paid per request.
627
+ *
628
+ * Pass `ifVersion` to write conditionally: `null` creates the key only if it
629
+ * does not exist, and a version replaces the value only if it is still that
630
+ * version. A failed condition throws `Gateway.VersionConflictError`.
631
+ *
632
+ * @experimental
633
+ *
634
+ * @example
635
+ * ```ts
636
+ * import { createClient, gatewayActions } from 'viem/tempo'
637
+ *
638
+ * const client = createClient({ account }).extend(
639
+ * gatewayActions(),
640
+ * )
641
+ *
642
+ * const entry = await client.kv.set({
643
+ * ifVersion: null,
644
+ * key: 'counter',
645
+ * value: { count: 1 },
646
+ * })
647
+ * ```
648
+ *
649
+ * @param parameters - Parameters.
650
+ * @returns The written entry.
651
+ */
652
+ set: (
653
+ parameters: kvActions.set.Parameters,
654
+ ) => Promise<kvActions.set.ReturnValue>
655
+ }
656
+ }
657
+
658
+ /**
659
+ * Adds Gateway inference (`client.ai`), object storage (`client.bucket`),
660
+ * sandboxed compute (`client.compute`), and key-value state (`client.kv`) to a
661
+ * Client.
662
+ *
663
+ * When the Client has a local account, requests are paid with it through
664
+ * `mppx` (an optional peer dependency, loaded on the first request). Other
665
+ * Clients use `globalThis.fetch`, which the Accounts SDK makes payment-aware
666
+ * for Tempo Wallet. Pass `fetch` to pay another way. Data is scoped by chain, the paying wallet, and `app`.
667
+ *
668
+ * @experimental
669
+ *
670
+ * @example
671
+ * ```ts
672
+ * import { createClient, gatewayActions } from 'viem/tempo'
673
+ *
674
+ * const client = createClient({ account }).extend(gatewayActions())
675
+ *
676
+ * const { text } = await client.ai.generateText({
677
+ * model: '@cf/meta/llama-3.3-70b-instruct-fp8-fast',
678
+ * prompt: 'Describe this app in one sentence.',
679
+ * })
680
+ * await client.kv.set({ key: 'description', value: text })
681
+ * ```
682
+ *
683
+ * @param options - Gateway connection options.
684
+ * @returns A Client decorator.
685
+ */
686
+ export function decorator(options: decorator.Options = {}) {
687
+ return <
688
+ transport extends Transport,
689
+ chain extends Chain | undefined,
690
+ account extends Account | undefined,
691
+ >(
692
+ client: Client<transport, chain, account>,
693
+ ): Decorator => {
694
+ const gateway = Gateway.from({
695
+ ...options,
696
+ fetch:
697
+ options.fetch ??
698
+ (client.account?.type === 'local' ? pay(client) : undefined),
699
+ })
700
+ return {
701
+ ai: {
702
+ embed: (parameters) => aiActions.embed(gateway, parameters),
703
+ generateText: (parameters) =>
704
+ aiActions.generateText(gateway, parameters),
705
+ streamText: (parameters) => aiActions.streamText(gateway, parameters),
706
+ },
707
+ bucket: {
708
+ delete: (parameters) => bucketActions.delete(gateway, parameters),
709
+ get: (parameters) => bucketActions.get(gateway, parameters),
710
+ head: (parameters) => bucketActions.head(gateway, parameters),
711
+ list: (parameters) => bucketActions.list(gateway, parameters),
712
+ put: (parameters) => bucketActions.put(gateway, parameters),
713
+ },
714
+ compute: {
715
+ create: (parameters) => computeActions.create(gateway, parameters),
716
+ exec: (parameters) => computeActions.exec(gateway, parameters),
717
+ list: (parameters) => computeActions.list(gateway, parameters),
718
+ logs: (parameters) => computeActions.logs(gateway, parameters),
719
+ read: (parameters) => computeActions.read(gateway, parameters),
720
+ renew: (parameters) => computeActions.renew(gateway, parameters),
721
+ snapshot: (parameters) => computeActions.snapshot(gateway, parameters),
722
+ spawn: (parameters) => computeActions.spawn(gateway, parameters),
723
+ status: (parameters) => computeActions.status(gateway, parameters),
724
+ stream: (parameters) => computeActions.stream(gateway, parameters),
725
+ terminate: (parameters) =>
726
+ computeActions.terminate(gateway, parameters),
727
+ write: (parameters) => computeActions.write(gateway, parameters),
728
+ },
729
+ gateway: {
730
+ getCapabilities: (parameters) =>
731
+ gatewayActions.getCapabilities(gateway, parameters),
732
+ },
733
+ kv: {
734
+ delete: (parameters) => kvActions.delete(gateway, parameters),
735
+ get: (parameters) => kvActions.get(gateway, parameters),
736
+ list: (parameters) => kvActions.list(gateway, parameters),
737
+ set: (parameters) => kvActions.set(gateway, parameters),
738
+ },
739
+ }
740
+ }
741
+ }
742
+
743
+ export declare namespace decorator {
744
+ type Options = Gateway.from.Options
745
+ }
746
+
747
+ /**
748
+ * Pays Gateway requests with the Client's account through `mppx`. Requests go
749
+ * through `globalThis.fetch` until the Gateway first asks for payment, so free
750
+ * routes work without `mppx` installed. `mppx` is loaded then, paying in the
751
+ * Gateway currency the account holds most of. When the account runs out, the
752
+ * next request reads its balances again, so funding it is enough to continue.
753
+ */
754
+ function pay(
755
+ client: Client<Transport, Chain | undefined, Account | undefined>,
756
+ ): Gateway.Fetch {
757
+ let mppx: Promise<Gateway.Fetch> | undefined
758
+ let funds: Funds | undefined
759
+ return async (input, init) => {
760
+ if (!mppx) {
761
+ const response = await globalThis.fetch(input, init)
762
+ if (response.status !== 402) return response
763
+ await response.body?.cancel().catch(() => {})
764
+ funds = await balances(client, new URL(input).origin)
765
+ const [best] = funds.balances
766
+ if (!best || best.amount === 0n)
767
+ throw new Gateway.InsufficientFundsError(funds)
768
+ mppx = load().then(
769
+ ({ Mppx, tempo }) =>
770
+ Mppx.create({
771
+ methods: [
772
+ tempo({
773
+ account: client.account,
774
+ getClient: ({ chainId }) => {
775
+ const expected = client.chain?.id
776
+ if (
777
+ chainId !== undefined &&
778
+ expected !== undefined &&
779
+ chainId !== expected
780
+ )
781
+ throw new Gateway.ChainMismatchError({ chainId, expected })
782
+ return client
783
+ },
784
+ }),
785
+ ],
786
+ orderChallenges: (candidates) =>
787
+ [...candidates].sort(
788
+ (a, b) =>
789
+ Number(!isCurrency(a, best.currency)) -
790
+ Number(!isCurrency(b, best.currency)),
791
+ ),
792
+ polyfill: false,
793
+ }).fetch,
794
+ (error: unknown) => {
795
+ mppx = undefined
796
+ throw new Gateway.MppxNotInstalledError({ cause: error as Error })
797
+ },
798
+ )
799
+ }
800
+ const underfunded = async (error: unknown) => {
801
+ if (!(error instanceof Error) || !isUnderfunded(error)) return error
802
+ mppx = undefined
803
+ const current = await balances(client, new URL(input).origin).catch(
804
+ () => funds,
805
+ )
806
+ return new Gateway.InsufficientFundsError({
807
+ ...(current ?? { address: '0x', balances: [] }),
808
+ cause: error,
809
+ })
810
+ }
811
+ const response = await (await mppx)(input, init).catch(async (error) => {
812
+ throw await underfunded(error)
813
+ })
814
+ if (!response.body) return response
815
+ const reader = response.body.getReader()
816
+ const body = new ReadableStream<Uint8Array>({
817
+ cancel: (reason) => reader.cancel(reason),
818
+ async pull(controller) {
819
+ try {
820
+ const { done, value } = await reader.read()
821
+ if (done) controller.close()
822
+ else controller.enqueue(value)
823
+ } catch (error) {
824
+ controller.error(await underfunded(error))
825
+ }
826
+ },
827
+ })
828
+ const wrapped = new Response(body, {
829
+ headers: response.headers,
830
+ status: response.status,
831
+ statusText: response.statusText,
832
+ })
833
+ Object.defineProperty(wrapped, 'url', { value: response.url })
834
+ return wrapped
835
+ }
836
+ }
837
+
838
+ type Funds = Gateway.InsufficientFundsError.Parameters
839
+
840
+ /** Reads the account's balance of each Gateway currency, largest first. */
841
+ async function balances(
842
+ client: Client<Transport, Chain | undefined, Account | undefined>,
843
+ origin: string,
844
+ ): Promise<Funds> {
845
+ const address = client.account!.address
846
+ const response = await globalThis.fetch(`${origin}/v1/capabilities`)
847
+ const { chainId, currencies } = (await response.json()) as {
848
+ chainId: number
849
+ currencies: Record<string, Address>
850
+ }
851
+ const expected = client.chain?.id
852
+ if (expected !== undefined && chainId !== expected)
853
+ throw new Gateway.ChainMismatchError({ chainId, expected })
854
+ const balances = await Promise.all(
855
+ Object.entries(currencies).map(async ([symbol, currency]) => ({
856
+ amount: (await readContract(client, {
857
+ abi: erc20Abi,
858
+ address: currency,
859
+ args: [address],
860
+ functionName: 'balanceOf',
861
+ })) as bigint,
862
+ currency,
863
+ symbol: symbol.toUpperCase(),
864
+ })),
865
+ )
866
+ return {
867
+ address,
868
+ balances: balances.sort((a, b) => (b.amount > a.amount ? 1 : -1)),
869
+ }
870
+ }
871
+
872
+ function isCurrency(candidate: unknown, currency: Address) {
873
+ const requested = (
874
+ candidate as { challenge?: { request?: { currency?: string } } }
875
+ ).challenge?.request?.currency
876
+ return requested?.toLowerCase() === currency.toLowerCase()
877
+ }
878
+
879
+ /** Whether a payment failed because the account could not cover it. */
880
+ function isUnderfunded(error: Error) {
881
+ for (let cause: unknown = error; cause instanceof Error; cause = cause.cause)
882
+ if (/InsufficientBalance/.test(cause.message)) return true
883
+ return false
884
+ }
885
+
886
+ type MppxClient = {
887
+ Mppx: {
888
+ create: (options: {
889
+ methods: readonly unknown[]
890
+ orderChallenges: (candidates: readonly unknown[]) => unknown[]
891
+ polyfill: boolean
892
+ }) => {
893
+ fetch: Gateway.Fetch
894
+ }
895
+ }
896
+ tempo: (options: {
897
+ account: unknown
898
+ getClient: (parameters: { chainId?: number | undefined }) => unknown
899
+ }) => unknown
900
+ }
901
+
902
+ /**
903
+ * Loads `mppx/client`. The specifier is cast so TypeScript doesn't pull the
904
+ * optional peer dependency's types into Viem's, while bundlers still see a
905
+ * literal import.
906
+ */
907
+ function load(): Promise<MppxClient> {
908
+ return import('mppx/client' as string)
909
+ }