@tangle-network/sandbox 0.60.3 → 0.60.7

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 (51) hide show
  1. package/README.md +2 -0
  2. package/dist/agent/index.d.ts +4 -4
  3. package/dist/agent/index.js +5 -5
  4. package/dist/agent/preview.d.ts +1 -1
  5. package/dist/agent/preview.js +2 -2
  6. package/dist/{agent-run-outcome-BDxby7zK.d.ts → agent-run-outcome-B7w8HpoL.d.ts} +1 -1
  7. package/dist/auth/index.d.ts +2 -2
  8. package/dist/auth/index.js +1 -1
  9. package/dist/{browser-interactive-control-controller-C2qVGzQz.d.ts → browser-interactive-control-controller-C-3MDol8.d.ts} +1 -1
  10. package/dist/{client-Co3TZfTd.d.ts → client-AXO7ykS7.d.ts} +5 -5
  11. package/dist/{client-p2T45dAv.js → client-qSyPPokh.js} +84 -355
  12. package/dist/collaboration/index.d.ts +1 -1
  13. package/dist/collaboration/index.js +1 -1
  14. package/dist/{collaboration-C1JAl5kE.js → collaboration-B7QeBrFQ.js} +1 -1
  15. package/dist/core.d.ts +5 -5
  16. package/dist/core.js +3 -3
  17. package/dist/{errors-CKl_BSlD.js → errors-D1JIX7Jm.js} +13 -1
  18. package/dist/{index-Numcq5sH.d.ts → index-BPt77jdR.d.ts} +88 -3
  19. package/dist/index.d.ts +12 -12
  20. package/dist/index.js +6 -6
  21. package/dist/intelligence/index.js +1 -1
  22. package/dist/interactive-control.d.ts +1 -1
  23. package/dist/{interactive-controller-DV1HT3NR.js → interactive-controller-f_ePJqoh.js} +14 -8
  24. package/dist/{interactive-controller-Dghv9yMk.d.ts → interactive-controller-iYddZt8b.d.ts} +2 -2
  25. package/dist/{lines-CRlIO585.d.ts → lines-ggdLY7xy.d.ts} +1 -1
  26. package/dist/lines.d.ts +1 -1
  27. package/dist/lines.js +1 -1
  28. package/dist/{local-cli-auth-CdIM0B6p.js → local-cli-auth-D4T4wi9r.js} +1 -1
  29. package/dist/{mcp-local-BSvH4yAU.js → mcp-local-DjryqUiY.js} +1 -1
  30. package/dist/{preview-DlN1ee1K.d.ts → preview-CAiSrOuZ.d.ts} +3 -3
  31. package/dist/runtime.d.ts +6 -6
  32. package/dist/runtime.js +2 -2
  33. package/dist/{sandbox-DeE2MDx9.js → sandbox-DF2Z1lqW.js} +128 -558
  34. package/dist/{sandbox-fyuaDhc3.d.ts → sandbox-DsJ3ZJdA.d.ts} +5 -5
  35. package/dist/secp256k1-CyKOxB5J.js +2619 -0
  36. package/dist/session-gateway/index.d.ts +31 -25
  37. package/dist/session-gateway/index.js +75 -79
  38. package/dist/tangle/index.d.ts +2 -2
  39. package/dist/tangle/index.js +2 -2
  40. package/dist/tangle-OZRTCbY4.js +2848 -0
  41. package/dist/{types-C9w6MdZB.d.ts → types-BbgO-4f8.d.ts} +6 -2
  42. package/dist/utils-ChcSLv53.js +170 -0
  43. package/package.json +8 -7
  44. package/dist/tangle-SNShua9T.js +0 -1146
  45. /package/dist/{cli-auth-bundle-gs7xEnA1.d.ts → cli-auth-bundle-CTia4WWs.d.ts} +0 -0
  46. /package/dist/{cli-auth-bundle-ChOdvrjd.js → cli-auth-bundle-DzbqR2nA.js} +0 -0
  47. /package/dist/{errors-C6dll8Qf.d.ts → errors-DS32ViPj.d.ts} +0 -0
  48. /package/dist/{index-BKhRnV0i.d.ts → index-BXcL8P-U.d.ts} +0 -0
  49. /package/dist/{index-BSCz2Q0v.d.ts → index-BoQeoNOD.d.ts} +0 -0
  50. /package/dist/{preview-operations-BLsclF88.js → preview-operations-DqSo-IBm.js} +0 -0
  51. /package/dist/{terminal-stream-C9jxoB07.d.ts → terminal-stream-BUMu8Oae.d.ts} +0 -0
@@ -0,0 +1,2848 @@
1
+ import { y as readResponseJson } from "./errors-D1JIX7Jm.js";
2
+ import { n as createSandboxInstanceFromResponse } from "./sandbox-DF2Z1lqW.js";
3
+ import { _ as rotlBH, a as anumber, b as rotlSL, d as createXOFer, g as u32, h as toBytes$1, l as createHasher, m as swap32IfBE, n as abytes, o as aoutput, r as aexists, s as clean, t as Hash, v as rotlBL, x as split, y as rotlSH } from "./utils-ChcSLv53.js";
4
+ //#region src/tangle/abi.ts
5
+ /**
6
+ * Tangle Contract ABI Definitions
7
+ *
8
+ * Viem-compatible ABI for the ITangleJobs precompile, the AgentSandbox
9
+ * blueprint contract views/events, and ABI parameter definitions for
10
+ * encoding/decoding blueprint job inputs and outputs.
11
+ */
12
+ const ITangleJobsAbi = [
13
+ {
14
+ type: "function",
15
+ name: "submitJob",
16
+ inputs: [
17
+ {
18
+ name: "serviceId",
19
+ type: "uint64"
20
+ },
21
+ {
22
+ name: "jobIndex",
23
+ type: "uint8"
24
+ },
25
+ {
26
+ name: "inputs",
27
+ type: "bytes"
28
+ }
29
+ ],
30
+ outputs: [{
31
+ name: "callId",
32
+ type: "uint64"
33
+ }],
34
+ stateMutability: "payable"
35
+ },
36
+ {
37
+ type: "function",
38
+ name: "getJobCall",
39
+ inputs: [{
40
+ name: "serviceId",
41
+ type: "uint64"
42
+ }, {
43
+ name: "callId",
44
+ type: "uint64"
45
+ }],
46
+ outputs: [{
47
+ name: "",
48
+ type: "tuple",
49
+ components: [
50
+ {
51
+ name: "jobIndex",
52
+ type: "uint8"
53
+ },
54
+ {
55
+ name: "caller",
56
+ type: "address"
57
+ },
58
+ {
59
+ name: "createdAt",
60
+ type: "uint64"
61
+ },
62
+ {
63
+ name: "resultCount",
64
+ type: "uint32"
65
+ },
66
+ {
67
+ name: "payment",
68
+ type: "uint256"
69
+ },
70
+ {
71
+ name: "completed",
72
+ type: "bool"
73
+ }
74
+ ]
75
+ }],
76
+ stateMutability: "view"
77
+ },
78
+ {
79
+ type: "event",
80
+ name: "JobSubmitted",
81
+ inputs: [
82
+ {
83
+ name: "serviceId",
84
+ type: "uint64",
85
+ indexed: true
86
+ },
87
+ {
88
+ name: "callId",
89
+ type: "uint64",
90
+ indexed: true
91
+ },
92
+ {
93
+ name: "jobIndex",
94
+ type: "uint8",
95
+ indexed: false
96
+ },
97
+ {
98
+ name: "caller",
99
+ type: "address",
100
+ indexed: false
101
+ },
102
+ {
103
+ name: "inputs",
104
+ type: "bytes",
105
+ indexed: false
106
+ }
107
+ ]
108
+ },
109
+ {
110
+ type: "event",
111
+ name: "JobResultSubmitted",
112
+ inputs: [
113
+ {
114
+ name: "serviceId",
115
+ type: "uint64",
116
+ indexed: true
117
+ },
118
+ {
119
+ name: "callId",
120
+ type: "uint64",
121
+ indexed: true
122
+ },
123
+ {
124
+ name: "operator",
125
+ type: "address",
126
+ indexed: true
127
+ },
128
+ {
129
+ name: "result",
130
+ type: "bytes",
131
+ indexed: false
132
+ }
133
+ ]
134
+ }
135
+ ];
136
+ const SandboxCreateParamTypes = [{
137
+ name: "request",
138
+ type: "tuple",
139
+ components: [
140
+ {
141
+ name: "name",
142
+ type: "string"
143
+ },
144
+ {
145
+ name: "image",
146
+ type: "string"
147
+ },
148
+ {
149
+ name: "stack",
150
+ type: "string"
151
+ },
152
+ {
153
+ name: "agent_identifier",
154
+ type: "string"
155
+ },
156
+ {
157
+ name: "env_json",
158
+ type: "string"
159
+ },
160
+ {
161
+ name: "metadata_json",
162
+ type: "string"
163
+ },
164
+ {
165
+ name: "ssh_enabled",
166
+ type: "bool"
167
+ },
168
+ {
169
+ name: "ssh_public_key",
170
+ type: "string"
171
+ },
172
+ {
173
+ name: "web_terminal_enabled",
174
+ type: "bool"
175
+ },
176
+ {
177
+ name: "max_lifetime_seconds",
178
+ type: "uint64"
179
+ },
180
+ {
181
+ name: "idle_timeout_seconds",
182
+ type: "uint64"
183
+ },
184
+ {
185
+ name: "cpu_cores",
186
+ type: "uint64"
187
+ },
188
+ {
189
+ name: "memory_mb",
190
+ type: "uint64"
191
+ },
192
+ {
193
+ name: "disk_gb",
194
+ type: "uint64"
195
+ },
196
+ {
197
+ name: "tee_required",
198
+ type: "bool"
199
+ },
200
+ {
201
+ name: "tee_type",
202
+ type: "uint8"
203
+ },
204
+ {
205
+ name: "attestation_nonce",
206
+ type: "string"
207
+ },
208
+ {
209
+ name: "capabilities_json",
210
+ type: "string"
211
+ }
212
+ ]
213
+ }];
214
+ const SandboxIdParamTypes = [{
215
+ name: "request",
216
+ type: "tuple",
217
+ components: [{
218
+ name: "sandbox_id",
219
+ type: "string"
220
+ }]
221
+ }];
222
+ const SandboxCreateResponseParamTypes = [{
223
+ name: "response",
224
+ type: "tuple",
225
+ components: [{
226
+ name: "sandboxId",
227
+ type: "string"
228
+ }, {
229
+ name: "json",
230
+ type: "string"
231
+ }]
232
+ }];
233
+ const JsonResponseParamTypes = [{
234
+ name: "response",
235
+ type: "tuple",
236
+ components: [{
237
+ name: "json",
238
+ type: "string"
239
+ }]
240
+ }];
241
+ const AgentSandboxBlueprintAbi = [
242
+ {
243
+ type: "function",
244
+ name: "getAvailableCapacity",
245
+ inputs: [],
246
+ outputs: [{
247
+ name: "available",
248
+ type: "uint32"
249
+ }],
250
+ stateMutability: "view"
251
+ },
252
+ {
253
+ type: "function",
254
+ name: "getServiceStats",
255
+ inputs: [],
256
+ outputs: [{
257
+ name: "totalSandboxes",
258
+ type: "uint32"
259
+ }, {
260
+ name: "totalCapacity",
261
+ type: "uint32"
262
+ }],
263
+ stateMutability: "view"
264
+ },
265
+ {
266
+ type: "function",
267
+ name: "getOperatorLoad",
268
+ inputs: [{
269
+ name: "operator",
270
+ type: "address"
271
+ }],
272
+ outputs: [{
273
+ name: "active",
274
+ type: "uint32"
275
+ }, {
276
+ name: "max",
277
+ type: "uint32"
278
+ }],
279
+ stateMutability: "view"
280
+ },
281
+ {
282
+ type: "function",
283
+ name: "getSandboxOperator",
284
+ inputs: [{
285
+ name: "sandboxId",
286
+ type: "string"
287
+ }],
288
+ outputs: [{
289
+ name: "",
290
+ type: "address"
291
+ }],
292
+ stateMutability: "view"
293
+ },
294
+ {
295
+ type: "function",
296
+ name: "isSandboxActive",
297
+ inputs: [{
298
+ name: "sandboxId",
299
+ type: "string"
300
+ }],
301
+ outputs: [{
302
+ name: "",
303
+ type: "bool"
304
+ }],
305
+ stateMutability: "view"
306
+ },
307
+ {
308
+ type: "event",
309
+ name: "OperatorAssigned",
310
+ inputs: [
311
+ {
312
+ name: "serviceId",
313
+ type: "uint64",
314
+ indexed: true
315
+ },
316
+ {
317
+ name: "callId",
318
+ type: "uint64",
319
+ indexed: true
320
+ },
321
+ {
322
+ name: "operator",
323
+ type: "address",
324
+ indexed: true
325
+ }
326
+ ]
327
+ },
328
+ {
329
+ type: "event",
330
+ name: "OperatorRouted",
331
+ inputs: [
332
+ {
333
+ name: "serviceId",
334
+ type: "uint64",
335
+ indexed: true
336
+ },
337
+ {
338
+ name: "callId",
339
+ type: "uint64",
340
+ indexed: true
341
+ },
342
+ {
343
+ name: "operator",
344
+ type: "address",
345
+ indexed: true
346
+ }
347
+ ]
348
+ },
349
+ {
350
+ type: "event",
351
+ name: "SandboxCreated",
352
+ inputs: [{
353
+ name: "sandboxHash",
354
+ type: "bytes32",
355
+ indexed: true
356
+ }, {
357
+ name: "operator",
358
+ type: "address",
359
+ indexed: true
360
+ }]
361
+ },
362
+ {
363
+ type: "event",
364
+ name: "SandboxDeleted",
365
+ inputs: [{
366
+ name: "sandboxHash",
367
+ type: "bytes32",
368
+ indexed: true
369
+ }, {
370
+ name: "operator",
371
+ type: "address",
372
+ indexed: true
373
+ }]
374
+ }
375
+ ];
376
+ //#endregion
377
+ //#region src/tangle/types.ts
378
+ /**
379
+ * Tangle Sandbox Client types and constants.
380
+ */
381
+ /** Tangle mainnet chain ID. */
382
+ const TANGLE_CHAIN_ID = 5845;
383
+ /** ITangleJobs precompile contract address. */
384
+ const TANGLE_JOBS_CONTRACT = "0x0000000000000000000000000000000000000808";
385
+ /** Job indices matching the blueprint's job IDs. */
386
+ const JOB_SANDBOX_CREATE = 0;
387
+ const JOB_SANDBOX_DELETE = 1;
388
+ //#endregion
389
+ //#region src/tangle/chain-client.ts
390
+ function confidentialFromOptions(options) {
391
+ if (options.confidential) return options.confidential;
392
+ const profile = options.backend?.profile;
393
+ if (typeof profile === "object" && profile?.confidential) return profile.confidential;
394
+ }
395
+ function teeTypeId(tee) {
396
+ switch (tee) {
397
+ case "tdx":
398
+ case "phala-dstack": return 1;
399
+ case "nitro": return 2;
400
+ case "sev-snp": return 3;
401
+ case "any":
402
+ case void 0: return 0;
403
+ default: throw new Error(`Unsupported TEE type for Tangle blueprint: ${tee}`);
404
+ }
405
+ }
406
+ function teeCreateValues(options) {
407
+ const confidential = confidentialFromOptions(options);
408
+ const teeRequired = Boolean(confidential?.tee);
409
+ return [
410
+ teeRequired,
411
+ teeRequired ? teeTypeId(confidential?.tee) : 0,
412
+ confidential?.attestationNonce ?? ""
413
+ ];
414
+ }
415
+ var TangleChainClient = class {
416
+ config;
417
+ publicClient = null;
418
+ walletClient = null;
419
+ account = null;
420
+ constructor(config) {
421
+ this.config = config;
422
+ }
423
+ async ensureInitialized() {
424
+ if (this.publicClient && this.walletClient) return {
425
+ publicClient: this.publicClient,
426
+ walletClient: this.walletClient
427
+ };
428
+ const rpcUrl = this.config.rpcUrl;
429
+ if (typeof rpcUrl !== "string" || rpcUrl.trim().length === 0) throw new Error("TangleSandboxClient requires rpcUrl: the SDK has no default Tangle RPC endpoint");
430
+ let viem;
431
+ try {
432
+ viem = await import("viem");
433
+ } catch {
434
+ throw new Error("viem is required for TangleSandboxClient. Install it: npm install viem");
435
+ }
436
+ const chain = {
437
+ id: TANGLE_CHAIN_ID,
438
+ name: "Tangle",
439
+ nativeCurrency: {
440
+ name: "TNT",
441
+ symbol: "TNT",
442
+ decimals: 18
443
+ },
444
+ rpcUrls: { default: { http: [rpcUrl] } }
445
+ };
446
+ const transport = viem.http(rpcUrl);
447
+ this.publicClient = viem.createPublicClient({
448
+ chain,
449
+ transport
450
+ });
451
+ if (this.config.privateKey) {
452
+ const { privateKeyToAccount } = await import("viem/accounts");
453
+ this.account = privateKeyToAccount(this.config.privateKey);
454
+ this.walletClient = viem.createWalletClient({
455
+ account: this.account,
456
+ chain,
457
+ transport
458
+ });
459
+ } else if (this.config.wallet) {
460
+ const wallet = this.config.wallet;
461
+ this.walletClient = wallet;
462
+ this.account = wallet.account ?? null;
463
+ } else throw new Error("TangleSandboxClient requires either privateKey or wallet");
464
+ return {
465
+ publicClient: this.publicClient,
466
+ walletClient: this.walletClient
467
+ };
468
+ }
469
+ encodeSandboxCreateInputs(options) {
470
+ if ((options.sshPublicKeys?.length ?? 0) > 1) throw new Error("Tangle sandbox creation accepts one SSH public key; pass at most one sshPublicKeys entry");
471
+ const [teeRequired, teeType, attestationNonce] = teeCreateValues(options);
472
+ return {
473
+ types: SandboxCreateParamTypes,
474
+ values: [{
475
+ name: options.name ?? "",
476
+ image: options.environment ?? "",
477
+ stack: "",
478
+ agent_identifier: "",
479
+ env_json: options.env ? JSON.stringify(options.env) : "",
480
+ metadata_json: options.metadata ? JSON.stringify(options.metadata) : "",
481
+ ssh_enabled: options.sshEnabled ?? false,
482
+ ssh_public_key: options.sshPublicKeys?.[0] ?? "",
483
+ web_terminal_enabled: options.webTerminalEnabled ?? false,
484
+ max_lifetime_seconds: BigInt(options.maxLifetimeSeconds ?? 0),
485
+ idle_timeout_seconds: BigInt(options.idleTimeoutSeconds ?? 0),
486
+ cpu_cores: BigInt(options.resources?.cpuCores ?? 0),
487
+ memory_mb: BigInt(options.resources?.memoryMB ?? 0),
488
+ disk_gb: BigInt(options.resources?.diskGB ?? 0),
489
+ tee_required: teeRequired,
490
+ tee_type: teeType,
491
+ attestation_nonce: attestationNonce,
492
+ capabilities_json: options.capabilities?.length ? JSON.stringify(options.capabilities) : ""
493
+ }]
494
+ };
495
+ }
496
+ encodeSandboxIdInputs(sandboxId) {
497
+ return {
498
+ types: SandboxIdParamTypes,
499
+ values: [{ sandbox_id: sandboxId }]
500
+ };
501
+ }
502
+ async submitJobAndWait(jobIndex, encoded) {
503
+ const { publicClient, walletClient } = await this.ensureInitialized();
504
+ const viem = await import("viem");
505
+ const contractAddress = this.config.contractAddress ?? "0x0000000000000000000000000000000000000808";
506
+ const serviceId = this.config.serviceId;
507
+ const inputs = viem.encodeAbiParameters(encoded.types, encoded.values);
508
+ const hash = await walletClient.writeContract({
509
+ address: contractAddress,
510
+ abi: ITangleJobsAbi,
511
+ functionName: "submitJob",
512
+ args: [
513
+ serviceId,
514
+ jobIndex,
515
+ inputs
516
+ ]
517
+ });
518
+ const receipt = await publicClient.waitForTransactionReceipt({ hash });
519
+ const jobSubmittedEvent = receipt.logs.find((log) => {
520
+ try {
521
+ return viem.decodeEventLog({
522
+ abi: ITangleJobsAbi,
523
+ data: log.data,
524
+ topics: log.topics
525
+ }).eventName === "JobSubmitted";
526
+ } catch {
527
+ return false;
528
+ }
529
+ });
530
+ if (!jobSubmittedEvent) throw new Error("JobSubmitted event not found in transaction receipt");
531
+ const callId = viem.decodeEventLog({
532
+ abi: ITangleJobsAbi,
533
+ data: jobSubmittedEvent.data,
534
+ topics: jobSubmittedEvent.topics
535
+ }).args.callId;
536
+ const timeoutMs = this.config.jobTimeoutMs ?? 144e5;
537
+ const pollIntervalMs = this.config.pollIntervalMs ?? 5e3;
538
+ const deadline = Date.now() + timeoutMs;
539
+ while (Date.now() < deadline) {
540
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
541
+ const jobCall = await publicClient.readContract({
542
+ address: contractAddress,
543
+ abi: ITangleJobsAbi,
544
+ functionName: "getJobCall",
545
+ args: [serviceId, callId]
546
+ });
547
+ if (jobCall.completed) return {
548
+ result: jobCall,
549
+ callId,
550
+ blockNumber: receipt.blockNumber
551
+ };
552
+ }
553
+ throw new Error(`Job ${jobIndex} (callId=${callId}) did not complete within ${timeoutMs}ms`);
554
+ }
555
+ async getJobResult(callId, fromBlock) {
556
+ const { publicClient } = await this.ensureInitialized();
557
+ const viem = await import("viem");
558
+ const contractAddress = this.config.contractAddress ?? "0x0000000000000000000000000000000000000808";
559
+ const logs = await publicClient.getLogs({
560
+ address: contractAddress,
561
+ event: viem.parseAbiItem("event JobResultSubmitted(uint64 indexed serviceId, uint64 indexed callId, address indexed operator, bytes result)"),
562
+ args: {
563
+ serviceId: this.config.serviceId,
564
+ callId
565
+ },
566
+ fromBlock: fromBlock ?? "earliest"
567
+ });
568
+ if (logs.length === 0) return null;
569
+ return logs[0]?.args.result ?? null;
570
+ }
571
+ async getAvailableCapacity() {
572
+ const { publicClient } = await this.ensureInitialized();
573
+ if (!this.config.blueprintContractAddress) throw new Error("blueprintContractAddress is required for getAvailableCapacity");
574
+ const result = await publicClient.readContract({
575
+ address: this.config.blueprintContractAddress,
576
+ abi: AgentSandboxBlueprintAbi,
577
+ functionName: "getAvailableCapacity"
578
+ });
579
+ return Number(result);
580
+ }
581
+ async getServiceStats() {
582
+ const { publicClient } = await this.ensureInitialized();
583
+ if (!this.config.blueprintContractAddress) throw new Error("blueprintContractAddress is required for getServiceStats");
584
+ const [totalSandboxes, totalCapacity] = await publicClient.readContract({
585
+ address: this.config.blueprintContractAddress,
586
+ abi: AgentSandboxBlueprintAbi,
587
+ functionName: "getServiceStats"
588
+ });
589
+ return {
590
+ totalSandboxes: Number(totalSandboxes),
591
+ totalCapacity: Number(totalCapacity)
592
+ };
593
+ }
594
+ getResponseParamTypes(jobIndex) {
595
+ if (jobIndex === 0) return SandboxCreateResponseParamTypes;
596
+ return JsonResponseParamTypes;
597
+ }
598
+ /**
599
+ * Sign a message with the job submitter's key (EIP-191 personal_sign).
600
+ *
601
+ * This is the credential for the operator API's session flow: the operator
602
+ * recovers the signer address and binds it to sandbox ownership, so only
603
+ * the key that submitted the create job can mint a session that manages
604
+ * that sandbox's secrets.
605
+ */
606
+ async signMessage(message) {
607
+ await this.ensureInitialized();
608
+ const account = this.account;
609
+ if (!account) throw new Error("TangleChainClient has no account to sign with; privateKey or wallet is required");
610
+ if (this.config.privateKey) {
611
+ if (typeof account.signMessage !== "function") throw new Error("Configured account cannot sign messages; an EIP-191 signer is required for operator sessions");
612
+ return account.signMessage({ message });
613
+ }
614
+ const walletClient = this.walletClient;
615
+ if (!walletClient) throw new Error("TangleChainClient has no wallet client; privateKey or wallet is required");
616
+ return walletClient.signMessage({
617
+ account,
618
+ message
619
+ });
620
+ }
621
+ };
622
+ //#endregion
623
+ //#region src/tangle/operator-auth.ts
624
+ const SESSION_REFRESH_MARGIN_MS = 6e4;
625
+ var OperatorSessionError = class extends Error {
626
+ constructor(message, status) {
627
+ super(message);
628
+ this.status = status;
629
+ this.name = "OperatorSessionError";
630
+ }
631
+ };
632
+ /**
633
+ * A bearer session with the blueprint operator API, minted by proving control
634
+ * of the job submitter's key. Establish lazily and reuse until near expiry;
635
+ * the caller retries with a fresh session on 401.
636
+ */
637
+ var OperatorSession = class OperatorSession {
638
+ constructor(token, address, expiresAtMs) {
639
+ this.token = token;
640
+ this.address = address;
641
+ this.expiresAtMs = expiresAtMs;
642
+ }
643
+ get signerAddress() {
644
+ return this.address;
645
+ }
646
+ /** True when the token is within the refresh margin of expiry. */
647
+ needsRefresh(nowMs = Date.now()) {
648
+ return nowMs >= this.expiresAtMs - SESSION_REFRESH_MARGIN_MS;
649
+ }
650
+ authorizationHeader() {
651
+ return `Bearer ${this.token}`;
652
+ }
653
+ /**
654
+ * Run the challenge-response flow against an operator API base URL.
655
+ *
656
+ * `signMessage` must implement EIP-191 personal_sign with the SAME key that
657
+ * submitted the sandbox create job — the operator binds ownership to the
658
+ * recovered address, so any other key yields a session that owns nothing.
659
+ */
660
+ static async establish(baseUrl, signMessage, fetchImpl = fetch) {
661
+ const root = baseUrl.replace(/\/+$/, "");
662
+ const challengeResponse = await fetchImpl(`${root}/api/auth/challenge`, { method: "POST" });
663
+ if (!challengeResponse.ok) throw new OperatorSessionError(`Operator challenge failed (HTTP ${challengeResponse.status})`, challengeResponse.status);
664
+ const challenge = await challengeResponse.json();
665
+ if (!challenge?.nonce || !challenge?.message) throw new OperatorSessionError("Operator challenge response is missing nonce/message");
666
+ const signature = await signMessage(challenge.message);
667
+ const sessionResponse = await fetchImpl(`${root}/api/auth/session`, {
668
+ method: "POST",
669
+ headers: { "Content-Type": "application/json" },
670
+ body: JSON.stringify({
671
+ nonce: challenge.nonce,
672
+ signature
673
+ })
674
+ });
675
+ if (!sessionResponse.ok) {
676
+ const body = await sessionResponse.text().catch(() => "");
677
+ throw new OperatorSessionError(`Operator session rejected (HTTP ${sessionResponse.status}): ${body.slice(0, 200)}`, sessionResponse.status);
678
+ }
679
+ const session = await sessionResponse.json();
680
+ if (!session?.token) throw new OperatorSessionError("Operator session response is missing a token");
681
+ return new OperatorSession(session.token, session.address, session.expires_at * 1e3);
682
+ }
683
+ };
684
+ //#endregion
685
+ //#region src/tangle/client.ts
686
+ /**
687
+ * TangleSandboxClient — on-chain sandbox lifecycle via EVM calls.
688
+ *
689
+ * Implements HttpClient so `SandboxInstance` works unchanged. Lifecycle
690
+ * operations (create/stop/resume/delete) go on-chain via Tangle jobs, and
691
+ * runtime operations are routed directly to the sandbox runtime URL
692
+ * returned by the on-chain job result.
693
+ */
694
+ function randomHexToken(bytes) {
695
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.getRandomValues !== "function") throw new Error("randomHexToken: globalThis.crypto.getRandomValues is unavailable; this runtime cannot generate cryptographically secure nonces. Run on a host with WebCrypto support (Node 20+, browsers, Workers).");
696
+ const buf = new Uint8Array(bytes);
697
+ globalThis.crypto.getRandomValues(buf);
698
+ return Array.from(buf).map((b) => b.toString(16).padStart(2, "0")).join("");
699
+ }
700
+ /** Key names that look like credentials. Heuristic, deliberately loud-but-not-blocking. */
701
+ const SECRET_SHAPED_KEY = /(?:secret|token|password|passwd|api[_-]?key|private[_-]?key|credential)/i;
702
+ /**
703
+ * `env` on the Tangle driver is ABI-encoded into the job calldata and is
704
+ * public on-chain forever. Warn (not block) when a key looks like a
705
+ * credential so the common mistake surfaces at the call site instead of on
706
+ * a block explorer.
707
+ */
708
+ function warnSecretShapedEnvKeys(env) {
709
+ if (!env) return;
710
+ const offenders = Object.keys(env).filter((key) => SECRET_SHAPED_KEY.test(key));
711
+ if (offenders.length === 0) return;
712
+ console.warn(`[tangle-sandbox] These env keys are published on-chain in the job calldata and are permanently public: ${offenders.join(", ")}. Pass confidential values via create({ tangleSecrets }) instead (requires operatorApiUrl; delivered over TLS via the operator's 2-phase secret endpoint).`);
713
+ }
714
+ function attestationNonceFromOptions(options) {
715
+ const direct = options.confidential?.attestationNonce;
716
+ if (direct) return direct;
717
+ const profile = options.backend?.profile;
718
+ if (typeof profile === "object") return profile.confidential?.attestationNonce;
719
+ }
720
+ function withAttestationNonce(options) {
721
+ if (options.confidential?.attestationRefresh && !options.confidential.attestationNonce) return {
722
+ ...options,
723
+ confidential: {
724
+ ...options.confidential,
725
+ attestationNonce: randomHexToken(32)
726
+ }
727
+ };
728
+ const profile = options.backend?.profile;
729
+ if (options.backend && typeof profile === "object" && profile.confidential?.attestationRefresh && !profile.confidential.attestationNonce) return {
730
+ ...options,
731
+ backend: {
732
+ ...options.backend,
733
+ profile: {
734
+ ...profile,
735
+ confidential: {
736
+ ...profile.confidential,
737
+ attestationNonce: randomHexToken(32)
738
+ }
739
+ }
740
+ }
741
+ };
742
+ return options;
743
+ }
744
+ function requirePathGroup(match, index) {
745
+ const value = match[index];
746
+ if (value === void 0) throw new Error(`Path matcher missing group ${index}`);
747
+ return value;
748
+ }
749
+ /** Narrow one field of already-parsed JSON to a record without widening
750
+ * the boundary to `unknown`. */
751
+ function recordField(raw, key) {
752
+ const value = raw[key];
753
+ return value && typeof value === "object" ? value : void 0;
754
+ }
755
+ function readString(record, keys) {
756
+ if (!record) return void 0;
757
+ for (const key of keys) {
758
+ const value = record[key];
759
+ if (typeof value === "string" && value.length > 0) return value;
760
+ }
761
+ }
762
+ /** The incarnation fields are one contract, not three independent hints. */
763
+ function classifyFilesystemIncarnation(value) {
764
+ const rawId = value.filesystemIncarnationId;
765
+ const rawProvenance = value.filesystemIncarnationProvenance;
766
+ const rawReadiness = value.filesystemIncarnationReadiness;
767
+ const id = typeof rawId === "string" && rawId.length > 0 ? rawId : void 0;
768
+ const provenance = rawProvenance === "fresh" || rawProvenance === "restored" || rawProvenance === "unknown" ? rawProvenance : void 0;
769
+ const readiness = rawReadiness === "transitioning" || rawReadiness === "ready" ? rawReadiness : void 0;
770
+ return {
771
+ complete: id !== void 0 && provenance !== void 0 && readiness !== void 0,
772
+ id,
773
+ provenance,
774
+ readiness
775
+ };
776
+ }
777
+ function runtimeCredentialsAllowed(incarnation) {
778
+ return incarnation.complete && incarnation.readiness === "ready";
779
+ }
780
+ function entryMetadata(entry) {
781
+ const metadata = {
782
+ ...entry.metadata ?? {},
783
+ ...entry.teeAttestationJson ? { teeAttestationJson: entry.teeAttestationJson } : {},
784
+ ...entry.teePublicKeyJson ? { teePublicKeyJson: entry.teePublicKeyJson } : {},
785
+ ...entry.attestationNonce ? { attestationNonce: entry.attestationNonce } : {}
786
+ };
787
+ return Object.keys(metadata).length > 0 ? metadata : void 0;
788
+ }
789
+ function sandboxInfoFromEntry(entry) {
790
+ const incarnation = classifyFilesystemIncarnation(entry);
791
+ const allowRuntime = runtimeCredentialsAllowed(incarnation);
792
+ return {
793
+ id: entry.id,
794
+ name: entry.name,
795
+ filesystemIncarnationId: incarnation.complete ? incarnation.id : void 0,
796
+ filesystemIncarnationProvenance: incarnation.complete ? incarnation.provenance : void 0,
797
+ filesystemIncarnationReadiness: incarnation.complete ? incarnation.readiness : void 0,
798
+ status: entry.status === "deleted" ? "stopped" : entry.status,
799
+ connection: allowRuntime && entry.runtimeUrl ? {
800
+ runtimeUrl: entry.runtimeUrl,
801
+ authToken: entry.runtimeToken
802
+ } : void 0,
803
+ metadata: entryMetadata(entry),
804
+ createdAt: entry.createdAt
805
+ };
806
+ }
807
+ function sandboxEntryFromWire(fallbackId, raw) {
808
+ const connection = recordField(raw, "connection");
809
+ const metadata = recordField(raw, "metadata");
810
+ const id = readString(raw, [
811
+ "id",
812
+ "sandboxId",
813
+ "sandbox_id"
814
+ ]) ?? fallbackId;
815
+ const runtimeUrl = readString(connection, ["runtimeUrl", "sidecar_url"]) ?? readString(raw, ["runtimeUrl", "sidecar_url"]) ?? "";
816
+ const runtimeToken = readString(connection, ["authToken", "runtimeToken"]) ?? readString(raw, [
817
+ "authToken",
818
+ "runtimeToken",
819
+ "token"
820
+ ]) ?? "";
821
+ const tupleField = (key) => {
822
+ const value = raw[key];
823
+ return typeof value === "string" ? value : value;
824
+ };
825
+ const tupleId = tupleField("filesystemIncarnationId") === void 0 ? void 0 : typeof tupleField("filesystemIncarnationId") === "string" ? tupleField("filesystemIncarnationId") : "";
826
+ const tupleProvenance = tupleField("filesystemIncarnationProvenance") === void 0 ? void 0 : tupleField("filesystemIncarnationProvenance");
827
+ const tupleReadiness = tupleField("filesystemIncarnationReadiness") === void 0 ? void 0 : tupleField("filesystemIncarnationReadiness");
828
+ const rawStatus = readString(raw, ["status"]) ?? "running";
829
+ const createdAtRaw = readString(raw, ["createdAt", "created_at"]);
830
+ const createdAt = createdAtRaw ? new Date(createdAtRaw) : /* @__PURE__ */ new Date();
831
+ return {
832
+ id,
833
+ name: readString(raw, ["name"]),
834
+ filesystemIncarnationId: tupleId,
835
+ filesystemIncarnationProvenance: tupleProvenance,
836
+ filesystemIncarnationReadiness: tupleReadiness,
837
+ runtimeUrl,
838
+ runtimeToken,
839
+ status: rawStatus === "stopped" || rawStatus === "deleted" || rawStatus === "running" ? rawStatus : "running",
840
+ createdAt,
841
+ metadata,
842
+ teeAttestationJson: readString(raw, ["teeAttestationJson"]),
843
+ teePublicKeyJson: readString(raw, ["teePublicKeyJson"]),
844
+ attestationNonce: readString(raw, ["attestationNonce"])
845
+ };
846
+ }
847
+ var TangleSandboxClient = class {
848
+ chain;
849
+ sandboxes = /* @__PURE__ */ new Map();
850
+ operatorApiUrl;
851
+ operatorApiToken;
852
+ operatorSession = null;
853
+ constructor(config) {
854
+ if (!config.privateKey && !config.wallet) throw new Error("TangleSandboxClient requires either privateKey or wallet");
855
+ this.chain = new TangleChainClient(config);
856
+ this.operatorApiUrl = config.operatorApiUrl?.replace(/\/+$/, "");
857
+ this.operatorApiToken = config.operatorApiToken;
858
+ }
859
+ /**
860
+ * Create a sandbox via on-chain job submission.
861
+ *
862
+ * Secrets never ride the chain: `options.tangleSecrets` is delivered to the
863
+ * operator's 2-phase provisioning endpoint over an EIP-191-authenticated
864
+ * session after the job completes (requires `operatorApiUrl`). Everything
865
+ * in `options.env` IS published on-chain in the job calldata — secret-shaped
866
+ * keys there trigger a warning pointing at `tangleSecrets`.
867
+ */
868
+ async create(options) {
869
+ if (options?.billingOwnerId !== void 0) throw new Error("billingOwnerId is supported only by the HTTP Sandbox API client");
870
+ warnSecretShapedEnvKeys(options?.env);
871
+ const tangleSecrets = options?.tangleSecrets;
872
+ if (tangleSecrets && Object.keys(tangleSecrets).length > 0) {
873
+ if (!this.operatorApiUrl) throw new Error("tangleSecrets requires operatorApiUrl: secrets are delivered via the operator's 2-phase provisioning endpoint, never via on-chain calldata. Configure operatorApiUrl, or pass the values as plain env only if they are NOT confidential (env_json is public on-chain forever).");
874
+ }
875
+ const createOptions = withAttestationNonce(options ?? {});
876
+ const encoded = this.chain.encodeSandboxCreateInputs(createOptions);
877
+ const { result: _result, callId, blockNumber } = await this.chain.submitJobAndWait(0, encoded);
878
+ const resultBytes = await this.chain.getJobResult(callId, blockNumber);
879
+ let sandboxId;
880
+ let responseJson = {};
881
+ if (resultBytes) try {
882
+ const [decoded] = (await import("viem")).decodeAbiParameters(this.chain.getResponseParamTypes(0), resultBytes);
883
+ const decodedEntry = decoded;
884
+ sandboxId = decodedEntry.sandboxId;
885
+ try {
886
+ responseJson = JSON.parse(decodedEntry.json);
887
+ } catch {}
888
+ } catch {
889
+ throw new Error("Failed to decode create job result");
890
+ }
891
+ else throw new Error("No result returned from create job");
892
+ const wireEntry = sandboxEntryFromWire(sandboxId, responseJson);
893
+ if (wireEntry.runtimeUrl && !wireEntry.runtimeToken) throw new Error("Create job returned a runtime URL without an auth token");
894
+ const allowRuntime = runtimeCredentialsAllowed(classifyFilesystemIncarnation(wireEntry));
895
+ const entry = {
896
+ ...wireEntry,
897
+ id: sandboxId,
898
+ name: options?.name ?? wireEntry.name,
899
+ runtimeUrl: allowRuntime ? wireEntry.runtimeUrl : "",
900
+ runtimeToken: allowRuntime ? wireEntry.runtimeToken : "",
901
+ status: wireEntry.status,
902
+ createdAt: wireEntry.createdAt,
903
+ metadata: createOptions.metadata ?? wireEntry.metadata,
904
+ teeAttestationJson: wireEntry.teeAttestationJson ?? responseJson.teeAttestationJson,
905
+ teePublicKeyJson: wireEntry.teePublicKeyJson ?? responseJson.teePublicKeyJson,
906
+ attestationNonce: attestationNonceFromOptions(createOptions) ?? wireEntry.attestationNonce
907
+ };
908
+ this.sandboxes.set(sandboxId, entry);
909
+ if (tangleSecrets && Object.keys(tangleSecrets).length > 0) await this.injectSecrets(sandboxId, tangleSecrets);
910
+ return createSandboxInstanceFromResponse(this, sandboxInfoFromEntry(entry));
911
+ }
912
+ /**
913
+ * Get a sandbox by id. Rehydrates from the operator API when configured so
914
+ * app servers can resolve sandboxes created by earlier requests.
915
+ */
916
+ async get(id) {
917
+ const response = await this.fetch(`/v1/sandboxes/${encodeURIComponent(id)}`);
918
+ if (response.status === 404) return null;
919
+ const data = await readResponseJson(response);
920
+ return createSandboxInstanceFromResponse(this, sandboxInfoFromEntry(sandboxEntryFromWire(id, data)));
921
+ }
922
+ /**
923
+ * Route interception for SandboxInstance lifecycle calls.
924
+ *
925
+ * SandboxInstance calls this.client.fetch() for:
926
+ * - GET /v1/sandboxes/:id → return from local tracking
927
+ * - POST /v1/sandboxes/:id/stop → unsupported until blueprint exposes stop
928
+ * - POST /v1/sandboxes/:id/resume → unsupported until blueprint exposes resume
929
+ * - DELETE /v1/sandboxes/:id → on-chain JOB_SANDBOX_DELETE
930
+ */
931
+ async fetch(path, options) {
932
+ const method = options?.method ?? "GET";
933
+ const runtimeMatch = path.match(/^\/v1\/sandboxes\/([^/]+)\/runtime(\/.*)$/);
934
+ if (runtimeMatch) {
935
+ const id = decodeURIComponent(requirePathGroup(runtimeMatch, 1));
936
+ const runtimePath = requirePathGroup(runtimeMatch, 2);
937
+ return this.fetchRuntime(id, runtimePath, options);
938
+ }
939
+ const getMatch = path.match(/^\/v1\/sandboxes\/([^/]+)$/);
940
+ if (getMatch && method === "GET") {
941
+ const id = decodeURIComponent(requirePathGroup(getMatch, 1));
942
+ let entry = this.sandboxes.get(id);
943
+ if (this.operatorApiUrl) {
944
+ const operatorResponse = await this.fetchOperatorApi(`/api/sandboxes/${encodeURIComponent(id)}`, { method: "GET" });
945
+ if (!operatorResponse.ok) return operatorResponse;
946
+ entry = sandboxEntryFromWire(id, await operatorResponse.json());
947
+ this.sandboxes.set(entry.id, entry);
948
+ }
949
+ if (!entry) return new Response(JSON.stringify({ error: "Not found" }), { status: 404 });
950
+ const info = sandboxInfoFromEntry(entry);
951
+ return new Response(JSON.stringify(info), {
952
+ status: 200,
953
+ headers: { "Content-Type": "application/json" }
954
+ });
955
+ }
956
+ const attestationMatch = path.match(/^\/v1\/sandboxes\/([^/]+)\/tee\/attestation$/);
957
+ if (attestationMatch && method === "GET") {
958
+ const id = decodeURIComponent(requirePathGroup(attestationMatch, 1));
959
+ if (this.operatorApiUrl) return this.fetchOperatorApi(`/api/sandboxes/${encodeURIComponent(id)}/tee/attestation`, options);
960
+ const response = await this.fetchRuntime(id, "/tee/attestation", {
961
+ ...options,
962
+ method: "GET"
963
+ });
964
+ if (!response.ok) return response;
965
+ const attestation = await response.json();
966
+ return new Response(JSON.stringify({
967
+ sandbox_id: id,
968
+ attestation
969
+ }), {
970
+ status: 200,
971
+ headers: { "Content-Type": "application/json" }
972
+ });
973
+ }
974
+ if (attestationMatch && method === "POST") {
975
+ if (this.operatorApiUrl) {
976
+ const id = decodeURIComponent(requirePathGroup(attestationMatch, 1));
977
+ return this.fetchOperatorApi(`/api/sandboxes/${encodeURIComponent(id)}/tee/attestation`, options);
978
+ }
979
+ return new Response(JSON.stringify({ error: "Nonce-bound TEE attestation requires the operator API and is not available through the direct sidecar Tangle client" }), {
980
+ status: 501,
981
+ headers: { "Content-Type": "application/json" }
982
+ });
983
+ }
984
+ const publicKeyMatch = path.match(/^\/v1\/sandboxes\/([^/]+)\/tee\/public-key$/);
985
+ if (publicKeyMatch && method === "GET") {
986
+ const id = decodeURIComponent(requirePathGroup(publicKeyMatch, 1));
987
+ if (this.operatorApiUrl) return this.fetchOperatorApi(`/api/sandboxes/${encodeURIComponent(id)}/tee/public-key`, options);
988
+ const response = await this.fetchRuntime(id, "/tee/public-key", {
989
+ ...options,
990
+ method: "GET"
991
+ });
992
+ if (!response.ok) return response;
993
+ const publicKey = await response.json();
994
+ return new Response(JSON.stringify({
995
+ sandbox_id: id,
996
+ public_key: publicKey
997
+ }), {
998
+ status: 200,
999
+ headers: { "Content-Type": "application/json" }
1000
+ });
1001
+ }
1002
+ if (path.match(/^\/v1\/sandboxes\/([^/]+)\/stop$/) && method === "POST") return new Response(JSON.stringify({ error: "Sandbox stop is not exposed by the current Tangle blueprint" }), {
1003
+ status: 501,
1004
+ headers: { "Content-Type": "application/json" }
1005
+ });
1006
+ if (path.match(/^\/v1\/sandboxes\/([^/]+)\/resume$/) && method === "POST") return new Response(JSON.stringify({ error: "Sandbox resume is not exposed by the current Tangle blueprint" }), {
1007
+ status: 501,
1008
+ headers: { "Content-Type": "application/json" }
1009
+ });
1010
+ const deleteMatch = path.match(/^\/v1\/sandboxes\/([^/]+)$/);
1011
+ if (deleteMatch && method === "DELETE") {
1012
+ const id = decodeURIComponent(requirePathGroup(deleteMatch, 1));
1013
+ const encoded = this.chain.encodeSandboxIdInputs(id);
1014
+ await this.chain.submitJobAndWait(1, encoded);
1015
+ const entry = this.sandboxes.get(id);
1016
+ if (entry) entry.status = "deleted";
1017
+ this.sandboxes.delete(id);
1018
+ return new Response(null, { status: 204 });
1019
+ }
1020
+ throw new Error(`Operation not supported via on-chain client: ${method} ${path}`);
1021
+ }
1022
+ async fetchRuntime(sandboxId, runtimePath, options) {
1023
+ let entry = this.sandboxes.get(sandboxId);
1024
+ if (this.operatorApiUrl) {
1025
+ const operatorResponse = await this.fetchOperatorApi(`/api/sandboxes/${encodeURIComponent(sandboxId)}`, { method: "GET" });
1026
+ if (!operatorResponse.ok) return operatorResponse;
1027
+ entry = sandboxEntryFromWire(sandboxId, await operatorResponse.json());
1028
+ this.sandboxes.set(entry.id, entry);
1029
+ }
1030
+ const incarnation = entry ? classifyFilesystemIncarnation(entry) : void 0;
1031
+ if (!entry || !incarnation || !runtimeCredentialsAllowed(incarnation) || !entry.runtimeUrl || !entry.runtimeToken) return new Response(JSON.stringify({ error: "Sandbox runtime unavailable" }), {
1032
+ status: 503,
1033
+ headers: { "Content-Type": "application/json" }
1034
+ });
1035
+ const headers = new Headers(options?.headers);
1036
+ headers.set("Authorization", `Bearer ${entry.runtimeToken}`);
1037
+ const isFormDataBody = typeof FormData !== "undefined" && options?.body instanceof FormData;
1038
+ if (!headers.has("Content-Type") && !isFormDataBody) headers.set("Content-Type", "application/json");
1039
+ const method = options?.method ?? "GET";
1040
+ return await fetch(`${entry.runtimeUrl.replace(/\/$/, "")}${runtimePath}`, {
1041
+ ...options,
1042
+ method,
1043
+ headers
1044
+ });
1045
+ }
1046
+ /**
1047
+ * Get available capacity from the blueprint contract.
1048
+ * Requires blueprintContractAddress in config.
1049
+ */
1050
+ async getAvailableCapacity() {
1051
+ return this.chain.getAvailableCapacity();
1052
+ }
1053
+ /**
1054
+ * Get service stats from the blueprint contract.
1055
+ * Requires blueprintContractAddress in config.
1056
+ */
1057
+ async getServiceStats() {
1058
+ return this.chain.getServiceStats();
1059
+ }
1060
+ /**
1061
+ * Mint or reuse the EIP-191 session for the operator API.
1062
+ *
1063
+ * The session is signed by the SAME key that submits jobs (`chain.signMessage`),
1064
+ * so the operator binds it to every sandbox this client created.
1065
+ */
1066
+ async getOperatorSession(force = false) {
1067
+ if (!this.operatorApiUrl) throw new Error("Operator API URL is not configured");
1068
+ if (!force && this.operatorSession && !this.operatorSession.needsRefresh()) return this.operatorSession;
1069
+ const session = await OperatorSession.establish(this.operatorApiUrl, (message) => this.chain.signMessage(message));
1070
+ this.operatorSession = session;
1071
+ return session;
1072
+ }
1073
+ /**
1074
+ * Deliver secrets to a sandbox via the operator's 2-phase provisioning
1075
+ * endpoint (`POST /api/sandboxes/:id/secrets`).
1076
+ *
1077
+ * Unlike `env`, these values never appear on-chain: they ride TLS to the
1078
+ * operator, which validates the session's recovered address against the
1079
+ * sandbox's on-chain creator before injecting.
1080
+ */
1081
+ async injectSecrets(sandboxId, secrets) {
1082
+ await this.withOperatorSession(sandboxId, async (session, url) => {
1083
+ return await fetch(`${url}/api/sandboxes/${encodeURIComponent(sandboxId)}/secrets`, {
1084
+ method: "POST",
1085
+ headers: {
1086
+ Authorization: session.authorizationHeader(),
1087
+ "Content-Type": "application/json"
1088
+ },
1089
+ body: JSON.stringify({ env_json: secrets })
1090
+ });
1091
+ }, "inject secrets into");
1092
+ }
1093
+ /** Read a sandbox's provisioned secret keys and credential availability. */
1094
+ async getSecrets(sandboxId) {
1095
+ return this.withOperatorSession(sandboxId, async (session, url) => {
1096
+ return await fetch(`${url}/api/sandboxes/${encodeURIComponent(sandboxId)}/secrets`, {
1097
+ method: "GET",
1098
+ headers: { Authorization: session.authorizationHeader() }
1099
+ });
1100
+ }, "read secrets for").then(async (response) => {
1101
+ const body = await response.json();
1102
+ return {
1103
+ sandboxId: body.sandbox_id ?? sandboxId,
1104
+ envJson: body.env_json ?? {},
1105
+ credentialsAvailable: Boolean(body.credentials_available)
1106
+ };
1107
+ });
1108
+ }
1109
+ /**
1110
+ * Run an operator-API request with a session, retrying once with a fresh
1111
+ * session on 401 (expired PASETO). Any other failure names the sandbox so
1112
+ * the caller can retry without losing the ID.
1113
+ */
1114
+ async withOperatorSession(sandboxId, request, action) {
1115
+ if (!this.operatorApiUrl) throw new Error(`Cannot ${action} sandbox ${sandboxId}: operatorApiUrl is not configured`);
1116
+ let session = await this.getOperatorSession();
1117
+ let response = await request(session, this.operatorApiUrl);
1118
+ if (response.status === 401) {
1119
+ session = await this.getOperatorSession(true);
1120
+ response = await request(session, this.operatorApiUrl);
1121
+ }
1122
+ if (!response.ok) {
1123
+ const body = await response.text().catch(() => "");
1124
+ throw new OperatorSessionError(`Failed to ${action} sandbox ${sandboxId} (HTTP ${response.status}): ${body.slice(0, 300)}`, response.status);
1125
+ }
1126
+ return response;
1127
+ }
1128
+ async fetchOperatorApi(path, options) {
1129
+ if (!this.operatorApiUrl) return new Response(JSON.stringify({ error: "Operator API URL is not configured" }), {
1130
+ status: 501,
1131
+ headers: { "Content-Type": "application/json" }
1132
+ });
1133
+ const headers = new Headers(options?.headers);
1134
+ if (this.operatorApiToken && !headers.has("Authorization")) headers.set("Authorization", `Bearer ${this.operatorApiToken}`);
1135
+ if (options?.body && !headers.has("Content-Type")) headers.set("Content-Type", "application/json");
1136
+ return fetch(`${this.operatorApiUrl}${path}`, {
1137
+ ...options,
1138
+ headers
1139
+ });
1140
+ }
1141
+ };
1142
+ //#endregion
1143
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/errors/version.js
1144
+ const version = "2.55.4";
1145
+ //#endregion
1146
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/errors/base.js
1147
+ let errorConfig = {
1148
+ getDocsUrl: ({ docsBaseUrl, docsPath = "", docsSlug }) => docsPath ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath}${docsSlug ? `#${docsSlug}` : ""}` : void 0,
1149
+ version: `viem@${version}`
1150
+ };
1151
+ var BaseError = class BaseError extends Error {
1152
+ constructor(shortMessage, args = {}) {
1153
+ const details = (() => {
1154
+ if (args.cause instanceof BaseError) return args.cause.details;
1155
+ if (args.cause?.message) return args.cause.message;
1156
+ return args.details;
1157
+ })();
1158
+ const docsPath = (() => {
1159
+ if (args.cause instanceof BaseError) return args.cause.docsPath || args.docsPath;
1160
+ return args.docsPath;
1161
+ })();
1162
+ const docsUrl = errorConfig.getDocsUrl?.({
1163
+ ...args,
1164
+ docsPath
1165
+ });
1166
+ const message = [
1167
+ shortMessage || "An error occurred.",
1168
+ "",
1169
+ ...args.metaMessages ? [...args.metaMessages, ""] : [],
1170
+ ...docsUrl ? [`Docs: ${docsUrl}`] : [],
1171
+ ...details ? [`Details: ${details}`] : [],
1172
+ ...errorConfig.version ? [`Version: ${errorConfig.version}`] : []
1173
+ ].join("\n");
1174
+ super(message, args.cause ? { cause: args.cause } : void 0);
1175
+ Object.defineProperty(this, "details", {
1176
+ enumerable: true,
1177
+ configurable: true,
1178
+ writable: true,
1179
+ value: void 0
1180
+ });
1181
+ Object.defineProperty(this, "docsPath", {
1182
+ enumerable: true,
1183
+ configurable: true,
1184
+ writable: true,
1185
+ value: void 0
1186
+ });
1187
+ Object.defineProperty(this, "metaMessages", {
1188
+ enumerable: true,
1189
+ configurable: true,
1190
+ writable: true,
1191
+ value: void 0
1192
+ });
1193
+ Object.defineProperty(this, "shortMessage", {
1194
+ enumerable: true,
1195
+ configurable: true,
1196
+ writable: true,
1197
+ value: void 0
1198
+ });
1199
+ Object.defineProperty(this, "version", {
1200
+ enumerable: true,
1201
+ configurable: true,
1202
+ writable: true,
1203
+ value: void 0
1204
+ });
1205
+ Object.defineProperty(this, "name", {
1206
+ enumerable: true,
1207
+ configurable: true,
1208
+ writable: true,
1209
+ value: "BaseError"
1210
+ });
1211
+ this.details = details;
1212
+ this.docsPath = docsPath;
1213
+ this.metaMessages = args.metaMessages;
1214
+ this.name = args.name ?? this.name;
1215
+ this.shortMessage = shortMessage;
1216
+ this.version = version;
1217
+ }
1218
+ walk(fn) {
1219
+ return walk(this, fn);
1220
+ }
1221
+ };
1222
+ function walk(err, fn) {
1223
+ if (fn?.(err)) return err;
1224
+ if (err && typeof err === "object" && "cause" in err && err.cause !== void 0) return walk(err.cause, fn);
1225
+ return fn ? null : err;
1226
+ }
1227
+ //#endregion
1228
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/errors/address.js
1229
+ var InvalidAddressError = class extends BaseError {
1230
+ constructor({ address }) {
1231
+ super(`Address "${address}" is invalid.`, {
1232
+ metaMessages: ["- Address must be a hex value of 20 bytes (40 hex characters).", "- Address must match its checksum counterpart."],
1233
+ name: "InvalidAddressError"
1234
+ });
1235
+ }
1236
+ };
1237
+ //#endregion
1238
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/data/isHex.js
1239
+ function isHex(value, { strict = true } = {}) {
1240
+ if (!value) return false;
1241
+ if (typeof value !== "string") return false;
1242
+ return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith("0x");
1243
+ }
1244
+ //#endregion
1245
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/errors/data.js
1246
+ var SliceOffsetOutOfBoundsError = class extends BaseError {
1247
+ constructor({ offset, position, size }) {
1248
+ super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset}" is out-of-bounds (size: ${size}).`, { name: "SliceOffsetOutOfBoundsError" });
1249
+ }
1250
+ };
1251
+ var SizeExceedsPaddingSizeError = class extends BaseError {
1252
+ constructor({ size, targetSize, type }) {
1253
+ super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" });
1254
+ }
1255
+ };
1256
+ //#endregion
1257
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/data/pad.js
1258
+ function pad(hexOrBytes, { dir, size = 32 } = {}) {
1259
+ if (typeof hexOrBytes === "string") return padHex(hexOrBytes, {
1260
+ dir,
1261
+ size
1262
+ });
1263
+ return padBytes(hexOrBytes, {
1264
+ dir,
1265
+ size
1266
+ });
1267
+ }
1268
+ function padHex(hex_, { dir, size = 32 } = {}) {
1269
+ if (size === null) return hex_;
1270
+ const hex = hex_.replace("0x", "");
1271
+ if (hex.length > size * 2) throw new SizeExceedsPaddingSizeError({
1272
+ size: Math.ceil(hex.length / 2),
1273
+ targetSize: size,
1274
+ type: "hex"
1275
+ });
1276
+ return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size * 2, "0")}`;
1277
+ }
1278
+ function padBytes(bytes, { dir, size = 32 } = {}) {
1279
+ if (size === null) return bytes;
1280
+ if (bytes.length > size) throw new SizeExceedsPaddingSizeError({
1281
+ size: bytes.length,
1282
+ targetSize: size,
1283
+ type: "bytes"
1284
+ });
1285
+ const paddedBytes = new Uint8Array(size);
1286
+ for (let i = 0; i < size; i++) {
1287
+ const padEnd = dir === "right";
1288
+ paddedBytes[padEnd ? i : size - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
1289
+ }
1290
+ return paddedBytes;
1291
+ }
1292
+ //#endregion
1293
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/errors/encoding.js
1294
+ var IntegerOutOfRangeError = class extends BaseError {
1295
+ constructor({ max, min, signed, size, value }) {
1296
+ super(`Number "${value}" is not in safe ${size ? `${size * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: "IntegerOutOfRangeError" });
1297
+ }
1298
+ };
1299
+ var SizeOverflowError = class extends BaseError {
1300
+ constructor({ givenSize, maxSize }) {
1301
+ super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" });
1302
+ }
1303
+ };
1304
+ //#endregion
1305
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/data/size.js
1306
+ /**
1307
+ * @description Retrieves the size of the value (in bytes).
1308
+ *
1309
+ * @param value The value (hex or byte array) to retrieve the size of.
1310
+ * @returns The size of the value (in bytes).
1311
+ */
1312
+ function size(value) {
1313
+ if (isHex(value, { strict: false })) return Math.ceil((value.length - 2) / 2);
1314
+ return value.length;
1315
+ }
1316
+ //#endregion
1317
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/encoding/fromHex.js
1318
+ function assertSize(hexOrBytes, { size: size$1 }) {
1319
+ if (size(hexOrBytes) > size$1) throw new SizeOverflowError({
1320
+ givenSize: size(hexOrBytes),
1321
+ maxSize: size$1
1322
+ });
1323
+ }
1324
+ /**
1325
+ * Decodes a hex value into a bigint.
1326
+ *
1327
+ * - Docs: https://viem.sh/docs/utilities/fromHex#hextobigint
1328
+ *
1329
+ * @param hex Hex value to decode.
1330
+ * @param opts Options.
1331
+ * @returns BigInt value.
1332
+ *
1333
+ * @example
1334
+ * import { hexToBigInt } from 'viem'
1335
+ * const data = hexToBigInt('0x1a4', { signed: true })
1336
+ * // 420n
1337
+ *
1338
+ * @example
1339
+ * import { hexToBigInt } from 'viem'
1340
+ * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })
1341
+ * // 420n
1342
+ */
1343
+ function hexToBigInt(hex, opts = {}) {
1344
+ const { signed } = opts;
1345
+ if (opts.size) assertSize(hex, { size: opts.size });
1346
+ const value = BigInt(hex);
1347
+ if (!signed) return value;
1348
+ const size = (hex.length - 2) / 2;
1349
+ if (value <= (1n << BigInt(size) * 8n - 1n) - 1n) return value;
1350
+ return value - BigInt(`0x${"f".padStart(size * 2, "f")}`) - 1n;
1351
+ }
1352
+ /**
1353
+ * Decodes a hex string into a number.
1354
+ *
1355
+ * - Docs: https://viem.sh/docs/utilities/fromHex#hextonumber
1356
+ *
1357
+ * @param hex Hex value to decode.
1358
+ * @param opts Options.
1359
+ * @returns Number value.
1360
+ *
1361
+ * @example
1362
+ * import { hexToNumber } from 'viem'
1363
+ * const data = hexToNumber('0x1a4')
1364
+ * // 420
1365
+ *
1366
+ * @example
1367
+ * import { hexToNumber } from 'viem'
1368
+ * const data = hexToNumber('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })
1369
+ * // 420
1370
+ */
1371
+ function hexToNumber(hex, opts = {}) {
1372
+ const value = hexToBigInt(hex, opts);
1373
+ const number = Number(value);
1374
+ if (!Number.isSafeInteger(number)) throw new IntegerOutOfRangeError({
1375
+ max: `${Number.MAX_SAFE_INTEGER}`,
1376
+ min: `${Number.MIN_SAFE_INTEGER}`,
1377
+ signed: opts.signed,
1378
+ size: opts.size,
1379
+ value: `${value}n`
1380
+ });
1381
+ return number;
1382
+ }
1383
+ //#endregion
1384
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/encoding/toHex.js
1385
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0"));
1386
+ /**
1387
+ * Encodes a string, number, bigint, or ByteArray into a hex string
1388
+ *
1389
+ * - Docs: https://viem.sh/docs/utilities/toHex
1390
+ * - Example: https://viem.sh/docs/utilities/toHex#usage
1391
+ *
1392
+ * @param value Value to encode.
1393
+ * @param opts Options.
1394
+ * @returns Hex value.
1395
+ *
1396
+ * @example
1397
+ * import { toHex } from 'viem'
1398
+ * const data = toHex('Hello world')
1399
+ * // '0x48656c6c6f20776f726c6421'
1400
+ *
1401
+ * @example
1402
+ * import { toHex } from 'viem'
1403
+ * const data = toHex(420)
1404
+ * // '0x1a4'
1405
+ *
1406
+ * @example
1407
+ * import { toHex } from 'viem'
1408
+ * const data = toHex('Hello world', { size: 32 })
1409
+ * // '0x48656c6c6f20776f726c64210000000000000000000000000000000000000000'
1410
+ */
1411
+ function toHex(value, opts = {}) {
1412
+ if (typeof value === "number" || typeof value === "bigint") return numberToHex(value, opts);
1413
+ if (typeof value === "string") return stringToHex(value, opts);
1414
+ if (typeof value === "boolean") return boolToHex(value, opts);
1415
+ return bytesToHex(value, opts);
1416
+ }
1417
+ /**
1418
+ * Encodes a boolean into a hex string
1419
+ *
1420
+ * - Docs: https://viem.sh/docs/utilities/toHex#booltohex
1421
+ *
1422
+ * @param value Value to encode.
1423
+ * @param opts Options.
1424
+ * @returns Hex value.
1425
+ *
1426
+ * @example
1427
+ * import { boolToHex } from 'viem'
1428
+ * const data = boolToHex(true)
1429
+ * // '0x1'
1430
+ *
1431
+ * @example
1432
+ * import { boolToHex } from 'viem'
1433
+ * const data = boolToHex(false)
1434
+ * // '0x0'
1435
+ *
1436
+ * @example
1437
+ * import { boolToHex } from 'viem'
1438
+ * const data = boolToHex(true, { size: 32 })
1439
+ * // '0x0000000000000000000000000000000000000000000000000000000000000001'
1440
+ */
1441
+ function boolToHex(value, opts = {}) {
1442
+ const hex = `0x${Number(value)}`;
1443
+ if (typeof opts.size === "number") {
1444
+ assertSize(hex, { size: opts.size });
1445
+ return pad(hex, { size: opts.size });
1446
+ }
1447
+ return hex;
1448
+ }
1449
+ /**
1450
+ * Encodes a bytes array into a hex string
1451
+ *
1452
+ * - Docs: https://viem.sh/docs/utilities/toHex#bytestohex
1453
+ *
1454
+ * @param value Value to encode.
1455
+ * @param opts Options.
1456
+ * @returns Hex value.
1457
+ *
1458
+ * @example
1459
+ * import { bytesToHex } from 'viem'
1460
+ * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
1461
+ * // '0x48656c6c6f20576f726c6421'
1462
+ *
1463
+ * @example
1464
+ * import { bytesToHex } from 'viem'
1465
+ * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]), { size: 32 })
1466
+ * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'
1467
+ */
1468
+ function bytesToHex(value, opts = {}) {
1469
+ let string = "";
1470
+ for (let i = 0; i < value.length; i++) string += hexes[value[i]];
1471
+ const hex = `0x${string}`;
1472
+ if (typeof opts.size === "number") {
1473
+ assertSize(hex, { size: opts.size });
1474
+ return pad(hex, {
1475
+ dir: "right",
1476
+ size: opts.size
1477
+ });
1478
+ }
1479
+ return hex;
1480
+ }
1481
+ /**
1482
+ * Encodes a number or bigint into a hex string
1483
+ *
1484
+ * - Docs: https://viem.sh/docs/utilities/toHex#numbertohex
1485
+ *
1486
+ * @param value Value to encode.
1487
+ * @param opts Options.
1488
+ * @returns Hex value.
1489
+ *
1490
+ * @example
1491
+ * import { numberToHex } from 'viem'
1492
+ * const data = numberToHex(420)
1493
+ * // '0x1a4'
1494
+ *
1495
+ * @example
1496
+ * import { numberToHex } from 'viem'
1497
+ * const data = numberToHex(420, { size: 32 })
1498
+ * // '0x00000000000000000000000000000000000000000000000000000000000001a4'
1499
+ */
1500
+ function numberToHex(value_, opts = {}) {
1501
+ const { signed, size } = opts;
1502
+ const value = BigInt(value_);
1503
+ let maxValue;
1504
+ if (size) if (signed) maxValue = (1n << BigInt(size) * 8n - 1n) - 1n;
1505
+ else maxValue = 2n ** (BigInt(size) * 8n) - 1n;
1506
+ else if (typeof value_ === "number") maxValue = BigInt(Number.MAX_SAFE_INTEGER);
1507
+ const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0;
1508
+ if (maxValue && value > maxValue || value < minValue) {
1509
+ const suffix = typeof value_ === "bigint" ? "n" : "";
1510
+ throw new IntegerOutOfRangeError({
1511
+ max: maxValue ? `${maxValue}${suffix}` : void 0,
1512
+ min: `${minValue}${suffix}`,
1513
+ signed,
1514
+ size,
1515
+ value: `${value_}${suffix}`
1516
+ });
1517
+ }
1518
+ const hex = `0x${(signed && value < 0 ? (1n << BigInt(size * 8)) + BigInt(value) : value).toString(16)}`;
1519
+ if (size) return pad(hex, { size });
1520
+ return hex;
1521
+ }
1522
+ const encoder$1 = /* @__PURE__ */ new TextEncoder();
1523
+ /**
1524
+ * Encodes a UTF-8 string into a hex string
1525
+ *
1526
+ * - Docs: https://viem.sh/docs/utilities/toHex#stringtohex
1527
+ *
1528
+ * @param value Value to encode.
1529
+ * @param opts Options.
1530
+ * @returns Hex value.
1531
+ *
1532
+ * @example
1533
+ * import { stringToHex } from 'viem'
1534
+ * const data = stringToHex('Hello World!')
1535
+ * // '0x48656c6c6f20576f726c6421'
1536
+ *
1537
+ * @example
1538
+ * import { stringToHex } from 'viem'
1539
+ * const data = stringToHex('Hello World!', { size: 32 })
1540
+ * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'
1541
+ */
1542
+ function stringToHex(value_, opts = {}) {
1543
+ return bytesToHex(encoder$1.encode(value_), opts);
1544
+ }
1545
+ //#endregion
1546
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/encoding/toBytes.js
1547
+ const encoder = /* @__PURE__ */ new TextEncoder();
1548
+ /**
1549
+ * Encodes a UTF-8 string, hex value, bigint, number or boolean to a byte array.
1550
+ *
1551
+ * - Docs: https://viem.sh/docs/utilities/toBytes
1552
+ * - Example: https://viem.sh/docs/utilities/toBytes#usage
1553
+ *
1554
+ * @param value Value to encode.
1555
+ * @param opts Options.
1556
+ * @returns Byte array value.
1557
+ *
1558
+ * @example
1559
+ * import { toBytes } from 'viem'
1560
+ * const data = toBytes('Hello world')
1561
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
1562
+ *
1563
+ * @example
1564
+ * import { toBytes } from 'viem'
1565
+ * const data = toBytes(420)
1566
+ * // Uint8Array([1, 164])
1567
+ *
1568
+ * @example
1569
+ * import { toBytes } from 'viem'
1570
+ * const data = toBytes(420, { size: 4 })
1571
+ * // Uint8Array([0, 0, 1, 164])
1572
+ */
1573
+ function toBytes(value, opts = {}) {
1574
+ if (typeof value === "number" || typeof value === "bigint") return numberToBytes(value, opts);
1575
+ if (typeof value === "boolean") return boolToBytes(value, opts);
1576
+ if (isHex(value)) return hexToBytes(value, opts);
1577
+ return stringToBytes(value, opts);
1578
+ }
1579
+ /**
1580
+ * Encodes a boolean into a byte array.
1581
+ *
1582
+ * - Docs: https://viem.sh/docs/utilities/toBytes#booltobytes
1583
+ *
1584
+ * @param value Boolean value to encode.
1585
+ * @param opts Options.
1586
+ * @returns Byte array value.
1587
+ *
1588
+ * @example
1589
+ * import { boolToBytes } from 'viem'
1590
+ * const data = boolToBytes(true)
1591
+ * // Uint8Array([1])
1592
+ *
1593
+ * @example
1594
+ * import { boolToBytes } from 'viem'
1595
+ * const data = boolToBytes(true, { size: 32 })
1596
+ * // Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
1597
+ */
1598
+ function boolToBytes(value, opts = {}) {
1599
+ const bytes = new Uint8Array(1);
1600
+ bytes[0] = Number(value);
1601
+ if (typeof opts.size === "number") {
1602
+ assertSize(bytes, { size: opts.size });
1603
+ return pad(bytes, { size: opts.size });
1604
+ }
1605
+ return bytes;
1606
+ }
1607
+ const charCodeMap = {
1608
+ zero: 48,
1609
+ nine: 57,
1610
+ A: 65,
1611
+ F: 70,
1612
+ a: 97,
1613
+ f: 102
1614
+ };
1615
+ function charCodeToBase16(char) {
1616
+ if (char >= charCodeMap.zero && char <= charCodeMap.nine) return char - charCodeMap.zero;
1617
+ if (char >= charCodeMap.A && char <= charCodeMap.F) return char - (charCodeMap.A - 10);
1618
+ if (char >= charCodeMap.a && char <= charCodeMap.f) return char - (charCodeMap.a - 10);
1619
+ }
1620
+ /**
1621
+ * Encodes a hex string into a byte array.
1622
+ *
1623
+ * - Docs: https://viem.sh/docs/utilities/toBytes#hextobytes
1624
+ *
1625
+ * @param hex Hex string to encode.
1626
+ * @param opts Options.
1627
+ * @returns Byte array value.
1628
+ *
1629
+ * @example
1630
+ * import { hexToBytes } from 'viem'
1631
+ * const data = hexToBytes('0x48656c6c6f20776f726c6421')
1632
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
1633
+ *
1634
+ * @example
1635
+ * import { hexToBytes } from 'viem'
1636
+ * const data = hexToBytes('0x48656c6c6f20776f726c6421', { size: 32 })
1637
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
1638
+ */
1639
+ function hexToBytes(hex_, opts = {}) {
1640
+ let hex = hex_;
1641
+ if (opts.size) {
1642
+ assertSize(hex, { size: opts.size });
1643
+ hex = pad(hex, {
1644
+ dir: "right",
1645
+ size: opts.size
1646
+ });
1647
+ }
1648
+ let hexString = hex.slice(2);
1649
+ if (hexString.length % 2) hexString = `0${hexString}`;
1650
+ const length = hexString.length / 2;
1651
+ const bytes = new Uint8Array(length);
1652
+ for (let index = 0, j = 0; index < length; index++) {
1653
+ const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++));
1654
+ const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++));
1655
+ if (nibbleLeft === void 0 || nibbleRight === void 0) throw new BaseError(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`);
1656
+ bytes[index] = nibbleLeft * 16 + nibbleRight;
1657
+ }
1658
+ return bytes;
1659
+ }
1660
+ /**
1661
+ * Encodes a number into a byte array.
1662
+ *
1663
+ * - Docs: https://viem.sh/docs/utilities/toBytes#numbertobytes
1664
+ *
1665
+ * @param value Number to encode.
1666
+ * @param opts Options.
1667
+ * @returns Byte array value.
1668
+ *
1669
+ * @example
1670
+ * import { numberToBytes } from 'viem'
1671
+ * const data = numberToBytes(420)
1672
+ * // Uint8Array([1, 164])
1673
+ *
1674
+ * @example
1675
+ * import { numberToBytes } from 'viem'
1676
+ * const data = numberToBytes(420, { size: 4 })
1677
+ * // Uint8Array([0, 0, 1, 164])
1678
+ */
1679
+ function numberToBytes(value, opts) {
1680
+ return hexToBytes(numberToHex(value, opts));
1681
+ }
1682
+ /**
1683
+ * Encodes a UTF-8 string into a byte array.
1684
+ *
1685
+ * - Docs: https://viem.sh/docs/utilities/toBytes#stringtobytes
1686
+ *
1687
+ * @param value String to encode.
1688
+ * @param opts Options.
1689
+ * @returns Byte array value.
1690
+ *
1691
+ * @example
1692
+ * import { stringToBytes } from 'viem'
1693
+ * const data = stringToBytes('Hello world!')
1694
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])
1695
+ *
1696
+ * @example
1697
+ * import { stringToBytes } from 'viem'
1698
+ * const data = stringToBytes('Hello world!', { size: 32 })
1699
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
1700
+ */
1701
+ function stringToBytes(value, opts = {}) {
1702
+ const bytes = encoder.encode(value);
1703
+ if (typeof opts.size === "number") {
1704
+ assertSize(bytes, { size: opts.size });
1705
+ return pad(bytes, {
1706
+ dir: "right",
1707
+ size: opts.size
1708
+ });
1709
+ }
1710
+ return bytes;
1711
+ }
1712
+ //#endregion
1713
+ //#region ../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha3.js
1714
+ /**
1715
+ * SHA3 (keccak) hash function, based on a new "Sponge function" design.
1716
+ * Different from older hashes, the internal state is bigger than output size.
1717
+ *
1718
+ * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
1719
+ * [Website](https://keccak.team/keccak.html),
1720
+ * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).
1721
+ *
1722
+ * Check out `sha3-addons` module for cSHAKE, k12, and others.
1723
+ * @module
1724
+ */
1725
+ const _0n = BigInt(0);
1726
+ const _1n = BigInt(1);
1727
+ const _2n = BigInt(2);
1728
+ const _7n = BigInt(7);
1729
+ const _256n = BigInt(256);
1730
+ const _0x71n = BigInt(113);
1731
+ const SHA3_PI = [];
1732
+ const SHA3_ROTL = [];
1733
+ const _SHA3_IOTA = [];
1734
+ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
1735
+ [x, y] = [y, (2 * x + 3 * y) % 5];
1736
+ SHA3_PI.push(2 * (5 * y + x));
1737
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
1738
+ let t = _0n;
1739
+ for (let j = 0; j < 7; j++) {
1740
+ R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
1741
+ if (R & _2n) t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j)) - _1n;
1742
+ }
1743
+ _SHA3_IOTA.push(t);
1744
+ }
1745
+ const IOTAS = split(_SHA3_IOTA, true);
1746
+ const SHA3_IOTA_H = IOTAS[0];
1747
+ const SHA3_IOTA_L = IOTAS[1];
1748
+ const rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
1749
+ const rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
1750
+ /** `keccakf1600` internal function, additionally allows to adjust round count. */
1751
+ function keccakP(s, rounds = 24) {
1752
+ const B = new Uint32Array(10);
1753
+ for (let round = 24 - rounds; round < 24; round++) {
1754
+ for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
1755
+ for (let x = 0; x < 10; x += 2) {
1756
+ const idx1 = (x + 8) % 10;
1757
+ const idx0 = (x + 2) % 10;
1758
+ const B0 = B[idx0];
1759
+ const B1 = B[idx0 + 1];
1760
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
1761
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
1762
+ for (let y = 0; y < 50; y += 10) {
1763
+ s[x + y] ^= Th;
1764
+ s[x + y + 1] ^= Tl;
1765
+ }
1766
+ }
1767
+ let curH = s[2];
1768
+ let curL = s[3];
1769
+ for (let t = 0; t < 24; t++) {
1770
+ const shift = SHA3_ROTL[t];
1771
+ const Th = rotlH(curH, curL, shift);
1772
+ const Tl = rotlL(curH, curL, shift);
1773
+ const PI = SHA3_PI[t];
1774
+ curH = s[PI];
1775
+ curL = s[PI + 1];
1776
+ s[PI] = Th;
1777
+ s[PI + 1] = Tl;
1778
+ }
1779
+ for (let y = 0; y < 50; y += 10) {
1780
+ for (let x = 0; x < 10; x++) B[x] = s[y + x];
1781
+ for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
1782
+ }
1783
+ s[0] ^= SHA3_IOTA_H[round];
1784
+ s[1] ^= SHA3_IOTA_L[round];
1785
+ }
1786
+ clean(B);
1787
+ }
1788
+ /** Keccak sponge function. */
1789
+ var Keccak = class Keccak extends Hash {
1790
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
1791
+ super();
1792
+ this.pos = 0;
1793
+ this.posOut = 0;
1794
+ this.finished = false;
1795
+ this.destroyed = false;
1796
+ this.enableXOF = false;
1797
+ this.blockLen = blockLen;
1798
+ this.suffix = suffix;
1799
+ this.outputLen = outputLen;
1800
+ this.enableXOF = enableXOF;
1801
+ this.rounds = rounds;
1802
+ anumber(outputLen);
1803
+ if (!(0 < blockLen && blockLen < 200)) throw new Error("only keccak-f1600 function is supported");
1804
+ this.state = new Uint8Array(200);
1805
+ this.state32 = u32(this.state);
1806
+ }
1807
+ clone() {
1808
+ return this._cloneInto();
1809
+ }
1810
+ keccak() {
1811
+ swap32IfBE(this.state32);
1812
+ keccakP(this.state32, this.rounds);
1813
+ swap32IfBE(this.state32);
1814
+ this.posOut = 0;
1815
+ this.pos = 0;
1816
+ }
1817
+ update(data) {
1818
+ aexists(this);
1819
+ data = toBytes$1(data);
1820
+ abytes(data);
1821
+ const { blockLen, state } = this;
1822
+ const len = data.length;
1823
+ for (let pos = 0; pos < len;) {
1824
+ const take = Math.min(blockLen - this.pos, len - pos);
1825
+ for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++];
1826
+ if (this.pos === blockLen) this.keccak();
1827
+ }
1828
+ return this;
1829
+ }
1830
+ finish() {
1831
+ if (this.finished) return;
1832
+ this.finished = true;
1833
+ const { state, suffix, pos, blockLen } = this;
1834
+ state[pos] ^= suffix;
1835
+ if ((suffix & 128) !== 0 && pos === blockLen - 1) this.keccak();
1836
+ state[blockLen - 1] ^= 128;
1837
+ this.keccak();
1838
+ }
1839
+ writeInto(out) {
1840
+ aexists(this, false);
1841
+ abytes(out);
1842
+ this.finish();
1843
+ const bufferOut = this.state;
1844
+ const { blockLen } = this;
1845
+ for (let pos = 0, len = out.length; pos < len;) {
1846
+ if (this.posOut >= blockLen) this.keccak();
1847
+ const take = Math.min(blockLen - this.posOut, len - pos);
1848
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
1849
+ this.posOut += take;
1850
+ pos += take;
1851
+ }
1852
+ return out;
1853
+ }
1854
+ xofInto(out) {
1855
+ if (!this.enableXOF) throw new Error("XOF is not possible for this instance");
1856
+ return this.writeInto(out);
1857
+ }
1858
+ xof(bytes) {
1859
+ anumber(bytes);
1860
+ return this.xofInto(new Uint8Array(bytes));
1861
+ }
1862
+ digestInto(out) {
1863
+ aoutput(out, this);
1864
+ if (this.finished) throw new Error("digest() was already called");
1865
+ this.writeInto(out);
1866
+ this.destroy();
1867
+ return out;
1868
+ }
1869
+ digest() {
1870
+ return this.digestInto(new Uint8Array(this.outputLen));
1871
+ }
1872
+ destroy() {
1873
+ this.destroyed = true;
1874
+ clean(this.state);
1875
+ }
1876
+ _cloneInto(to) {
1877
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
1878
+ to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
1879
+ to.state32.set(this.state32);
1880
+ to.pos = this.pos;
1881
+ to.posOut = this.posOut;
1882
+ to.finished = this.finished;
1883
+ to.rounds = rounds;
1884
+ to.suffix = suffix;
1885
+ to.outputLen = outputLen;
1886
+ to.enableXOF = enableXOF;
1887
+ to.destroyed = this.destroyed;
1888
+ return to;
1889
+ }
1890
+ };
1891
+ const gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
1892
+ gen(6, 144, 224 / 8);
1893
+ gen(6, 136, 256 / 8);
1894
+ gen(6, 104, 384 / 8);
1895
+ gen(6, 72, 512 / 8);
1896
+ gen(1, 144, 224 / 8);
1897
+ /** keccak-256 hash function. Different from SHA3-256. */
1898
+ const keccak_256 = gen(1, 136, 256 / 8);
1899
+ gen(1, 104, 384 / 8);
1900
+ gen(1, 72, 512 / 8);
1901
+ const genShake = (suffix, blockLen, outputLen) => createXOFer((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true));
1902
+ genShake(31, 168, 128 / 8);
1903
+ genShake(31, 136, 256 / 8);
1904
+ //#endregion
1905
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/hash/keccak256.js
1906
+ function keccak256(value, to_) {
1907
+ const to = to_ || "hex";
1908
+ const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes(value) : value);
1909
+ if (to === "bytes") return bytes;
1910
+ return toHex(bytes);
1911
+ }
1912
+ //#endregion
1913
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/lru.js
1914
+ /**
1915
+ * Map with a LRU (Least recently used) policy.
1916
+ *
1917
+ * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
1918
+ */
1919
+ var LruMap = class extends Map {
1920
+ constructor(size) {
1921
+ super();
1922
+ Object.defineProperty(this, "maxSize", {
1923
+ enumerable: true,
1924
+ configurable: true,
1925
+ writable: true,
1926
+ value: void 0
1927
+ });
1928
+ this.maxSize = size;
1929
+ }
1930
+ get(key) {
1931
+ const value = super.get(key);
1932
+ if (super.has(key)) {
1933
+ super.delete(key);
1934
+ super.set(key, value);
1935
+ }
1936
+ return value;
1937
+ }
1938
+ set(key, value) {
1939
+ if (super.has(key)) super.delete(key);
1940
+ super.set(key, value);
1941
+ if (this.maxSize && this.size > this.maxSize) {
1942
+ const firstKey = super.keys().next().value;
1943
+ if (firstKey !== void 0) super.delete(firstKey);
1944
+ }
1945
+ return this;
1946
+ }
1947
+ };
1948
+ //#endregion
1949
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/address/isAddress.js
1950
+ const addressRegex = /^0x[a-fA-F0-9]{40}$/;
1951
+ /** @internal */
1952
+ const isAddressCache = /* @__PURE__ */ new LruMap(8192);
1953
+ function isAddress(address, options) {
1954
+ const { strict = true } = options ?? {};
1955
+ const cacheKey = `${address}.${strict}`;
1956
+ if (isAddressCache.has(cacheKey)) return isAddressCache.get(cacheKey);
1957
+ const result = (() => {
1958
+ if (!addressRegex.test(address)) return false;
1959
+ if (address.toLowerCase() === address) return true;
1960
+ if (strict) return checksumAddress(address) === address;
1961
+ return true;
1962
+ })();
1963
+ isAddressCache.set(cacheKey, result);
1964
+ return result;
1965
+ }
1966
+ //#endregion
1967
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/address/getAddress.js
1968
+ const checksumAddressCache = /* @__PURE__ */ new LruMap(8192);
1969
+ function checksumAddress(address_, chainId) {
1970
+ if (checksumAddressCache.has(`${address_}.${chainId}`)) return checksumAddressCache.get(`${address_}.${chainId}`);
1971
+ const hexAddress = chainId ? `${chainId}${address_.toLowerCase()}` : address_.substring(2).toLowerCase();
1972
+ const hash = keccak256(stringToBytes(hexAddress), "bytes");
1973
+ const address = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split("");
1974
+ for (let i = 0; i < 40; i += 2) {
1975
+ if (hash[i >> 1] >> 4 >= 8 && address[i]) address[i] = address[i].toUpperCase();
1976
+ if ((hash[i >> 1] & 15) >= 8 && address[i + 1]) address[i + 1] = address[i + 1].toUpperCase();
1977
+ }
1978
+ const result = `0x${address.join("")}`;
1979
+ checksumAddressCache.set(`${address_}.${chainId}`, result);
1980
+ return result;
1981
+ }
1982
+ function getAddress(address, chainId) {
1983
+ if (!isAddress(address, { strict: false })) throw new InvalidAddressError({ address });
1984
+ return checksumAddress(address, chainId);
1985
+ }
1986
+ //#endregion
1987
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js
1988
+ /**
1989
+ * @description Converts an ECDSA public key to an address.
1990
+ *
1991
+ * @param publicKey The public key to convert.
1992
+ *
1993
+ * @returns The address.
1994
+ */
1995
+ function publicKeyToAddress(publicKey) {
1996
+ return checksumAddress(`0x${keccak256(`0x${publicKey.substring(4)}`).substring(26)}`);
1997
+ }
1998
+ //#endregion
1999
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/errors/abi.js
2000
+ var AbiEncodingArrayLengthMismatchError = class extends BaseError {
2001
+ constructor({ expectedLength, givenLength, type }) {
2002
+ super([
2003
+ `ABI encoding array length mismatch for type ${type}.`,
2004
+ `Expected length: ${expectedLength}`,
2005
+ `Given length: ${givenLength}`
2006
+ ].join("\n"), { name: "AbiEncodingArrayLengthMismatchError" });
2007
+ }
2008
+ };
2009
+ var AbiEncodingBytesSizeMismatchError = class extends BaseError {
2010
+ constructor({ expectedSize, value }) {
2011
+ super(`Size of bytes "${value}" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: "AbiEncodingBytesSizeMismatchError" });
2012
+ }
2013
+ };
2014
+ var AbiEncodingLengthMismatchError = class extends BaseError {
2015
+ constructor({ expectedLength, givenLength }) {
2016
+ super([
2017
+ "ABI encoding params/values length mismatch.",
2018
+ `Expected length (params): ${expectedLength}`,
2019
+ `Given length (values): ${givenLength}`
2020
+ ].join("\n"), { name: "AbiEncodingLengthMismatchError" });
2021
+ }
2022
+ };
2023
+ var BytesSizeMismatchError = class extends BaseError {
2024
+ constructor({ expectedSize, givenSize }) {
2025
+ super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, { name: "BytesSizeMismatchError" });
2026
+ }
2027
+ };
2028
+ var InvalidAbiEncodingTypeError = class extends BaseError {
2029
+ constructor(type, { docsPath }) {
2030
+ super([`Type "${type}" is not a valid encoding type.`, "Please provide a valid ABI type."].join("\n"), {
2031
+ docsPath,
2032
+ name: "InvalidAbiEncodingType"
2033
+ });
2034
+ }
2035
+ };
2036
+ var InvalidArrayError = class extends BaseError {
2037
+ constructor(value) {
2038
+ super([`Value "${value}" is not a valid array.`].join("\n"), { name: "InvalidArrayError" });
2039
+ }
2040
+ };
2041
+ //#endregion
2042
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/data/slice.js
2043
+ /**
2044
+ * @description Returns a section of the hex or byte array given a start/end bytes offset.
2045
+ *
2046
+ * @param value The hex or byte array to slice.
2047
+ * @param start The start offset (in bytes).
2048
+ * @param end The end offset (in bytes).
2049
+ */
2050
+ function slice(value, start, end, { strict } = {}) {
2051
+ if (isHex(value, { strict: false })) return sliceHex(value, start, end, { strict });
2052
+ return sliceBytes(value, start, end, { strict });
2053
+ }
2054
+ function assertStartOffset(value, start) {
2055
+ if (typeof start === "number" && start > 0 && start > size(value) - 1) throw new SliceOffsetOutOfBoundsError({
2056
+ offset: start,
2057
+ position: "start",
2058
+ size: size(value)
2059
+ });
2060
+ }
2061
+ function assertEndOffset(value, start, end) {
2062
+ if (typeof start === "number" && typeof end === "number" && size(value) !== end - start) throw new SliceOffsetOutOfBoundsError({
2063
+ offset: end,
2064
+ position: "end",
2065
+ size: size(value)
2066
+ });
2067
+ }
2068
+ /**
2069
+ * @description Returns a section of the byte array given a start/end bytes offset.
2070
+ *
2071
+ * @param value The byte array to slice.
2072
+ * @param start The start offset (in bytes).
2073
+ * @param end The end offset (in bytes).
2074
+ */
2075
+ function sliceBytes(value_, start, end, { strict } = {}) {
2076
+ assertStartOffset(value_, start);
2077
+ const value = value_.slice(start, end);
2078
+ if (strict) assertEndOffset(value, start, end);
2079
+ return value;
2080
+ }
2081
+ /**
2082
+ * @description Returns a section of the hex value given a start/end bytes offset.
2083
+ *
2084
+ * @param value The hex value to slice.
2085
+ * @param start The start offset (in bytes).
2086
+ * @param end The end offset (in bytes).
2087
+ */
2088
+ function sliceHex(value_, start, end, { strict } = {}) {
2089
+ assertStartOffset(value_, start);
2090
+ const value = `0x${value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`;
2091
+ if (strict) assertEndOffset(value, start, end);
2092
+ return value;
2093
+ }
2094
+ //#endregion
2095
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/data/concat.js
2096
+ function concat(values) {
2097
+ if (typeof values[0] === "string") return concatHex(values);
2098
+ return concatBytes(values);
2099
+ }
2100
+ function concatBytes(values) {
2101
+ let length = 0;
2102
+ for (const arr of values) length += arr.length;
2103
+ const result = new Uint8Array(length);
2104
+ let offset = 0;
2105
+ for (const arr of values) {
2106
+ result.set(arr, offset);
2107
+ offset += arr.length;
2108
+ }
2109
+ return result;
2110
+ }
2111
+ function concatHex(values) {
2112
+ return `0x${values.reduce((acc, x) => acc + x.replace("0x", ""), "")}`;
2113
+ }
2114
+ //#endregion
2115
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/regex.js
2116
+ const bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;
2117
+ const integerRegex = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;
2118
+ //#endregion
2119
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/abi/encodeAbiParameters.js
2120
+ /**
2121
+ * @description Encodes a list of primitive values into an ABI-encoded hex value.
2122
+ *
2123
+ * - Docs: https://viem.sh/docs/abi/encodeAbiParameters#encodeabiparameters
2124
+ *
2125
+ * Generates ABI encoded data using the [ABI specification](https://docs.soliditylang.org/en/latest/abi-spec), given a set of ABI parameters (inputs/outputs) and their corresponding values.
2126
+ *
2127
+ * @param params - a set of ABI Parameters (params), that can be in the shape of the inputs or outputs attribute of an ABI Item.
2128
+ * @param values - a set of values (values) that correspond to the given params.
2129
+ * @example
2130
+ * ```typescript
2131
+ * import { encodeAbiParameters } from 'viem'
2132
+ *
2133
+ * const encodedData = encodeAbiParameters(
2134
+ * [
2135
+ * { name: 'x', type: 'string' },
2136
+ * { name: 'y', type: 'uint' },
2137
+ * { name: 'z', type: 'bool' }
2138
+ * ],
2139
+ * ['wagmi', 420n, true]
2140
+ * )
2141
+ * ```
2142
+ *
2143
+ * You can also pass in Human Readable parameters with the parseAbiParameters utility.
2144
+ *
2145
+ * @example
2146
+ * ```typescript
2147
+ * import { encodeAbiParameters, parseAbiParameters } from 'viem'
2148
+ *
2149
+ * const encodedData = encodeAbiParameters(
2150
+ * parseAbiParameters('string x, uint y, bool z'),
2151
+ * ['wagmi', 420n, true]
2152
+ * )
2153
+ * ```
2154
+ */
2155
+ function encodeAbiParameters(params, values) {
2156
+ if (params.length !== values.length) throw new AbiEncodingLengthMismatchError({
2157
+ expectedLength: params.length,
2158
+ givenLength: values.length
2159
+ });
2160
+ return encodeParams(prepareParams({
2161
+ params,
2162
+ values
2163
+ }));
2164
+ }
2165
+ function prepareParams({ params, values }) {
2166
+ const preparedParams = [];
2167
+ for (let i = 0; i < params.length; i++) preparedParams.push(prepareParam({
2168
+ param: params[i],
2169
+ value: values[i]
2170
+ }));
2171
+ return preparedParams;
2172
+ }
2173
+ function prepareParam({ param, value }) {
2174
+ const arrayComponents = getArrayComponents(param.type);
2175
+ if (arrayComponents) {
2176
+ const [length, type] = arrayComponents;
2177
+ return encodeArray(value, {
2178
+ length,
2179
+ param: {
2180
+ ...param,
2181
+ type
2182
+ }
2183
+ });
2184
+ }
2185
+ if (param.type === "tuple") return encodeTuple(value, { param });
2186
+ if (param.type === "address") return encodeAddress(value);
2187
+ if (param.type === "bool") return encodeBool(value);
2188
+ if (param.type.startsWith("uint") || param.type.startsWith("int")) {
2189
+ const signed = param.type.startsWith("int");
2190
+ const [, , size = "256"] = integerRegex.exec(param.type) ?? [];
2191
+ return encodeNumber(value, {
2192
+ signed,
2193
+ size: Number(size)
2194
+ });
2195
+ }
2196
+ if (param.type.startsWith("bytes")) return encodeBytes(value, { param });
2197
+ if (param.type === "string") return encodeString(value);
2198
+ throw new InvalidAbiEncodingTypeError(param.type, { docsPath: "/docs/contract/encodeAbiParameters" });
2199
+ }
2200
+ function encodeParams(preparedParams) {
2201
+ let staticSize = 0;
2202
+ for (let i = 0; i < preparedParams.length; i++) {
2203
+ const { dynamic, encoded } = preparedParams[i];
2204
+ if (dynamic) staticSize += 32;
2205
+ else staticSize += size(encoded);
2206
+ }
2207
+ const staticParams = [];
2208
+ const dynamicParams = [];
2209
+ let dynamicSize = 0;
2210
+ for (let i = 0; i < preparedParams.length; i++) {
2211
+ const { dynamic, encoded } = preparedParams[i];
2212
+ if (dynamic) {
2213
+ staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 }));
2214
+ dynamicParams.push(encoded);
2215
+ dynamicSize += size(encoded);
2216
+ } else staticParams.push(encoded);
2217
+ }
2218
+ return concatHex([...staticParams, ...dynamicParams]);
2219
+ }
2220
+ function encodeAddress(value) {
2221
+ if (!isAddress(value)) throw new InvalidAddressError({ address: value });
2222
+ return {
2223
+ dynamic: false,
2224
+ encoded: padHex(value.toLowerCase())
2225
+ };
2226
+ }
2227
+ function encodeArray(value, { length, param }) {
2228
+ const dynamic = length === null;
2229
+ if (!Array.isArray(value)) throw new InvalidArrayError(value);
2230
+ if (!dynamic && value.length !== length) throw new AbiEncodingArrayLengthMismatchError({
2231
+ expectedLength: length,
2232
+ givenLength: value.length,
2233
+ type: `${param.type}[${length}]`
2234
+ });
2235
+ let dynamicChild = value.length === 0 && isDynamicType(param);
2236
+ const preparedParams = [];
2237
+ for (let i = 0; i < value.length; i++) {
2238
+ const preparedParam = prepareParam({
2239
+ param,
2240
+ value: value[i]
2241
+ });
2242
+ if (preparedParam.dynamic) dynamicChild = true;
2243
+ preparedParams.push(preparedParam);
2244
+ }
2245
+ if (dynamic || dynamicChild) {
2246
+ const data = encodeParams(preparedParams);
2247
+ if (dynamic) return {
2248
+ dynamic: true,
2249
+ encoded: concatHex([numberToHex(preparedParams.length, { size: 32 }), data])
2250
+ };
2251
+ if (dynamicChild) return {
2252
+ dynamic: true,
2253
+ encoded: data
2254
+ };
2255
+ }
2256
+ return {
2257
+ dynamic: false,
2258
+ encoded: concatHex(preparedParams.map(({ encoded }) => encoded))
2259
+ };
2260
+ }
2261
+ function encodeBytes(value, { param }) {
2262
+ const [, paramSize] = param.type.split("bytes");
2263
+ const bytesSize = size(value);
2264
+ if (!paramSize) {
2265
+ let value_ = value;
2266
+ if (bytesSize % 32 !== 0) value_ = padHex(value_, {
2267
+ dir: "right",
2268
+ size: Math.ceil((value.length - 2) / 2 / 32) * 32
2269
+ });
2270
+ return {
2271
+ dynamic: true,
2272
+ encoded: concatHex([padHex(numberToHex(bytesSize, { size: 32 })), value_])
2273
+ };
2274
+ }
2275
+ if (bytesSize !== Number.parseInt(paramSize, 10)) throw new AbiEncodingBytesSizeMismatchError({
2276
+ expectedSize: Number.parseInt(paramSize, 10),
2277
+ value
2278
+ });
2279
+ return {
2280
+ dynamic: false,
2281
+ encoded: padHex(value, { dir: "right" })
2282
+ };
2283
+ }
2284
+ function encodeBool(value) {
2285
+ if (typeof value !== "boolean") throw new BaseError(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`);
2286
+ return {
2287
+ dynamic: false,
2288
+ encoded: padHex(boolToHex(value))
2289
+ };
2290
+ }
2291
+ function encodeNumber(value, { signed, size = 256 }) {
2292
+ if (typeof size === "number") {
2293
+ const max = 2n ** (BigInt(size) - (signed ? 1n : 0n)) - 1n;
2294
+ const min = signed ? -max - 1n : 0n;
2295
+ if (value > max || value < min) throw new IntegerOutOfRangeError({
2296
+ max: max.toString(),
2297
+ min: min.toString(),
2298
+ signed,
2299
+ size: size / 8,
2300
+ value: value.toString()
2301
+ });
2302
+ }
2303
+ return {
2304
+ dynamic: false,
2305
+ encoded: numberToHex(value, {
2306
+ size: 32,
2307
+ signed
2308
+ })
2309
+ };
2310
+ }
2311
+ function encodeString(value) {
2312
+ const hexValue = stringToHex(value);
2313
+ const partsLength = Math.ceil(size(hexValue) / 32);
2314
+ const parts = [];
2315
+ for (let i = 0; i < partsLength; i++) parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), { dir: "right" }));
2316
+ return {
2317
+ dynamic: true,
2318
+ encoded: concatHex([padHex(numberToHex(size(hexValue), { size: 32 })), ...parts])
2319
+ };
2320
+ }
2321
+ function encodeTuple(value, { param }) {
2322
+ let dynamic = false;
2323
+ const preparedParams = [];
2324
+ for (let i = 0; i < param.components.length; i++) {
2325
+ const param_ = param.components[i];
2326
+ const preparedParam = prepareParam({
2327
+ param: param_,
2328
+ value: value[Array.isArray(value) ? i : param_.name]
2329
+ });
2330
+ preparedParams.push(preparedParam);
2331
+ if (preparedParam.dynamic) dynamic = true;
2332
+ }
2333
+ return {
2334
+ dynamic,
2335
+ encoded: dynamic ? encodeParams(preparedParams) : concatHex(preparedParams.map(({ encoded }) => encoded))
2336
+ };
2337
+ }
2338
+ function getArrayComponents(type) {
2339
+ const matches = type.match(/^(.*)\[(\d+)?\]$/);
2340
+ return matches ? [matches[2] ? Number(matches[2]) : null, matches[1]] : void 0;
2341
+ }
2342
+ function isDynamicType(param) {
2343
+ const { type } = param;
2344
+ if (type === "string") return true;
2345
+ if (type === "bytes") return true;
2346
+ if (type.endsWith("[]")) return true;
2347
+ if (type === "tuple") return param.components.some(isDynamicType);
2348
+ const arrayComponents = getArrayComponents(type);
2349
+ if (arrayComponents) return isDynamicType({
2350
+ ...param,
2351
+ type: arrayComponents[1]
2352
+ });
2353
+ return false;
2354
+ }
2355
+ //#endregion
2356
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/stringify.js
2357
+ const stringify = (value, replacer, space) => JSON.stringify(value, (key, value_) => {
2358
+ const value = typeof value_ === "bigint" ? value_.toString() : value_;
2359
+ return typeof replacer === "function" ? replacer(key, value) : value;
2360
+ }, space);
2361
+ //#endregion
2362
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/address/isAddressEqual.js
2363
+ function isAddressEqual(a, b) {
2364
+ if (!isAddress(a, { strict: false })) throw new InvalidAddressError({ address: a });
2365
+ if (!isAddress(b, { strict: false })) throw new InvalidAddressError({ address: b });
2366
+ return a.toLowerCase() === b.toLowerCase();
2367
+ }
2368
+ //#endregion
2369
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/signature/recoverPublicKey.js
2370
+ async function recoverPublicKey({ hash, signature }) {
2371
+ const hashHex = isHex(hash) ? hash : toHex(hash);
2372
+ const { secp256k1 } = await import("./secp256k1-CyKOxB5J.js");
2373
+ return `0x${(() => {
2374
+ if (typeof signature === "object" && "r" in signature && "s" in signature) {
2375
+ const { r, s, v, yParity } = signature;
2376
+ const recoveryBit = toRecoveryBit(Number(yParity ?? v));
2377
+ return new secp256k1.Signature(hexToBigInt(r), hexToBigInt(s)).addRecoveryBit(recoveryBit);
2378
+ }
2379
+ const signatureHex = isHex(signature) ? signature : toHex(signature);
2380
+ if (size(signatureHex) !== 65) throw new Error("invalid signature length");
2381
+ const recoveryBit = toRecoveryBit(hexToNumber(`0x${signatureHex.slice(130)}`));
2382
+ return secp256k1.Signature.fromCompact(signatureHex.substring(2, 130)).addRecoveryBit(recoveryBit);
2383
+ })().recoverPublicKey(hashHex.substring(2)).toHex(false)}`;
2384
+ }
2385
+ function toRecoveryBit(yParityOrV) {
2386
+ if (yParityOrV === 0 || yParityOrV === 1) return yParityOrV;
2387
+ if (yParityOrV === 27) return 0;
2388
+ if (yParityOrV === 28) return 1;
2389
+ throw new Error("Invalid yParityOrV value");
2390
+ }
2391
+ //#endregion
2392
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/signature/recoverAddress.js
2393
+ async function recoverAddress({ hash, signature }) {
2394
+ return publicKeyToAddress(await recoverPublicKey({
2395
+ hash,
2396
+ signature
2397
+ }));
2398
+ }
2399
+ //#endregion
2400
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/errors/typedData.js
2401
+ var InvalidDomainError = class extends BaseError {
2402
+ constructor({ domain }) {
2403
+ super(`Invalid domain "${stringify(domain)}".`, { metaMessages: ["Must be a valid EIP-712 domain."] });
2404
+ }
2405
+ };
2406
+ var InvalidPrimaryTypeError = class extends BaseError {
2407
+ constructor({ primaryType, types }) {
2408
+ super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, {
2409
+ docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror",
2410
+ metaMessages: ["Check that the primary type is a key in `types`."]
2411
+ });
2412
+ }
2413
+ };
2414
+ var InvalidStructTypeError = class extends BaseError {
2415
+ constructor({ type }) {
2416
+ super(`Struct type "${type}" is invalid.`, {
2417
+ metaMessages: ["Struct type must not be a Solidity type."],
2418
+ name: "InvalidStructTypeError"
2419
+ });
2420
+ }
2421
+ };
2422
+ //#endregion
2423
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/typedData.js
2424
+ function validateTypedData(parameters) {
2425
+ const { domain, message, primaryType, types } = parameters;
2426
+ const validateData = (struct, data) => {
2427
+ for (const param of struct) {
2428
+ const { name, type } = param;
2429
+ const value = data[name];
2430
+ const integerMatch = type.match(integerRegex);
2431
+ if (integerMatch && (typeof value === "number" || typeof value === "bigint")) {
2432
+ const [_type, base, size_] = integerMatch;
2433
+ numberToHex(value, {
2434
+ signed: base === "int",
2435
+ size: Number.parseInt(size_, 10) / 8
2436
+ });
2437
+ }
2438
+ if (type === "address" && typeof value === "string" && !isAddress(value)) throw new InvalidAddressError({ address: value });
2439
+ const bytesMatch = type.match(bytesRegex);
2440
+ if (bytesMatch) {
2441
+ const [_type, size_] = bytesMatch;
2442
+ if (size_ && size(value) !== Number.parseInt(size_, 10)) throw new BytesSizeMismatchError({
2443
+ expectedSize: Number.parseInt(size_, 10),
2444
+ givenSize: size(value)
2445
+ });
2446
+ }
2447
+ const struct = types[type];
2448
+ if (struct) {
2449
+ validateReference(type);
2450
+ validateData(struct, value);
2451
+ }
2452
+ }
2453
+ };
2454
+ if (types.EIP712Domain && domain) {
2455
+ if (typeof domain !== "object") throw new InvalidDomainError({ domain });
2456
+ validateData(types.EIP712Domain, domain);
2457
+ }
2458
+ if (primaryType !== "EIP712Domain") if (types[primaryType]) validateData(types[primaryType], message);
2459
+ else throw new InvalidPrimaryTypeError({
2460
+ primaryType,
2461
+ types
2462
+ });
2463
+ }
2464
+ function getTypesForEIP712Domain({ domain }) {
2465
+ return [
2466
+ typeof domain?.name === "string" && {
2467
+ name: "name",
2468
+ type: "string"
2469
+ },
2470
+ domain?.version && {
2471
+ name: "version",
2472
+ type: "string"
2473
+ },
2474
+ (typeof domain?.chainId === "number" || typeof domain?.chainId === "bigint") && {
2475
+ name: "chainId",
2476
+ type: "uint256"
2477
+ },
2478
+ domain?.verifyingContract && {
2479
+ name: "verifyingContract",
2480
+ type: "address"
2481
+ },
2482
+ domain?.salt && {
2483
+ name: "salt",
2484
+ type: "bytes32"
2485
+ }
2486
+ ].filter(Boolean);
2487
+ }
2488
+ /** @internal */
2489
+ function validateReference(type) {
2490
+ if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int")) throw new InvalidStructTypeError({ type });
2491
+ }
2492
+ //#endregion
2493
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/signature/hashTypedData.js
2494
+ function hashTypedData(parameters) {
2495
+ const { domain = {}, message, primaryType } = parameters;
2496
+ const types = {
2497
+ EIP712Domain: getTypesForEIP712Domain({ domain }),
2498
+ ...parameters.types
2499
+ };
2500
+ validateTypedData({
2501
+ domain,
2502
+ message,
2503
+ primaryType,
2504
+ types
2505
+ });
2506
+ const parts = ["0x1901"];
2507
+ if (domain) parts.push(hashDomain({
2508
+ domain,
2509
+ types
2510
+ }));
2511
+ if (primaryType !== "EIP712Domain") parts.push(hashStruct({
2512
+ data: message,
2513
+ primaryType,
2514
+ types
2515
+ }));
2516
+ return keccak256(concat(parts));
2517
+ }
2518
+ function hashDomain({ domain, types }) {
2519
+ return hashStruct({
2520
+ data: domain,
2521
+ primaryType: "EIP712Domain",
2522
+ types
2523
+ });
2524
+ }
2525
+ function hashStruct({ data, primaryType, types }) {
2526
+ return keccak256(encodeData({
2527
+ data,
2528
+ primaryType,
2529
+ types
2530
+ }));
2531
+ }
2532
+ function encodeData({ data, primaryType, types }) {
2533
+ const encodedTypes = [{ type: "bytes32" }];
2534
+ const encodedValues = [hashType({
2535
+ primaryType,
2536
+ types
2537
+ })];
2538
+ for (const field of types[primaryType]) {
2539
+ const [type, value] = encodeField({
2540
+ types,
2541
+ name: field.name,
2542
+ type: field.type,
2543
+ value: data[field.name]
2544
+ });
2545
+ encodedTypes.push(type);
2546
+ encodedValues.push(value);
2547
+ }
2548
+ return encodeAbiParameters(encodedTypes, encodedValues);
2549
+ }
2550
+ function hashType({ primaryType, types }) {
2551
+ return keccak256(toHex(encodeType({
2552
+ primaryType,
2553
+ types
2554
+ })));
2555
+ }
2556
+ function encodeType({ primaryType, types }) {
2557
+ let result = "";
2558
+ const unsortedDeps = findTypeDependencies({
2559
+ primaryType,
2560
+ types
2561
+ });
2562
+ unsortedDeps.delete(primaryType);
2563
+ const deps = [primaryType, ...Array.from(unsortedDeps).sort()];
2564
+ for (const type of deps) result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`;
2565
+ return result;
2566
+ }
2567
+ function findTypeDependencies({ primaryType: primaryType_, types }, results = /* @__PURE__ */ new Set()) {
2568
+ const primaryType = primaryType_.match(/^\w*/u)?.[0];
2569
+ if (results.has(primaryType) || types[primaryType] === void 0) return results;
2570
+ results.add(primaryType);
2571
+ for (const field of types[primaryType]) findTypeDependencies({
2572
+ primaryType: field.type,
2573
+ types
2574
+ }, results);
2575
+ return results;
2576
+ }
2577
+ function encodeField({ types, name, type, value }) {
2578
+ if (types[type] !== void 0) return [{ type: "bytes32" }, keccak256(encodeData({
2579
+ data: value,
2580
+ primaryType: type,
2581
+ types
2582
+ }))];
2583
+ if (type === "bytes") return [{ type: "bytes32" }, keccak256(value)];
2584
+ if (type === "string") return [{ type: "bytes32" }, keccak256(toHex(value))];
2585
+ if (type.lastIndexOf("]") === type.length - 1) {
2586
+ const parsedType = type.slice(0, type.lastIndexOf("["));
2587
+ const typeValuePairs = value.map((item) => encodeField({
2588
+ name,
2589
+ type: parsedType,
2590
+ types,
2591
+ value: item
2592
+ }));
2593
+ return [{ type: "bytes32" }, keccak256(encodeAbiParameters(typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v)))];
2594
+ }
2595
+ return [{ type }, value];
2596
+ }
2597
+ //#endregion
2598
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/signature/recoverTypedDataAddress.js
2599
+ async function recoverTypedDataAddress(parameters) {
2600
+ const { domain, message, primaryType, signature, types } = parameters;
2601
+ return recoverAddress({
2602
+ hash: hashTypedData({
2603
+ domain,
2604
+ message,
2605
+ primaryType,
2606
+ types
2607
+ }),
2608
+ signature
2609
+ });
2610
+ }
2611
+ //#endregion
2612
+ //#region ../../../node_modules/.pnpm/viem@2.55.4_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.5/node_modules/viem/_esm/utils/signature/verifyTypedData.js
2613
+ /**
2614
+ * Verify that typed data was signed by the provided address.
2615
+ *
2616
+ * Note: Only supports Externally Owned Accounts. Does not support Contract Accounts.
2617
+ * It is highly recommended to use `publicClient.verifyTypedData` instead to ensure
2618
+ * wallet interoperability.
2619
+ *
2620
+ * - Docs {@link https://viem.sh/docs/utilities/verifyTypedData}
2621
+ *
2622
+ * @param parameters - {@link VerifyTypedDataParameters}
2623
+ * @returns Whether or not the signature is valid. {@link VerifyTypedDataReturnType}
2624
+ */
2625
+ async function verifyTypedData(parameters) {
2626
+ const { address, domain, message, primaryType, signature, types } = parameters;
2627
+ return isAddressEqual(getAddress(address), await recoverTypedDataAddress({
2628
+ domain,
2629
+ message,
2630
+ primaryType,
2631
+ signature,
2632
+ types
2633
+ }));
2634
+ }
2635
+ //#endregion
2636
+ //#region src/tangle/rfq.ts
2637
+ /**
2638
+ * RFQ quote primitives for tnt-core's `JobsRFQ` marketplace flow.
2639
+ *
2640
+ * These helpers fetch, hash, and validate operator quotes. Callers remain
2641
+ * responsible for preparing and submitting on-chain transactions.
2642
+ *
2643
+ * The EIP-712 hashing here is pinned byte-for-byte against the Rust SDK
2644
+ * (blueprint `tangle-extra::job_quote`, digest fixture in
2645
+ * `tangle-rfq.test.ts`) and against `SignatureLib` in tnt-core. Never change
2646
+ * the typed-data shape without regenerating all three.
2647
+ */
2648
+ const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
2649
+ var QuoteError = class extends Error {
2650
+ constructor(message, code) {
2651
+ super(message);
2652
+ this.code = code;
2653
+ this.name = "QuoteError";
2654
+ }
2655
+ };
2656
+ const JOB_QUOTE_TYPE = { JobQuoteDetails: [
2657
+ {
2658
+ name: "requester",
2659
+ type: "address"
2660
+ },
2661
+ {
2662
+ name: "serviceId",
2663
+ type: "uint64"
2664
+ },
2665
+ {
2666
+ name: "jobIndex",
2667
+ type: "uint8"
2668
+ },
2669
+ {
2670
+ name: "price",
2671
+ type: "uint256"
2672
+ },
2673
+ {
2674
+ name: "timestamp",
2675
+ type: "uint64"
2676
+ },
2677
+ {
2678
+ name: "expiry",
2679
+ type: "uint64"
2680
+ },
2681
+ {
2682
+ name: "confidentiality",
2683
+ type: "uint8"
2684
+ },
2685
+ {
2686
+ name: "inputsHash",
2687
+ type: "bytes32"
2688
+ }
2689
+ ] };
2690
+ /**
2691
+ * The EIP-712 digest of a quote — matches
2692
+ * `job_quote_digest_eip712` (Rust SDK) and `computeJobQuoteDigest` (tnt-core).
2693
+ */
2694
+ function jobQuoteDigest(details, domain) {
2695
+ assertQuoteDomain(domain);
2696
+ return hashTypedData({
2697
+ domain: {
2698
+ name: "TangleQuote",
2699
+ version: "1",
2700
+ chainId: domain.chainId,
2701
+ verifyingContract: domain.verifyingContract
2702
+ },
2703
+ types: JOB_QUOTE_TYPE,
2704
+ primaryType: "JobQuoteDetails",
2705
+ message: {
2706
+ requester: details.requester,
2707
+ serviceId: details.serviceId,
2708
+ jobIndex: details.jobIndex,
2709
+ price: details.price,
2710
+ timestamp: details.timestamp,
2711
+ expiry: details.expiry,
2712
+ confidentiality: details.confidentiality,
2713
+ inputsHash: details.inputsHash
2714
+ }
2715
+ });
2716
+ }
2717
+ function isRecord(value) {
2718
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2719
+ }
2720
+ function readUint(value, field, bits) {
2721
+ if (!(typeof value === "bigint" || typeof value === "number" && Number.isSafeInteger(value) || typeof value === "string" && /^[0-9]+$/.test(value))) throw new QuoteError(`Quote field ${field} must be an exact unsigned integer`, "QUOTE_REJECTED");
2722
+ const parsed = BigInt(value);
2723
+ if (parsed < 0n || parsed >= 1n << BigInt(bits)) throw new QuoteError(`Quote field ${field} is outside uint${bits}`, "QUOTE_REJECTED");
2724
+ return parsed;
2725
+ }
2726
+ function readAddress(value, field) {
2727
+ if (typeof value !== "string" || !isAddress(value, { strict: false }) || value.toLowerCase() === ZERO_ADDRESS) throw new QuoteError(`Quote field ${field} must be an address`, "QUOTE_REJECTED");
2728
+ return value;
2729
+ }
2730
+ function readConfidentiality(value) {
2731
+ const policy = readUint(value, "confidentiality", 8);
2732
+ if (policy > 3n) throw new QuoteError("Quote field confidentiality is not a supported policy", "QUOTE_REJECTED");
2733
+ return Number(policy);
2734
+ }
2735
+ function assertQuoteDomain(domain) {
2736
+ if (!isRecord(domain) || !Number.isSafeInteger(domain.chainId) || domain.chainId < 0 || typeof domain.verifyingContract !== "string" || !isAddress(domain.verifyingContract, { strict: false }) || domain.verifyingContract.toLowerCase() === ZERO_ADDRESS) throw new QuoteError("Quote domain requires an exact chain id and contract address", "QUOTE_MISMATCH");
2737
+ }
2738
+ /** Parse the operator's `/api/quote` JSON without fabricating missing values. */
2739
+ function parseQuoteResponse(raw) {
2740
+ if (!isRecord(raw) || !isRecord(raw.quote)) throw new QuoteError("Response missing `quote` object", "QUOTE_REJECTED");
2741
+ const quote = raw.quote;
2742
+ if (typeof quote.inputsHash !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(quote.inputsHash)) throw new QuoteError("Quote field inputsHash must be bytes32", "QUOTE_REJECTED");
2743
+ if (typeof raw.signature !== "string" || !isHex(raw.signature) || !/^0x[0-9a-fA-F]{130}$/.test(raw.signature) || !["1b", "1c"].includes(raw.signature.slice(-2).toLowerCase())) throw new QuoteError("Quote signature must be 65-byte r, s, v hex with a valid recovery byte", "QUOTE_SIGNATURE_INVALID");
2744
+ const details = {
2745
+ requester: readAddress(quote.requester, "requester"),
2746
+ serviceId: readUint(quote.serviceId, "serviceId", 64),
2747
+ jobIndex: Number(readUint(quote.jobIndex, "jobIndex", 8)),
2748
+ price: readUint(quote.price, "price", 256),
2749
+ timestamp: readUint(quote.timestamp, "timestamp", 64),
2750
+ expiry: readUint(quote.expiry, "expiry", 64),
2751
+ confidentiality: readConfidentiality(quote.confidentiality),
2752
+ inputsHash: quote.inputsHash
2753
+ };
2754
+ let capacity;
2755
+ if (raw.capacity !== void 0 && raw.capacity !== null) {
2756
+ if (!isRecord(raw.capacity)) throw new QuoteError("Quote capacity must be an object", "QUOTE_REJECTED");
2757
+ capacity = {
2758
+ active: Number(readUint(raw.capacity.active, "capacity.active", 53)),
2759
+ max: Number(readUint(raw.capacity.max, "capacity.max", 53))
2760
+ };
2761
+ }
2762
+ return {
2763
+ details,
2764
+ signature: raw.signature,
2765
+ operator: readAddress(raw.operator, "operator"),
2766
+ capacity
2767
+ };
2768
+ }
2769
+ /** keccak256 of the exact ABI-encoded job inputs — what quotes bind to. */
2770
+ function inputsHashOf(encodedInputs) {
2771
+ return keccak256(encodedInputs);
2772
+ }
2773
+ /**
2774
+ * Validate a quote before paying for it: fresh (not expired), addressed to
2775
+ * the buyer, for the exact inputs about to be submitted, on the expected
2776
+ * service/job, and signed by the operator it names.
2777
+ *
2778
+ * Signature verification uses viem's offline EOA recovery and compares the
2779
+ * signer against the same digest the chain checks.
2780
+ */
2781
+ async function validateQuote(args) {
2782
+ const { domain, buyer, serviceId, jobIndex, inputsHash } = args;
2783
+ assertQuoteDomain(domain);
2784
+ const quote = parseQuoteResponse({
2785
+ quote: args.quote.details,
2786
+ signature: args.quote.signature,
2787
+ operator: args.quote.operator,
2788
+ capacity: args.quote.capacity
2789
+ });
2790
+ const now = args.now ?? Math.floor(Date.now() / 1e3);
2791
+ if (!Number.isSafeInteger(now) || now < 0) throw new QuoteError("Quote validation requires an exact current timestamp", "QUOTE_MISMATCH");
2792
+ if (BigInt(now) > quote.details.expiry) throw new QuoteError(`Quote expired at ${quote.details.expiry} (now ${now})`, "QUOTE_EXPIRED");
2793
+ if (quote.details.requester.toLowerCase() !== buyer.toLowerCase()) throw new QuoteError(`Quote is addressed to ${quote.details.requester}, not ${buyer}`, "QUOTE_MISMATCH");
2794
+ if (quote.details.serviceId !== serviceId || quote.details.jobIndex !== jobIndex) throw new QuoteError(`Quote is for service ${quote.details.serviceId}/job ${quote.details.jobIndex}, not ${serviceId}/${jobIndex}`, "QUOTE_MISMATCH");
2795
+ if (quote.details.inputsHash.toLowerCase() !== inputsHash.toLowerCase()) throw new QuoteError("Quote inputs hash does not match the inputs being submitted", "QUOTE_MISMATCH");
2796
+ let valid;
2797
+ try {
2798
+ valid = await verifyTypedData({
2799
+ address: quote.operator,
2800
+ domain: {
2801
+ name: "TangleQuote",
2802
+ version: "1",
2803
+ chainId: domain.chainId,
2804
+ verifyingContract: domain.verifyingContract
2805
+ },
2806
+ types: JOB_QUOTE_TYPE,
2807
+ primaryType: "JobQuoteDetails",
2808
+ message: {
2809
+ requester: quote.details.requester,
2810
+ serviceId: quote.details.serviceId,
2811
+ jobIndex: quote.details.jobIndex,
2812
+ price: quote.details.price,
2813
+ timestamp: quote.details.timestamp,
2814
+ expiry: quote.details.expiry,
2815
+ confidentiality: quote.details.confidentiality,
2816
+ inputsHash: quote.details.inputsHash
2817
+ },
2818
+ signature: quote.signature
2819
+ });
2820
+ } catch {
2821
+ throw new QuoteError("Quote signature could not be verified", "QUOTE_SIGNATURE_INVALID");
2822
+ }
2823
+ if (!valid) throw new QuoteError(`Signature does not recover to operator ${quote.operator}`, "QUOTE_SIGNATURE_INVALID");
2824
+ }
2825
+ /** Query one operator for a quote over HTTP. */
2826
+ async function fetchQuote(operatorApiUrl, params) {
2827
+ const url = new URL("/api/quote", operatorApiUrl);
2828
+ url.searchParams.set("requester", params.requester);
2829
+ url.searchParams.set("job_index", String(params.jobIndex));
2830
+ if (params.inputs) url.searchParams.set("inputs", params.inputs);
2831
+ if (params.inputsHash) url.searchParams.set("inputs_hash", params.inputsHash);
2832
+ if (params.confidentiality !== void 0) url.searchParams.set("confidentiality", String(params.confidentiality));
2833
+ const response = await (params.fetchImpl ?? fetch)(url, { method: "GET" });
2834
+ if (!response.ok) {
2835
+ const body = await response.text().catch(() => "");
2836
+ throw new QuoteError(`Operator refused the quote request (HTTP ${response.status}): ${body.slice(0, 200)}`, "QUOTE_REJECTED");
2837
+ }
2838
+ let raw;
2839
+ try {
2840
+ raw = await response.json();
2841
+ } catch {
2842
+ throw new QuoteError("Operator returned invalid quote JSON", "QUOTE_REJECTED");
2843
+ }
2844
+ if (!isRecord(raw)) throw new QuoteError("Operator returned invalid quote JSON", "QUOTE_REJECTED");
2845
+ return parseQuoteResponse(raw);
2846
+ }
2847
+ //#endregion
2848
+ export { SandboxCreateParamTypes as _, parseQuoteResponse as a, OperatorSession as c, JOB_SANDBOX_DELETE as d, TANGLE_CHAIN_ID as f, JsonResponseParamTypes as g, ITangleJobsAbi as h, jobQuoteDigest as i, OperatorSessionError as l, AgentSandboxBlueprintAbi as m, fetchQuote as n, validateQuote as o, TANGLE_JOBS_CONTRACT as p, inputsHashOf as r, TangleSandboxClient as s, QuoteError as t, JOB_SANDBOX_CREATE as u, SandboxCreateResponseParamTypes as v, SandboxIdParamTypes as y };