@steerprotocol/app-loader 3.0.6 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +86 -0
  2. package/lib/browser.d.ts +5 -2
  3. package/lib/browser.mjs +247 -72
  4. package/lib/browser.mjs.map +1 -1
  5. package/lib/index.cjs +3687 -107
  6. package/lib/index.cjs.map +1 -1
  7. package/lib/index.d.ts +5 -2
  8. package/lib/index.mjs +3687 -107
  9. package/lib/index.mjs.map +1 -1
  10. package/lib/internal/asyncHostCalls.d.ts +37 -0
  11. package/lib/internal/instantiate.d.ts +3 -4
  12. package/lib/internal/loadOptions.d.ts +1 -0
  13. package/lib/internal/panoptic/deps.d.ts +24 -0
  14. package/lib/internal/panoptic/dynamicJobs/fragments.d.ts +10 -0
  15. package/lib/internal/panoptic/dynamicJobs/renderExecuteJob.d.ts +8 -0
  16. package/lib/internal/panoptic/fragments/collateral.d.ts +5 -0
  17. package/lib/internal/panoptic/fragments/erc20.d.ts +3 -0
  18. package/lib/internal/panoptic/fragments/hypovault.d.ts +12 -0
  19. package/lib/internal/panoptic/fragments/merkle.d.ts +22 -0
  20. package/lib/internal/panoptic/fragments/panoptic.d.ts +17 -0
  21. package/lib/internal/panoptic/fragments/permit2.d.ts +3 -0
  22. package/lib/internal/panoptic/fragments/support.d.ts +16 -0
  23. package/lib/internal/panoptic/fragments/uniswap.d.ts +10 -0
  24. package/lib/internal/panoptic/fragments/weth.d.ts +19 -0
  25. package/lib/internal/panoptic/handlers.d.ts +27 -0
  26. package/lib/internal/panoptic/protocol.d.ts +29 -0
  27. package/lib/internal/panoptic/reads/account.d.ts +11 -0
  28. package/lib/internal/panoptic/reads/greeks.d.ts +5 -0
  29. package/lib/internal/panoptic/reads/hypovault.d.ts +7 -0
  30. package/lib/internal/panoptic/reads/pool.d.ts +10 -0
  31. package/lib/internal/panoptic/reads/uniswap.d.ts +6 -0
  32. package/lib/internal/panoptic/support.d.ts +20 -0
  33. package/lib/internal/panopticBrowserRuntime.d.ts +6 -0
  34. package/lib/internal/panopticDtos.d.ts +72 -0
  35. package/lib/internal/panopticHostEnvelope.d.ts +2 -0
  36. package/lib/internal/panopticHostImport.d.ts +17 -0
  37. package/lib/internal/panopticJsonArgs.d.ts +26 -0
  38. package/lib/internal/panopticRuntime.d.ts +12 -0
  39. package/lib/internal/panopticScalars.d.ts +10 -0
  40. package/lib/internal/panopticSerialization.d.ts +19 -0
  41. package/lib/internal/panopticSources.d.ts +22 -0
  42. package/lib/loadOptions.d.ts +5 -0
  43. package/lib/node.cjs +3634 -72
  44. package/lib/node.cjs.map +1 -1
  45. package/lib/node.d.ts +5 -2
  46. package/lib/node.mjs +3634 -72
  47. package/lib/node.mjs.map +1 -1
  48. package/lib/panoptic.cjs +19 -0
  49. package/lib/panoptic.cjs.map +1 -0
  50. package/lib/panoptic.d.ts +56 -0
  51. package/lib/panoptic.mjs +1 -0
  52. package/lib/panoptic.mjs.map +1 -0
  53. package/package.json +44 -3
package/lib/index.mjs CHANGED
@@ -180,6 +180,160 @@ var RawTradeData = class {
180
180
  }
181
181
  };
182
182
 
183
+ // src/internal/asyncHostCalls.ts
184
+ function createAsyncHostCallSlot() {
185
+ let stagedHostCall = null;
186
+ let completedHostCall = null;
187
+ function stage(call) {
188
+ if (stagedHostCall || completedHostCall) {
189
+ throw new Error("Only one async host call can be staged per asyncify unwind.");
190
+ }
191
+ stagedHostCall = call;
192
+ }
193
+ async function complete() {
194
+ if (!stagedHostCall) {
195
+ throw new Error("Asyncify unwound without a staged host call.");
196
+ }
197
+ const call = stagedHostCall;
198
+ stagedHostCall = null;
199
+ if (call.kind === "fetch-buffer") {
200
+ completedHostCall = { kind: "fetch-buffer", value: await call.run() };
201
+ return;
202
+ }
203
+ if (call.kind === "ccxt-ohlcv") {
204
+ completedHostCall = { kind: "ccxt-ohlcv", value: await call.run() };
205
+ return;
206
+ }
207
+ completedHostCall = { kind: "panoptic-json", value: await call.run() };
208
+ }
209
+ function take(kind) {
210
+ if (!completedHostCall) {
211
+ throw new Error(`Asyncify rewind for ${kind} did not have a completed host result.`);
212
+ }
213
+ if (completedHostCall.kind !== kind) {
214
+ throw new Error(`Asyncify rewind expected ${kind} but found ${completedHostCall.kind}.`);
215
+ }
216
+ const call = completedHostCall;
217
+ completedHostCall = null;
218
+ return call;
219
+ }
220
+ function reset() {
221
+ stagedHostCall = null;
222
+ completedHostCall = null;
223
+ }
224
+ return { stage, complete, take, reset };
225
+ }
226
+
227
+ // src/internal/panoptic/protocol.ts
228
+ var DEFAULT_MAX_REQUEST_BYTES = 512 * 1024;
229
+ function parsePanopticRequest(value, maxBytes = DEFAULT_MAX_REQUEST_BYTES) {
230
+ if (utf8ByteLength(value) > maxBytes) {
231
+ throw new Error(`Invalid Panoptic request JSON: request exceeds maximum size ${maxBytes} bytes.`);
232
+ }
233
+ let parsed;
234
+ try {
235
+ parsed = JSON.parse(value);
236
+ } catch (error) {
237
+ throw new Error(`Invalid Panoptic request JSON: ${error instanceof Error ? error.message : String(error)}`);
238
+ }
239
+ if (!isJsonObject(parsed) || !isJsonValue(parsed)) {
240
+ throw new Error("Invalid Panoptic request JSON: expected a JSON-safe object envelope.");
241
+ }
242
+ return parsed;
243
+ }
244
+ function assertPanopticSuccessResponse(value) {
245
+ const keys = isJsonObject(value) ? Object.keys(value) : [];
246
+ if (!isJsonObject(value) || value.ok !== true || !("result" in value) || !isJsonValue(value.result) || keys.length !== 2 || !keys.includes("ok") || !keys.includes("result")) {
247
+ throw new Error("Panoptic runtime adapter returned an invalid success response.");
248
+ }
249
+ }
250
+ function panopticSuccess(result) {
251
+ return { ok: true, result };
252
+ }
253
+ function isJsonObject(value) {
254
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
255
+ return false;
256
+ }
257
+ const prototype = Object.getPrototypeOf(value);
258
+ return prototype === Object.prototype || prototype === null;
259
+ }
260
+ function isJsonRecord(value) {
261
+ return isJsonObject(value) && isJsonValue(value);
262
+ }
263
+ function requestArgs(request, method) {
264
+ if (!isJsonRecord(request.args)) {
265
+ throw new Error(`Panoptic ${method} args must be an object.`);
266
+ }
267
+ return request.args;
268
+ }
269
+ function sanitizePanopticError(error) {
270
+ const message = error instanceof Error ? error.message : String(error);
271
+ return message.split("\n")[0].replace(/https?:\/\/[^\s)]+/gi, "[redacted-url]").replace(/\b(api[_-]?key|token|secret|authorization)=([^&\s]+)/gi, "$1=[redacted]").replace(/\b(authorization|proxy-authorization)\s*:\s*(bearer|basic)\s+[^\s,}]+/gi, "$1: $2 [redacted]").replace(/\b(bearer|basic)\s+[a-z0-9._~+/-]+=*/gi, "$1 [redacted]").replace(/"(api[_-]?key|token|secret|authorization)"\s*:\s*"[^"]*"/gi, '"$1":"[redacted]"').replace(/\b(api[_-]?key|token|secret)\s*:\s*([^\s,}]+)/gi, "$1: [redacted]").slice(0, 240);
272
+ }
273
+ function isJsonValue(value) {
274
+ if (value === null) return true;
275
+ const valueType = typeof value;
276
+ if (valueType === "string" || valueType === "number" || valueType === "boolean") {
277
+ return Number.isFinite(value) || valueType !== "number";
278
+ }
279
+ if (Array.isArray(value)) {
280
+ return value.every(isJsonValue);
281
+ }
282
+ if (isJsonObject(value)) {
283
+ return Object.values(value).every(isJsonValue);
284
+ }
285
+ return false;
286
+ }
287
+ function utf8ByteLength(value) {
288
+ let bytes = 0;
289
+ for (let i = 0; i < value.length; i++) {
290
+ const codePoint = value.codePointAt(i) || 0;
291
+ if (codePoint <= 127) {
292
+ bytes += 1;
293
+ } else if (codePoint <= 2047) {
294
+ bytes += 2;
295
+ } else if (codePoint <= 65535) {
296
+ bytes += 3;
297
+ } else {
298
+ bytes += 4;
299
+ i += 1;
300
+ }
301
+ }
302
+ return bytes;
303
+ }
304
+
305
+ // src/internal/panopticHostImport.ts
306
+ function createPanopticHostImport(options) {
307
+ return (methodPtr, paramsJsonPtr) => {
308
+ if (options.getAsyncifyState() === options.rewindingState) {
309
+ options.stopRewind();
310
+ const completed = options.hostCalls.take("panoptic-json");
311
+ return options.lowerString(completed.value, "wasm");
312
+ }
313
+ const method = options.liftString(methodPtr);
314
+ const paramsJson = options.liftString(paramsJsonPtr) || "{}";
315
+ options.hostCalls.stage({
316
+ kind: "panoptic-json",
317
+ run: async () => {
318
+ if (!method) {
319
+ throw new Error("Panoptic method not provided.");
320
+ }
321
+ const request = parsePanopticRequest(paramsJson);
322
+ const response = await callPanopticOrThrow(options.runtime, method, request);
323
+ assertPanopticSuccessResponse(response);
324
+ return JSON.stringify({ ok: true, result: response.result });
325
+ }
326
+ });
327
+ options.startUnwind();
328
+ };
329
+ }
330
+ async function callPanopticOrThrow(runtime, method, request) {
331
+ if (!runtime.callPanoptic) {
332
+ throw new Error("Panoptic runtime adapter is not available in this runtime.");
333
+ }
334
+ return runtime.callPanoptic(method, request);
335
+ }
336
+
183
337
  // src/internal/instantiate.ts
184
338
  function instantiate(module, imports = {}, runtime = {}) {
185
339
  let WASM_MEMORY;
@@ -188,9 +342,7 @@ function instantiate(module, imports = {}, runtime = {}) {
188
342
  let ASYNCIFY_PTR = 0;
189
343
  let ASYNCIFY_MEM;
190
344
  let ASYNCIFY_INITIALIZED = false;
191
- let fetchFn = null;
192
- let ccxtFn = null;
193
- let detachedValue = null;
345
+ const hostCalls = createAsyncHostCallSlot();
194
346
  let executeInFlight = false;
195
347
  const pinScopes = [];
196
348
  const adaptedImports = Object.assign(
@@ -288,31 +440,50 @@ function instantiate(module, imports = {}, runtime = {}) {
288
440
  const currentState = WASM_EXPORTS.asyncify_get_state();
289
441
  if (currentState === 2 /* Rewinding */) {
290
442
  WASM_EXPORTS.asyncify_stop_rewind();
443
+ const completed = hostCalls.take("ccxt-ohlcv");
291
444
  const ptr = __lowerStaticArray(
292
445
  (pointer, value) => {
293
- __setU32(pointer, __lowerStaticArray(__setF64, 7, 3, value, Float64Array));
446
+ __setU32(pointer, __lowerStaticArray(__setF64, 7, 3, value, Float64Array, "wasm"));
294
447
  },
295
448
  8,
296
449
  2,
297
- detachedValue
450
+ completed.value,
451
+ null,
452
+ "host"
298
453
  );
299
454
  return ptr;
300
455
  }
301
456
  const _exchange = __liftString(exchangeId);
302
457
  const _symbol = __liftString(symbol);
303
458
  const _timeframe = __liftString(timeframe);
304
- ccxtFn = async () => {
305
- if (!_exchange || !_symbol || !_timeframe)
306
- throw new Error("Exchange, Symbol, or Timeframe not provided when fetching OHCLV data.");
307
- const ccxt = await getCcxtOrThrow(runtime);
308
- const data = await new ccxt[_exchange]({
309
- apiKey: "",
310
- secret: ""
311
- }).fetchOHLCV(_symbol, _timeframe, since, limit);
312
- return data;
313
- };
459
+ hostCalls.stage({
460
+ kind: "ccxt-ohlcv",
461
+ run: async () => {
462
+ if (!_exchange || !_symbol || !_timeframe)
463
+ throw new Error("Exchange, Symbol, or Timeframe not provided when fetching OHCLV data.");
464
+ const ccxt = await getCcxtOrThrow(runtime);
465
+ const data = await new ccxt[_exchange]({
466
+ apiKey: "",
467
+ secret: ""
468
+ }).fetchOHLCV(_symbol, _timeframe, since, limit);
469
+ return data;
470
+ }
471
+ });
314
472
  WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);
315
- }
473
+ },
474
+ panoptic_call: createPanopticHostImport({
475
+ runtime,
476
+ hostCalls,
477
+ // @ts-ignore
478
+ getAsyncifyState: () => WASM_EXPORTS.asyncify_get_state(),
479
+ rewindingState: 2 /* Rewinding */,
480
+ // @ts-ignore
481
+ stopRewind: () => WASM_EXPORTS.asyncify_stop_rewind(),
482
+ // @ts-ignore
483
+ startUnwind: () => WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR),
484
+ liftString: __liftString,
485
+ lowerString: __lowerString
486
+ })
316
487
  },
317
488
  "as-fetch": {
318
489
  /**
@@ -343,25 +514,28 @@ function instantiate(module, imports = {}, runtime = {}) {
343
514
  const currentState = WASM_EXPORTS.asyncify_get_state();
344
515
  if (currentState === 2 /* Rewinding */) {
345
516
  WASM_EXPORTS.asyncify_stop_rewind();
346
- const ptr = __lowerBuffer(detachedValue);
347
- detachedValue = null;
517
+ const completed = hostCalls.take("fetch-buffer");
518
+ const ptr = __lowerBuffer(completed.value, "wasm");
348
519
  return ptr;
349
520
  }
350
- fetchFn = async () => {
351
- const fetchImpl = await getFetchOrThrow(runtime);
352
- const res = await fetchImpl(__liftString(url) || "", {
353
- method: "POST",
354
- mode: modeToString(mode) || "cors",
355
- headers: __liftArray(
356
- (pointer) => __liftArray((pointer2) => __liftString(__getU32(pointer2)), 2, __getU32(pointer)),
357
- 2,
358
- headers
359
- ) || [],
360
- body: __liftBuffer(body)
361
- });
362
- const value = await res.arrayBuffer();
363
- return value;
364
- };
521
+ hostCalls.stage({
522
+ kind: "fetch-buffer",
523
+ run: async () => {
524
+ const fetchImpl = await getFetchOrThrow(runtime);
525
+ const res = await fetchImpl(__liftString(url) || "", {
526
+ method: "POST",
527
+ mode: modeToString(mode) || "cors",
528
+ headers: __liftArray(
529
+ (pointer) => __liftArray((pointer2) => __liftString(__getU32(pointer2)), 2, __getU32(pointer)),
530
+ 2,
531
+ headers
532
+ ) || [],
533
+ body: __liftBuffer(body)
534
+ });
535
+ const value = await res.arrayBuffer();
536
+ return value;
537
+ }
538
+ });
365
539
  WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);
366
540
  },
367
541
  /**
@@ -375,24 +549,27 @@ function instantiate(module, imports = {}, runtime = {}) {
375
549
  const currentState = WASM_EXPORTS.asyncify_get_state();
376
550
  if (currentState === 2 /* Rewinding */) {
377
551
  WASM_EXPORTS.asyncify_stop_rewind();
378
- const ptr = __lowerBuffer(detachedValue);
379
- detachedValue = null;
552
+ const completed = hostCalls.take("fetch-buffer");
553
+ const ptr = __lowerBuffer(completed.value, "wasm");
380
554
  return ptr;
381
555
  }
382
- fetchFn = async () => {
383
- const fetchImpl = await getFetchOrThrow(runtime);
384
- const res = await fetchImpl(__liftString(url) || "", {
385
- method: "GET",
386
- mode: modeToString(mode) || "cors",
387
- headers: __liftArray(
388
- (pointer) => __liftArray((pointer2) => __liftString(__getU32(pointer2)), 2, __getU32(pointer)),
389
- 2,
390
- headers
391
- ) || []
392
- });
393
- const value = await res.arrayBuffer();
394
- return value;
395
- };
556
+ hostCalls.stage({
557
+ kind: "fetch-buffer",
558
+ run: async () => {
559
+ const fetchImpl = await getFetchOrThrow(runtime);
560
+ const res = await fetchImpl(__liftString(url) || "", {
561
+ method: "GET",
562
+ mode: modeToString(mode) || "cors",
563
+ headers: __liftArray(
564
+ (pointer) => __liftArray((pointer2) => __liftString(__getU32(pointer2)), 2, __getU32(pointer)),
565
+ 2,
566
+ headers
567
+ ) || []
568
+ });
569
+ const value = await res.arrayBuffer();
570
+ return value;
571
+ }
572
+ });
396
573
  WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);
397
574
  },
398
575
  /**
@@ -523,16 +700,7 @@ function instantiate(module, imports = {}, runtime = {}) {
523
700
  if (ASYNCIFY_INITIALIZED) {
524
701
  while (WASM_EXPORTS.asyncify_get_state() === 1 /* Unwinding */) {
525
702
  WASM_EXPORTS.asyncify_stop_unwind();
526
- if (fetchFn) {
527
- const pendingFetch = fetchFn;
528
- fetchFn = null;
529
- detachedValue = await pendingFetch();
530
- }
531
- if (ccxtFn) {
532
- const pendingCcxt = ccxtFn;
533
- ccxtFn = null;
534
- detachedValue = await pendingCcxt();
535
- }
703
+ await hostCalls.complete();
536
704
  WASM_EXPORTS.asyncify_start_rewind(ASYNCIFY_PTR);
537
705
  result = executeWithReplayArgs(replayArgs);
538
706
  }
@@ -543,9 +711,7 @@ function instantiate(module, imports = {}, runtime = {}) {
543
711
  for (let i = scope.length - 1; i >= 0; i--) {
544
712
  WASM_EXPORTS.__unpin(scope[i]);
545
713
  }
546
- fetchFn = null;
547
- ccxtFn = null;
548
- detachedValue = null;
714
+ hostCalls.reset();
549
715
  executeInFlight = false;
550
716
  }
551
717
  },
@@ -639,10 +805,10 @@ function instantiate(module, imports = {}, runtime = {}) {
639
805
  while (end - start > 1024) string += String.fromCharCode(...memoryU16.subarray(start, start += 1024));
640
806
  return string + String.fromCharCode(...memoryU16.subarray(start, end));
641
807
  }
642
- function __lowerString(value) {
808
+ function __lowerString(value, owner = "host") {
643
809
  if (value == null) return 0;
644
810
  const length = value.length;
645
- const ptr = trackPinnedPointer(WASM_EXPORTS.__pin(WASM_EXPORTS.__new(length << 1, 2) >>> 0));
811
+ const ptr = allocateLoweredPointer(length << 1, 2, owner);
646
812
  const memoryU16 = new Uint16Array(WASM_MEMORY.buffer);
647
813
  for (let i = 0; i < length; ++i) memoryU16[(ptr >>> 1) + i] = value.charCodeAt(i);
648
814
  return ptr;
@@ -651,9 +817,9 @@ function instantiate(module, imports = {}, runtime = {}) {
651
817
  if (!ptr) return null;
652
818
  return WASM_MEMORY.buffer.slice(ptr, ptr + new Uint32Array(WASM_MEMORY.buffer)[ptr - 4 >>> 2]);
653
819
  }
654
- function __lowerBuffer(value) {
820
+ function __lowerBuffer(value, owner = "host") {
655
821
  if (value == null) return 0;
656
- const ptr = trackPinnedPointer(WASM_EXPORTS.__pin(WASM_EXPORTS.__new(value.byteLength, 1) >>> 0));
822
+ const ptr = allocateLoweredPointer(value.byteLength, 1, owner);
657
823
  new Uint8Array(WASM_MEMORY.buffer).set(new Uint8Array(value), ptr);
658
824
  return ptr;
659
825
  }
@@ -665,10 +831,10 @@ function instantiate(module, imports = {}, runtime = {}) {
665
831
  for (let i = 0; i < length; ++i) values[i] = liftElement(dataStart + (i << align >>> 0));
666
832
  return values;
667
833
  }
668
- function __lowerStaticArray(lowerElement, id, align, values, typedConstructor = null) {
834
+ function __lowerStaticArray(lowerElement, id, align, values, typedConstructor = null, owner = "host") {
669
835
  if (values == null) return 0;
670
836
  const length = values.length;
671
- const buffer = trackPinnedPointer(WASM_EXPORTS.__pin(WASM_EXPORTS.__new(length << align, id)) >>> 0) >>> 0;
837
+ const buffer = allocateLoweredPointer(length << align, id, owner) >>> 0;
672
838
  if (typedConstructor) {
673
839
  new typedConstructor(WASM_MEMORY.buffer, buffer, length).set(values);
674
840
  } else {
@@ -676,6 +842,13 @@ function instantiate(module, imports = {}, runtime = {}) {
676
842
  }
677
843
  return buffer;
678
844
  }
845
+ function allocateLoweredPointer(size, id, owner) {
846
+ const ptr = WASM_EXPORTS.__new(size, id) >>> 0;
847
+ if (owner === "wasm") {
848
+ return ptr;
849
+ }
850
+ return trackPinnedPointer(WASM_EXPORTS.__pin(ptr) >>> 0);
851
+ }
679
852
  function __setU32(ptr, value) {
680
853
  try {
681
854
  WASM_DV.setUint32(ptr, value, true);
@@ -722,60 +895,3467 @@ function modeToString(mode) {
722
895
  return null;
723
896
  }
724
897
 
725
- // src/index.ts
726
- function loadWasmSync(input, imports = {}) {
727
- return instantiate(new WebAssembly.Module(input), imports, {
728
- getFetch: getRuntimeFetch,
729
- getCcxt: getRuntimeCcxt
730
- });
898
+ // src/internal/panopticBrowserRuntime.ts
899
+ async function callBrowserPanoptic(method, request) {
900
+ void method;
901
+ void request;
902
+ throw new Error(
903
+ "Panoptic runtime adapter is not enabled for browser runtimes yet. Phase 8 must choose globalThis SDK globals or dynamic browser imports first."
904
+ );
731
905
  }
732
- async function loadWasm(input, imports = {}) {
733
- const module = typeof input === "string" ? await compileFromString(input) : await WebAssembly.compile(input);
734
- return instantiate(module, imports, {
735
- getFetch: getRuntimeFetch,
736
- getCcxt: getRuntimeCcxt
906
+
907
+ // src/internal/panoptic/deps.ts
908
+ var PANOPTIC_MODULE_SPECIFIERS = {
909
+ sdk: "@panoptic-eng/sdk",
910
+ sdkV2: "@panoptic-eng/sdk/v2",
911
+ uniswap: "@panoptic-eng/sdk/uniswap",
912
+ viem: "viem"
913
+ };
914
+ var dynamicImport = null;
915
+ var runtimeImport = null;
916
+ var moduleCache = /* @__PURE__ */ new Map();
917
+ function createPanopticDependencies() {
918
+ return {
919
+ sdk: () => loadPanopticModuleRecord("sdk"),
920
+ sdkV2: () => loadPanopticModuleRecord("sdkV2"),
921
+ uniswap: () => loadPanopticModuleRecord("uniswap"),
922
+ viem: () => loadPanopticModuleRecord("viem")
923
+ };
924
+ }
925
+ async function loadPanopticModule(key) {
926
+ const cached = moduleCache.get(key);
927
+ if (cached) {
928
+ return cached;
929
+ }
930
+ const specifier = PANOPTIC_MODULE_SPECIFIERS[key];
931
+ const loaded = getRuntimeImport()(specifier).catch(() => {
932
+ moduleCache.delete(key);
933
+ throw missingPanopticDependencyError(specifier);
737
934
  });
935
+ moduleCache.set(key, loaded);
936
+ return loaded;
738
937
  }
739
- async function compileFromString(input) {
740
- if (!isNodeRuntime()) {
741
- return compileFromUrl(input);
938
+ async function loadPanopticModuleRecord(key) {
939
+ const loadedModule = await loadPanopticModule(key);
940
+ if (!isRecord(loadedModule)) {
941
+ return {};
742
942
  }
743
- if (isHttpUrl(input)) {
744
- return compileFromUrl(input);
943
+ return loadedModule;
944
+ }
945
+ function missingPanopticDependencyError(specifier) {
946
+ return new Error(
947
+ `Panoptic runtime dependency "${specifier}" is not available. Install the optional Panoptic dependencies before calling Panoptic methods.`
948
+ );
949
+ }
950
+ function isRecord(value) {
951
+ return typeof value === "object" && value !== null && !Array.isArray(value);
952
+ }
953
+ function getRuntimeImport() {
954
+ if (runtimeImport) {
955
+ return runtimeImport;
745
956
  }
746
- const fs = await importRuntimeModule("fs/promises");
747
- return WebAssembly.compile(await fs.readFile(input));
957
+ if (!dynamicImport) {
958
+ dynamicImport = new Function("s", "return import(s)");
959
+ }
960
+ return dynamicImport;
748
961
  }
749
- async function compileFromUrl(url) {
750
- const fetchImpl = await getRuntimeFetch();
751
- const response = await fetchImpl(url);
752
- if (typeof WebAssembly.compileStreaming === "function") {
962
+
963
+ // src/internal/panopticSerialization.ts
964
+ var DEFAULT_MAX_ARRAY_ITEMS = 256;
965
+ var DEFAULT_MAX_OBJECT_KEYS = 128;
966
+ var DEFAULT_MAX_DEPTH = 32;
967
+ var DEFAULT_MAX_REQUEST_BYTES2 = 512 * 1024;
968
+ var DEFAULT_MAX_RESPONSE_BYTES = 512 * 1024;
969
+ var DEFAULT_MAX_CALLDATA_BYTES = 256 * 1024;
970
+ var DEFAULT_MAX_STRING_BYTES = 64 * 1024;
971
+ var DEFAULT_MAX_DECIMAL_DIGITS = 96;
972
+ function normalizePanopticAddress(value, fieldName = "address") {
973
+ if (typeof value !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(value)) {
974
+ throw new Error(`Panoptic ${fieldName} must be a 20-byte hex address.`);
975
+ }
976
+ return value.toLowerCase();
977
+ }
978
+ function normalizePanopticHex(value, fieldName = "hex", maxBytes = DEFAULT_MAX_CALLDATA_BYTES) {
979
+ if (typeof value === "string" && value.length > maxBytes * 2 + 2) {
980
+ throw new Error(`Panoptic ${fieldName} exceeds maximum hex size ${maxBytes} bytes.`);
981
+ }
982
+ if (typeof value !== "string" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) {
983
+ throw new Error(`Panoptic ${fieldName} must be an even-length hex string.`);
984
+ }
985
+ return value.toLowerCase();
986
+ }
987
+ function normalizePanopticDecimalString(value, fieldName = "value", maxDigits = DEFAULT_MAX_DECIMAL_DIGITS) {
988
+ if (typeof value === "string" && /^(0|[1-9][0-9]*)$/.test(value)) {
989
+ assertDecimalDigitLength(value, fieldName, maxDigits);
990
+ return BigInt(value).toString(10);
991
+ }
992
+ throw new Error(`Panoptic ${fieldName} must be an unsigned decimal string.`);
993
+ }
994
+ function projectPanopticSerializableValue(value, limits = {}, label = "result") {
995
+ const normalized = normalizeSerializableValue(value, normalizeLimits(limits), label, 0, /* @__PURE__ */ new WeakSet());
996
+ assertSerializedSize(normalized, limits.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES, label, "response");
997
+ return normalized;
998
+ }
999
+ function normalizeSerializableValue(value, limits, path, depth, seen) {
1000
+ if (depth > limits.maxDepth) {
1001
+ throw new Error(`Panoptic ${path} exceeds maximum JSON depth.`);
1002
+ }
1003
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
1004
+ enforceHexSizeIfNeeded(value, limits, path);
1005
+ if (typeof value === "string" && utf8ByteLength2(value) > limits.maxStringBytes) {
1006
+ throw new Error(`Panoptic ${path} exceeds maximum string length ${limits.maxStringBytes} bytes.`);
1007
+ }
1008
+ return value;
1009
+ }
1010
+ if (typeof value === "bigint") {
1011
+ return value.toString(10);
1012
+ }
1013
+ if (typeof value === "number") {
1014
+ if (!Number.isFinite(value)) {
1015
+ throw new Error(`Panoptic ${path} must be a finite number.`);
1016
+ }
1017
+ return value;
1018
+ }
1019
+ if (value instanceof Uint8Array) {
1020
+ if (value.byteLength > limits.maxCalldataBytes) {
1021
+ throw new Error(`Panoptic ${path} exceeds maximum encoded calldata size ${limits.maxCalldataBytes} bytes.`);
1022
+ }
1023
+ return bytesToHex(value);
1024
+ }
1025
+ if (value instanceof ArrayBuffer) {
1026
+ if (value.byteLength > limits.maxCalldataBytes) {
1027
+ throw new Error(`Panoptic ${path} exceeds maximum encoded calldata size ${limits.maxCalldataBytes} bytes.`);
1028
+ }
1029
+ return bytesToHex(new Uint8Array(value));
1030
+ }
1031
+ if (Array.isArray(value)) {
1032
+ if (value.length > limits.maxArrayItems) {
1033
+ throw new Error(`Panoptic ${path} exceeds maximum array length ${limits.maxArrayItems}.`);
1034
+ }
1035
+ return value.map((item, index) => normalizeSerializableValue(item, limits, `${path}[${index}]`, depth + 1, seen));
1036
+ }
1037
+ if (typeof value === "object" && value !== null) {
1038
+ const prototype = Object.getPrototypeOf(value);
1039
+ if (prototype !== Object.prototype && prototype !== null) {
1040
+ throw new Error(`Panoptic ${path} must be explicitly projected before crossing the wasm boundary.`);
1041
+ }
1042
+ if (seen.has(value)) {
1043
+ throw new Error(`Panoptic ${path} contains a circular reference.`);
1044
+ }
1045
+ seen.add(value);
1046
+ const entries = Object.entries(value);
1047
+ if (entries.length > limits.maxObjectKeys) {
1048
+ throw new Error(`Panoptic ${path} exceeds maximum object key count ${limits.maxObjectKeys}.`);
1049
+ }
1050
+ const normalized = /* @__PURE__ */ Object.create(null);
1051
+ for (const [key, entryValue] of entries) {
1052
+ if (isUnsafeObjectKey(key)) {
1053
+ throw new Error(`Panoptic ${path}.${key} is not supported as an object key.`);
1054
+ }
1055
+ if (entryValue === void 0 || typeof entryValue === "function" || typeof entryValue === "symbol") {
1056
+ throw new Error(`Panoptic ${path}.${key} is not serializable.`);
1057
+ }
1058
+ normalized[key] = normalizeSerializableValue(entryValue, limits, `${path}.${key}`, depth + 1, seen);
1059
+ }
1060
+ seen.delete(value);
1061
+ return normalized;
1062
+ }
1063
+ throw new Error(`Panoptic ${path} is not serializable.`);
1064
+ }
1065
+ function normalizeLimits(limits) {
1066
+ return {
1067
+ maxArrayItems: limits.maxArrayItems ?? DEFAULT_MAX_ARRAY_ITEMS,
1068
+ maxObjectKeys: limits.maxObjectKeys ?? DEFAULT_MAX_OBJECT_KEYS,
1069
+ maxDepth: limits.maxDepth ?? DEFAULT_MAX_DEPTH,
1070
+ maxRequestBytes: limits.maxRequestBytes ?? DEFAULT_MAX_REQUEST_BYTES2,
1071
+ maxResponseBytes: limits.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
1072
+ maxCalldataBytes: limits.maxCalldataBytes ?? DEFAULT_MAX_CALLDATA_BYTES,
1073
+ maxStringBytes: limits.maxStringBytes ?? DEFAULT_MAX_STRING_BYTES,
1074
+ maxDecimalDigits: limits.maxDecimalDigits ?? DEFAULT_MAX_DECIMAL_DIGITS
1075
+ };
1076
+ }
1077
+ function assertSerializedSize(value, maxBytes, label, kind) {
1078
+ const serialized = JSON.stringify(value);
1079
+ if (utf8ByteLength2(serialized) > maxBytes) {
1080
+ throw new Error(`Panoptic ${label} exceeds maximum ${kind} size ${maxBytes} bytes.`);
1081
+ }
1082
+ }
1083
+ function utf8ByteLength2(value) {
1084
+ let bytes = 0;
1085
+ for (let i = 0; i < value.length; i++) {
1086
+ const codePoint = value.codePointAt(i) || 0;
1087
+ if (codePoint > 65535) {
1088
+ i += 1;
1089
+ }
1090
+ if (codePoint <= 127) {
1091
+ bytes += 1;
1092
+ } else if (codePoint <= 2047) {
1093
+ bytes += 2;
1094
+ } else if (codePoint <= 65535) {
1095
+ bytes += 3;
1096
+ } else {
1097
+ bytes += 4;
1098
+ }
1099
+ }
1100
+ return bytes;
1101
+ }
1102
+ function enforceHexSizeIfNeeded(value, limits, path) {
1103
+ if (typeof value !== "string" || !/^0x[0-9a-fA-F]*$/.test(value)) {
1104
+ return;
1105
+ }
1106
+ const byteLength = Math.max(0, (value.length - 2) / 2);
1107
+ if (byteLength > limits.maxCalldataBytes) {
1108
+ throw new Error(`Panoptic ${path} exceeds maximum encoded calldata size ${limits.maxCalldataBytes} bytes.`);
1109
+ }
1110
+ }
1111
+ function bytesToHex(bytes) {
1112
+ let hex = "0x";
1113
+ for (const byte of bytes) {
1114
+ hex += byte.toString(16).padStart(2, "0");
1115
+ }
1116
+ return hex;
1117
+ }
1118
+ function assertDecimalDigitLength(value, fieldName, maxDigits) {
1119
+ if (value.length > maxDigits) {
1120
+ throw new Error(`Panoptic ${fieldName} exceeds maximum decimal digit length ${maxDigits}.`);
1121
+ }
1122
+ }
1123
+ function isUnsafeObjectKey(key) {
1124
+ return key === "__proto__" || key === "constructor" || key === "prototype";
1125
+ }
1126
+
1127
+ // src/internal/panopticSources.ts
1128
+ var DEFAULT_OPERATION_TIMEOUT_MS = 1e4;
1129
+ var DEFAULT_OPERATION_RETRIES = 2;
1130
+ var DEFAULT_CLIENT_CACHE_MAX_ENTRIES = 16;
1131
+ var publicClientCache = /* @__PURE__ */ new Map();
1132
+ function resolvePanopticSource(context, registry) {
1133
+ if (!context?.sourceId && !context?.chainId && !context?.rpcUrl) {
1134
+ throw new Error("Panoptic source context must include sourceId or chainId.");
1135
+ }
1136
+ if (!registry?.sources?.length) {
1137
+ throw new Error("Panoptic source registry is not configured.");
1138
+ }
1139
+ const requestedChainId = context.chainId ? normalizeDecimalString(context.chainId, "chainId") : null;
1140
+ const source = selectRegistrySource(context.sourceId, requestedChainId, registry);
1141
+ const sourceChainId = normalizeDecimalString(source.chainId, "source.chainId");
1142
+ if (requestedChainId && sourceChainId !== requestedChainId) {
1143
+ throw new Error(
1144
+ `Panoptic source "${source.sourceId}" is configured for chain ${sourceChainId}, not requested chain ${requestedChainId}.`
1145
+ );
1146
+ }
1147
+ const registryRpcUrl = normalizeRegistryRpcUrl(source, registry);
1148
+ const rpcUrl = context.rpcUrl ? normalizeOverrideRpcUrl(context.rpcUrl, source, registry) : registryRpcUrl;
1149
+ return {
1150
+ source,
1151
+ chainId: sourceChainId,
1152
+ rpcUrl,
1153
+ normalizedRpcUrl: rpcUrl,
1154
+ overrideApplied: !!context.rpcUrl && rpcUrl !== registryRpcUrl
1155
+ };
1156
+ }
1157
+ async function preparePanopticSourceContext(request, viemModule, registry, operationOptions = {}, cacheOptions = {}) {
1158
+ const source = resolvePanopticSource(request.context, registry);
1159
+ const client = getPanopticPublicClient(viemModule, source, cacheOptions);
1160
+ await runPanopticOperation(
1161
+ "Panoptic RPC chain verification",
1162
+ () => verifyPanopticSourceChain(client, source.chainId),
1163
+ operationOptions
1164
+ );
1165
+ const blockNumber = request.context?.blockNumber ? normalizeDecimalString(request.context.blockNumber, "blockNumber") : await runPanopticOperation("Panoptic RPC block pinning", () => readPanopticBlockNumber(client), operationOptions);
1166
+ return {
1167
+ source,
1168
+ client,
1169
+ blockNumber,
1170
+ sourceMeta: buildSourceMeta(source, blockNumber)
1171
+ };
1172
+ }
1173
+ function getPanopticPublicClient(viemModule, source, options = {}) {
1174
+ const viem = viemModule;
1175
+ if (typeof viem.createPublicClient !== "function" || typeof viem.http !== "function") {
1176
+ throw new Error('Panoptic runtime dependency "viem" does not provide createPublicClient and http.');
1177
+ }
1178
+ const maxEntries = normalizeClientCacheMaxEntries(options.maxEntries);
1179
+ const cacheKey = buildPublicClientCacheKey(source);
1180
+ const cached = publicClientCache.get(cacheKey);
1181
+ if (cached) {
1182
+ publicClientCache.delete(cacheKey);
1183
+ publicClientCache.set(cacheKey, cached);
1184
+ return cached;
1185
+ }
1186
+ const clientOptions = getNormalizedClientOptions(source);
1187
+ const client = viem.createPublicClient({
1188
+ ...clientOptions,
1189
+ chain: {
1190
+ id: Number(source.chainId),
1191
+ name: source.source.label || source.source.sourceId,
1192
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
1193
+ rpcUrls: { default: { http: [source.normalizedRpcUrl] } }
1194
+ },
1195
+ transport: viem.http(source.normalizedRpcUrl)
1196
+ });
1197
+ publicClientCache.set(cacheKey, client);
1198
+ evictPublicClientCache(maxEntries);
1199
+ return client;
1200
+ }
1201
+ async function verifyPanopticSourceChain(client, expectedChainId) {
1202
+ const actualChainId = normalizeChainIdValue(await readPanopticChainId(client), "rpc.chainId");
1203
+ if (actualChainId !== expectedChainId) {
1204
+ throw new Error(`Panoptic RPC chain mismatch: expected ${expectedChainId}, received ${actualChainId}.`);
1205
+ }
1206
+ }
1207
+ async function readPanopticBlockNumber(client) {
1208
+ const blockNumber = await callClient(client, "getBlockNumber", { method: "eth_blockNumber" });
1209
+ return normalizeChainIdValue(blockNumber, "rpc.blockNumber");
1210
+ }
1211
+ function buildSourceMeta(source, blockNumber) {
1212
+ return {
1213
+ chainId: source.chainId,
1214
+ blockNumber,
1215
+ rpcSourceId: source.source.sourceId,
1216
+ ...source.source.subgraph?.sourceId ? { subgraphSourceId: source.source.subgraph.sourceId } : {}
1217
+ };
1218
+ }
1219
+ async function runPanopticOperation(label, operation, options = {}) {
1220
+ const retries = options.retries ?? DEFAULT_OPERATION_RETRIES;
1221
+ let lastError;
1222
+ for (let attempt = 1; attempt <= retries + 1; attempt++) {
1223
+ const startedAt = Date.now();
753
1224
  try {
754
- return await WebAssembly.compileStreaming(Promise.resolve(response.clone()));
755
- } catch {
1225
+ throwIfAborted(options.signal);
1226
+ const result = await withTimeout(operation(), label, options.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS);
1227
+ options.onAudit?.({ label, status: "success", attempt, durationMs: Date.now() - startedAt });
1228
+ return result;
1229
+ } catch (error) {
1230
+ lastError = error;
1231
+ options.onAudit?.({
1232
+ label,
1233
+ status: "failure",
1234
+ attempt,
1235
+ durationMs: Date.now() - startedAt,
1236
+ error: sanitizeOperationError(error)
1237
+ });
1238
+ if (attempt > retries || isNonRetryablePanopticOperationError(error)) {
1239
+ break;
1240
+ }
756
1241
  }
757
1242
  }
758
- return WebAssembly.compile(await response.arrayBuffer());
1243
+ throw new Error(`${label} failed: ${sanitizeOperationError(lastError)}`);
759
1244
  }
760
- async function getRuntimeFetch() {
761
- if (typeof globalThis.fetch === "function") {
762
- return globalThis.fetch.bind(globalThis);
1245
+ function buildPublicClientCacheKey(source) {
1246
+ return `${source.chainId}:${source.normalizedRpcUrl}:${stableStringify(getNormalizedClientOptions(source))}`;
1247
+ }
1248
+ function getNormalizedClientOptions(source) {
1249
+ if (!isJsonObject2(source.source.clientOptions)) {
1250
+ return {};
763
1251
  }
764
- if (!isNodeRuntime()) {
765
- throw new Error("Fetch is not available in this browser runtime.");
1252
+ const normalized = projectPanopticSerializableValue(
1253
+ source.source.clientOptions,
1254
+ { maxDepth: 8, maxObjectKeys: 64, maxResponseBytes: 32 * 1024 },
1255
+ "source.clientOptions"
1256
+ );
1257
+ if (!isJsonObject2(normalized)) {
1258
+ return {};
766
1259
  }
767
- throw new Error("Fetch is not available in this Node runtime. Node 18+ is required.");
1260
+ return normalized;
768
1261
  }
769
- async function getRuntimeCcxt() {
770
- if (isNodeRuntime()) {
771
- const ccxt2 = await importRuntimeModule("ccxt");
772
- return ccxt2.default ?? ccxt2;
1262
+ function selectRegistrySource(sourceId, requestedChainId, registry) {
1263
+ if (sourceId) {
1264
+ const source = registry.sources.find((candidate) => candidate.sourceId === sourceId);
1265
+ if (!source) {
1266
+ throw new Error(`Panoptic source "${sourceId}" is not configured.`);
1267
+ }
1268
+ return source;
773
1269
  }
774
- const ccxt = globalThis.ccxt;
775
- if (!ccxt) {
776
- throw new Error("ccxt is not available in this browser runtime.");
1270
+ const candidates = registry.sources.filter(
1271
+ (source) => normalizeDecimalString(source.chainId, "source.chainId") === requestedChainId
1272
+ );
1273
+ if (candidates.length === 0) {
1274
+ throw new Error(`No Panoptic source is configured for chain ${requestedChainId}.`);
777
1275
  }
778
- return ccxt;
1276
+ if (candidates.length > 1) {
1277
+ throw new Error(`Multiple Panoptic sources are configured for chain ${requestedChainId}; sourceId is required.`);
1278
+ }
1279
+ return candidates[0];
1280
+ }
1281
+ function normalizeOverrideRpcUrl(value, source, registry) {
1282
+ if (!source.overrideable) {
1283
+ throw new Error(`Panoptic source "${source.sourceId}" does not allow RPC URL overrides.`);
1284
+ }
1285
+ const normalized = normalizeRpcUrl(value);
1286
+ const overrideUrl = new URL(normalized);
1287
+ const registryUrl = new URL(normalizeRegistryRpcUrl(source, registry));
1288
+ const allowLocalhost = !!(registry.devMode && source.allowLocalhostOverrides);
1289
+ if (isLocalOrPrivateHostname(overrideUrl.hostname) && !allowLocalhost) {
1290
+ throw new Error("Panoptic RPC URL override uses a localhost or private host without explicit dev-mode permission.");
1291
+ }
1292
+ if (overrideUrl.protocol !== "https:" && !(allowLocalhost && overrideUrl.protocol === "http:")) {
1293
+ throw new Error("Panoptic RPC URL override must use https.");
1294
+ }
1295
+ const allowedHosts = /* @__PURE__ */ new Set([
1296
+ registryUrl.hostname.toLowerCase(),
1297
+ ...(registry.allowedOverrideHosts || []).map((host) => host.toLowerCase()),
1298
+ ...(source.allowedOverrideHosts || []).map((host) => host.toLowerCase())
1299
+ ]);
1300
+ if (!hostMatchesAllowedList(overrideUrl.hostname, allowedHosts)) {
1301
+ throw new Error(`Panoptic RPC URL override host "${overrideUrl.hostname}" is not allowed.`);
1302
+ }
1303
+ return normalized;
1304
+ }
1305
+ function normalizeRegistryRpcUrl(source, registry) {
1306
+ const normalized = normalizeRpcUrl(source.rpcUrl);
1307
+ const url = new URL(normalized);
1308
+ const allowLocalhost = !!(registry.devMode && source.allowLocalhostOverrides);
1309
+ if (isLocalOrPrivateHostname(url.hostname) && !allowLocalhost) {
1310
+ throw new Error("Panoptic registry RPC URL uses a localhost or private host without explicit dev-mode permission.");
1311
+ }
1312
+ if (url.protocol !== "https:" && !(allowLocalhost && url.protocol === "http:")) {
1313
+ throw new Error("Panoptic registry RPC URL must use https.");
1314
+ }
1315
+ return normalized;
1316
+ }
1317
+ function normalizeRpcUrl(value) {
1318
+ let url;
1319
+ try {
1320
+ url = new URL(value);
1321
+ } catch {
1322
+ throw new Error("Panoptic RPC URL must be an absolute URL.");
1323
+ }
1324
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
1325
+ throw new Error("Panoptic RPC URL must use http or https.");
1326
+ }
1327
+ if (url.hash) {
1328
+ throw new Error("Panoptic RPC URL must not include a fragment.");
1329
+ }
1330
+ url.protocol = url.protocol.toLowerCase();
1331
+ url.hostname = url.hostname.toLowerCase();
1332
+ if (url.pathname === "/" && !url.search) {
1333
+ return `${url.protocol}//${url.host}`;
1334
+ }
1335
+ return url.toString();
1336
+ }
1337
+ function normalizeDecimalString(value, fieldName) {
1338
+ if (!/^(0|[1-9][0-9]*)$/.test(value)) {
1339
+ throw new Error(`Panoptic ${fieldName} must be a decimal string.`);
1340
+ }
1341
+ return BigInt(value).toString(10);
1342
+ }
1343
+ function normalizeChainIdValue(value, fieldName) {
1344
+ if (typeof value === "bigint") {
1345
+ return value.toString(10);
1346
+ }
1347
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) {
1348
+ return value.toString(10);
1349
+ }
1350
+ if (typeof value === "string") {
1351
+ if (/^0x[0-9a-f]+$/i.test(value)) {
1352
+ return BigInt(value).toString(10);
1353
+ }
1354
+ return normalizeDecimalString(value, fieldName);
1355
+ }
1356
+ throw new Error(`Panoptic ${fieldName} must be a decimal string, hex string, bigint, or safe integer.`);
1357
+ }
1358
+ async function readPanopticChainId(client) {
1359
+ return callClient(client, "getChainId", { method: "eth_chainId" });
1360
+ }
1361
+ async function callClient(client, methodName, request) {
1362
+ if (isRecord2(client) && typeof client[methodName] === "function") {
1363
+ return client[methodName]();
1364
+ }
1365
+ if (isRecord2(client) && typeof client.request === "function") {
1366
+ return client.request(request);
1367
+ }
1368
+ throw new Error(`Panoptic viem client does not provide ${methodName} or request.`);
1369
+ }
1370
+ function evictPublicClientCache(maxEntries) {
1371
+ while (publicClientCache.size > maxEntries) {
1372
+ const oldestKey = publicClientCache.keys().next().value;
1373
+ if (oldestKey === void 0) {
1374
+ break;
1375
+ }
1376
+ publicClientCache.delete(oldestKey);
1377
+ }
1378
+ }
1379
+ function normalizeClientCacheMaxEntries(maxEntries) {
1380
+ if (maxEntries === void 0) {
1381
+ return DEFAULT_CLIENT_CACHE_MAX_ENTRIES;
1382
+ }
1383
+ if (!Number.isInteger(maxEntries) || maxEntries < 1) {
1384
+ throw new Error("Panoptic client cache maxEntries must be a positive integer.");
1385
+ }
1386
+ return maxEntries;
1387
+ }
1388
+ function hostMatchesAllowedList(hostname, allowedHosts) {
1389
+ const normalized = hostname.toLowerCase();
1390
+ for (const allowedHost of allowedHosts) {
1391
+ if (allowedHost.startsWith("*.") && normalized.endsWith(allowedHost.slice(1))) {
1392
+ return true;
1393
+ }
1394
+ if (normalized === allowedHost) {
1395
+ return true;
1396
+ }
1397
+ }
1398
+ return false;
1399
+ }
1400
+ function isLocalOrPrivateHostname(hostname) {
1401
+ const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
1402
+ if (normalized === "localhost" || normalized === "::" || normalized === "::1" || normalized === "0:0:0:0:0:0:0:0" || normalized === "0:0:0:0:0:0:0:1") {
1403
+ return true;
1404
+ }
1405
+ if (normalized.startsWith("::ffff:")) {
1406
+ return true;
1407
+ }
1408
+ const ipv4Parts = normalized.split(".").map((part) => Number(part));
1409
+ if (ipv4Parts.length === 4 && ipv4Parts.every((part) => Number.isInteger(part) && part >= 0 && part <= 255)) {
1410
+ const [first, second] = ipv4Parts;
1411
+ return first === 0 || first === 10 || first === 127 || first === 172 && second >= 16 && second <= 31 || first === 192 && second === 168 || first === 169 && second === 254;
1412
+ }
1413
+ return normalized.startsWith("fc") || normalized.startsWith("fd") || normalized.startsWith("fe8") || normalized.startsWith("fe9") || normalized.startsWith("fea") || normalized.startsWith("feb");
1414
+ }
1415
+ async function withTimeout(promise, label, timeoutMs) {
1416
+ let timeout = null;
1417
+ try {
1418
+ return await Promise.race([
1419
+ promise,
1420
+ new Promise((_, reject) => {
1421
+ timeout = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms.`)), timeoutMs);
1422
+ })
1423
+ ]);
1424
+ } finally {
1425
+ if (timeout) {
1426
+ clearTimeout(timeout);
1427
+ }
1428
+ }
1429
+ }
1430
+ function throwIfAborted(signal) {
1431
+ if (signal?.aborted) {
1432
+ throw new Error("Panoptic operation was aborted.");
1433
+ }
1434
+ }
1435
+ function sanitizeOperationError(error) {
1436
+ return sanitizePanopticError(error);
1437
+ }
1438
+ function isNonRetryablePanopticOperationError(error) {
1439
+ return sanitizeOperationError(error).startsWith('Panoptic runtime dependency "');
1440
+ }
1441
+ function stableStringify(value) {
1442
+ if (Array.isArray(value)) {
1443
+ return `[${value.map(stableStringify).join(",")}]`;
1444
+ }
1445
+ if (isJsonObject2(value)) {
1446
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
1447
+ }
1448
+ return JSON.stringify(value);
1449
+ }
1450
+ function isJsonObject2(value) {
1451
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1452
+ }
1453
+ function isRecord2(value) {
1454
+ return typeof value === "object" && value !== null;
1455
+ }
1456
+
1457
+ // src/internal/panopticJsonArgs.ts
1458
+ function decimalValue(value, label) {
1459
+ if (typeof value !== "string" || !/^(0|[1-9][0-9]*)$/.test(value)) {
1460
+ throw new Error(`Panoptic ${label} must be a decimal string.`);
1461
+ }
1462
+ return BigInt(value);
1463
+ }
1464
+ function signedDecimalValue(value, label) {
1465
+ if (typeof value !== "string" || !/^-?(0|[1-9][0-9]*)$/.test(value)) {
1466
+ throw new Error(`Panoptic ${label} must be a signed decimal string.`);
1467
+ }
1468
+ return BigInt(value);
1469
+ }
1470
+ function stringValue(value, label) {
1471
+ if (typeof value !== "string") {
1472
+ throw new Error(`Panoptic ${label} must be a string.`);
1473
+ }
1474
+ return value;
1475
+ }
1476
+ function booleanValue(value, label) {
1477
+ if (typeof value !== "boolean") {
1478
+ throw new Error(`Panoptic ${label} must be a boolean.`);
1479
+ }
1480
+ return value;
1481
+ }
1482
+ function numberValue(value, label) {
1483
+ if (typeof value !== "number") {
1484
+ throw new Error(`Panoptic ${label} must be a number.`);
1485
+ }
1486
+ return value;
1487
+ }
1488
+ function decimalArg(args, fieldName) {
1489
+ return decimalValue(args[fieldName], `args.${fieldName}`);
1490
+ }
1491
+ function signedDecimalArg(args, fieldName) {
1492
+ return signedDecimalValue(args[fieldName], `args.${fieldName}`);
1493
+ }
1494
+ function optionalDecimalArg(args, fieldName) {
1495
+ return args[fieldName] === void 0 ? void 0 : decimalArg(args, fieldName);
1496
+ }
1497
+ function optionalSignedDecimalArg(args, fieldName) {
1498
+ return args[fieldName] === void 0 ? void 0 : signedDecimalArg(args, fieldName);
1499
+ }
1500
+ function optionalBooleanArg(args, fieldName) {
1501
+ return args[fieldName] === void 0 ? void 0 : booleanValue(args[fieldName], `args.${fieldName}`);
1502
+ }
1503
+ function decimalArrayArg(args, fieldName) {
1504
+ return decimalArrayValue(args[fieldName], `args.${fieldName}`);
1505
+ }
1506
+ function optionalDecimalArrayArg(args, fieldName) {
1507
+ return args[fieldName] === void 0 ? void 0 : decimalArrayArg(args, fieldName);
1508
+ }
1509
+ function signedDecimalArrayArg(args, fieldName) {
1510
+ return arrayValue(args[fieldName], `args.${fieldName}`).map(
1511
+ (item, index) => signedDecimalValue(item, `args.${fieldName}[${index}]`)
1512
+ );
1513
+ }
1514
+ function decimalMatrixArg(args, fieldName) {
1515
+ return arrayValue(args[fieldName], `args.${fieldName}`).map(
1516
+ (row, rowIndex) => decimalArrayValue(row, `args.${fieldName}[${rowIndex}]`)
1517
+ );
1518
+ }
1519
+ function optionalStringArrayArg(args, fieldName) {
1520
+ if (args[fieldName] === void 0) {
1521
+ return void 0;
1522
+ }
1523
+ return arrayValue(args[fieldName], `args.${fieldName}`).map(
1524
+ (item, index) => stringValue(item, `args.${fieldName}[${index}]`)
1525
+ );
1526
+ }
1527
+ function decimalArrayValue(value, label) {
1528
+ return arrayValue(value, label).map((item, index) => decimalValue(item, `${label}[${index}]`));
1529
+ }
1530
+ function arrayValue(value, label) {
1531
+ if (!Array.isArray(value)) {
1532
+ throw new Error(`Panoptic ${label} must be an array.`);
1533
+ }
1534
+ return value;
1535
+ }
1536
+ function recordValue(value, label) {
1537
+ if (!isJsonRecord2(value)) {
1538
+ throw new Error(`Panoptic ${label} must be an object.`);
1539
+ }
1540
+ return value;
1541
+ }
1542
+ function isJsonRecord2(value) {
1543
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1544
+ }
1545
+ function isRecord3(value) {
1546
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1547
+ }
1548
+
1549
+ // src/internal/panopticDtos.ts
1550
+ function collateralAddressesValue(value, label) {
1551
+ const record = recordValue(value, label);
1552
+ return {
1553
+ collateralToken0: stringValue(record.collateralToken0, `${label}.collateralToken0`),
1554
+ collateralToken1: stringValue(record.collateralToken1, `${label}.collateralToken1`)
1555
+ };
1556
+ }
1557
+ function poolInfoArrayArg(args, fieldName) {
1558
+ return arrayValue(args[fieldName], `args.${fieldName}`).map(
1559
+ (item, index) => poolInfoValue(item, `args.${fieldName}[${index}]`)
1560
+ );
1561
+ }
1562
+ function poolInfoValue(value, label) {
1563
+ const record = recordValue(value, label);
1564
+ return {
1565
+ pool: stringValue(record.pool, `${label}.pool`),
1566
+ token0: stringValue(record.token0, `${label}.token0`),
1567
+ token1: stringValue(record.token1, `${label}.token1`),
1568
+ maxPriceDeviation: numberValue(record.maxPriceDeviation, `${label}.maxPriceDeviation`)
1569
+ };
1570
+ }
1571
+ function poolMetadataValue(value, label) {
1572
+ const record = recordValue(value, label);
1573
+ return {
1574
+ poolKeyBytes: stringValue(record.poolKeyBytes, `${label}.poolKeyBytes`),
1575
+ poolId: decimalValue(record.poolId, `${label}.poolId`),
1576
+ collateralToken0Address: stringValue(record.collateralToken0Address, `${label}.collateralToken0Address`),
1577
+ collateralToken1Address: stringValue(record.collateralToken1Address, `${label}.collateralToken1Address`),
1578
+ riskEngineAddress: stringValue(record.riskEngineAddress, `${label}.riskEngineAddress`),
1579
+ token0Asset: stringValue(record.token0Asset, `${label}.token0Asset`),
1580
+ token1Asset: stringValue(record.token1Asset, `${label}.token1Asset`),
1581
+ token0Symbol: stringValue(record.token0Symbol, `${label}.token0Symbol`),
1582
+ token1Symbol: stringValue(record.token1Symbol, `${label}.token1Symbol`),
1583
+ token0Decimals: decimalValue(record.token0Decimals, `${label}.token0Decimals`),
1584
+ token1Decimals: decimalValue(record.token1Decimals, `${label}.token1Decimals`),
1585
+ token0Name: stringValue(record.token0Name, `${label}.token0Name`),
1586
+ token1Name: stringValue(record.token1Name, `${label}.token1Name`),
1587
+ underlyingPoolId: stringValue(record.underlyingPoolId, `${label}.underlyingPoolId`),
1588
+ isV4: booleanValue(record.isV4, `${label}.isV4`),
1589
+ tickSpacing: decimalValue(record.tickSpacing, `${label}.tickSpacing`),
1590
+ fee: decimalValue(record.fee, `${label}.fee`),
1591
+ sfpmAddress: stringValue(record.sfpmAddress, `${label}.sfpmAddress`)
1592
+ };
1593
+ }
1594
+ function tokenIdLegArrayArg(args, fieldName) {
1595
+ return arrayValue(args[fieldName], `args.${fieldName}`).map(
1596
+ (item, index) => tokenIdLegValue(item, `args.${fieldName}[${index}]`)
1597
+ );
1598
+ }
1599
+ function tokenIdLegValue(value, label) {
1600
+ const record = recordValue(value, label);
1601
+ return {
1602
+ index: decimalValue(record.index, `${label}.index`),
1603
+ asset: decimalValue(record.asset, `${label}.asset`),
1604
+ optionRatio: decimalValue(record.optionRatio, `${label}.optionRatio`),
1605
+ isLong: booleanValue(record.isLong, `${label}.isLong`),
1606
+ tokenType: decimalValue(record.tokenType, `${label}.tokenType`),
1607
+ riskPartner: decimalValue(record.riskPartner, `${label}.riskPartner`),
1608
+ strike: signedDecimalValue(record.strike, `${label}.strike`),
1609
+ width: decimalValue(record.width, `${label}.width`),
1610
+ tickLower: signedDecimalValue(record.tickLower, `${label}.tickLower`),
1611
+ tickUpper: signedDecimalValue(record.tickUpper, `${label}.tickUpper`)
1612
+ };
1613
+ }
1614
+ function storedPositionArrayArg(args, fieldName) {
1615
+ return arrayValue(args[fieldName], `args.${fieldName}`).map(
1616
+ (item, index) => storedPositionValue(item, `args.${fieldName}[${index}]`)
1617
+ );
1618
+ }
1619
+ function storedPositionValue(value, label) {
1620
+ const record = recordValue(value, label);
1621
+ return {
1622
+ tokenId: decimalValue(record.tokenId, `${label}.tokenId`),
1623
+ legs: arrayValue(record.legs, `${label}.legs`).map((leg, index) => tokenIdLegValue(leg, `${label}.legs[${index}]`)),
1624
+ tickAtMint: signedDecimalValue(record.tickAtMint, `${label}.tickAtMint`),
1625
+ positionSize: decimalValue(record.positionSize, `${label}.positionSize`)
1626
+ };
1627
+ }
1628
+ function vaultCandidatesByPoolArrayArg(args, fieldName) {
1629
+ return arrayValue(args[fieldName], `args.${fieldName}`).map(
1630
+ (item, index) => vaultCandidatesByPoolValue(item, `args.${fieldName}[${index}]`)
1631
+ );
1632
+ }
1633
+ function vaultCandidatesByPoolValue(value, label) {
1634
+ const record = recordValue(value, label);
1635
+ return {
1636
+ poolAddress: stringValue(record.poolAddress, `${label}.poolAddress`),
1637
+ candidates: decimalArrayValue(record.candidates, `${label}.candidates`)
1638
+ };
1639
+ }
1640
+ function uniswapAddressesValue(value, label) {
1641
+ const record = recordValue(value, label);
1642
+ return {
1643
+ universalRouter: stringValue(record.universalRouter, `${label}.universalRouter`),
1644
+ v4Quoter: stringValue(record.v4Quoter, `${label}.v4Quoter`),
1645
+ poolManager: stringValue(record.poolManager, `${label}.poolManager`),
1646
+ permit2: stringValue(record.permit2, `${label}.permit2`)
1647
+ };
1648
+ }
1649
+
1650
+ // src/internal/panopticScalars.ts
1651
+ var UINT48_MAX = (BigInt(1) << BigInt(48)) - BigInt(1);
1652
+ var UINT128_MAX = (BigInt(1) << BigInt(128)) - BigInt(1);
1653
+ var UINT160_MAX = (BigInt(1) << BigInt(160)) - BigInt(1);
1654
+ var UINT256_MAX = (BigInt(1) << BigInt(256)) - BigInt(1);
1655
+ var INT24_MIN = -(BigInt(1) << BigInt(23));
1656
+ var INT24_MAX = (BigInt(1) << BigInt(23)) - BigInt(1);
1657
+ function uint48Arg(args, fieldName) {
1658
+ return unsignedDecimalValue(args[fieldName], `args.${fieldName}`, UINT48_MAX, "uint48");
1659
+ }
1660
+ function uint128Arg(args, fieldName) {
1661
+ return unsignedDecimalValue(args[fieldName], `args.${fieldName}`, UINT128_MAX, "uint128");
1662
+ }
1663
+ function uint160Arg(args, fieldName) {
1664
+ return unsignedDecimalValue(args[fieldName], `args.${fieldName}`, UINT160_MAX, "uint160");
1665
+ }
1666
+ function uint256Arg(args, fieldName) {
1667
+ return unsignedDecimalValue(args[fieldName], `args.${fieldName}`, UINT256_MAX, "uint256");
1668
+ }
1669
+ function optionalUint256Arg(args, fieldName) {
1670
+ return args[fieldName] === void 0 ? void 0 : unsignedDecimalValue(args[fieldName], `args.${fieldName}`, UINT256_MAX, "uint256");
1671
+ }
1672
+ function uint256ArrayArg(args, fieldName) {
1673
+ const value = args[fieldName];
1674
+ if (!Array.isArray(value)) {
1675
+ throw new Error(`Panoptic args.${fieldName} must be an array.`);
1676
+ }
1677
+ return value.map((item, index) => unsignedDecimalValue(item, `args.${fieldName}[${index}]`, UINT256_MAX, "uint256"));
1678
+ }
1679
+ function int24Arg(args, fieldName) {
1680
+ return signedDecimalValue2(args[fieldName], `args.${fieldName}`, INT24_MIN, INT24_MAX, "int24");
1681
+ }
1682
+ function optionalInt24Arg(args, fieldName) {
1683
+ return args[fieldName] === void 0 ? void 0 : signedDecimalValue2(args[fieldName], `args.${fieldName}`, INT24_MIN, INT24_MAX, "int24");
1684
+ }
1685
+ function unsignedDecimalValue(value, label, maxValue, rangeLabel) {
1686
+ if (typeof value !== "string" || !/^(0|[1-9][0-9]*)$/.test(value)) {
1687
+ throw new Error(`Panoptic ${label} must be an unsigned decimal string.`);
1688
+ }
1689
+ const parsed = BigInt(value);
1690
+ if (parsed > maxValue) {
1691
+ throw new Error(`Panoptic ${label} exceeds ${rangeLabel} range.`);
1692
+ }
1693
+ return parsed;
1694
+ }
1695
+ function signedDecimalValue2(value, label, minValue, maxValue, rangeLabel) {
1696
+ if (typeof value !== "string" || !/^-?(0|[1-9][0-9]*)$/.test(value)) {
1697
+ throw new Error(`Panoptic ${label} must be a signed decimal string.`);
1698
+ }
1699
+ const parsed = BigInt(value);
1700
+ if (parsed < minValue || parsed > maxValue) {
1701
+ throw new Error(`Panoptic ${label} exceeds ${rangeLabel} range.`);
1702
+ }
1703
+ return parsed;
1704
+ }
1705
+
1706
+ // src/internal/panoptic/support.ts
1707
+ function rejectContext(request, method) {
1708
+ if (request.context !== void 0) {
1709
+ throw new Error(`Panoptic ${method} is a pure method and does not accept runtime context.`);
1710
+ }
1711
+ }
1712
+ function requireSourceContext(request, method) {
1713
+ if (request.context) {
1714
+ rejectExtraContextKeys(request, method);
1715
+ }
1716
+ if (!request.context?.sourceId && !request.context?.chainId) {
1717
+ throw new Error(`Panoptic ${method} requires context.sourceId or context.chainId.`);
1718
+ }
1719
+ }
1720
+ function rejectExtraContextKeys(request, method) {
1721
+ const context = request.context;
1722
+ if (!context) {
1723
+ return;
1724
+ }
1725
+ const allowed = /* @__PURE__ */ new Set(["chainId", "sourceId", "blockNumber", "account", "panopticSubgraphId", "rpcUrl"]);
1726
+ for (const key of Object.keys(context)) {
1727
+ if (!allowed.has(key)) {
1728
+ throw new Error(`Panoptic ${method} context.${key} is not supported by the schema.`);
1729
+ }
1730
+ }
1731
+ }
1732
+ function rejectExtraKeys(args, allowedKeys, method) {
1733
+ const allowed = new Set(allowedKeys);
1734
+ for (const key of Object.keys(args)) {
1735
+ if (!allowed.has(key)) {
1736
+ throw new Error(`Panoptic ${method} args.${key} is not supported by the schema.`);
1737
+ }
1738
+ }
1739
+ }
1740
+ function requireString(value, label) {
1741
+ if (typeof value !== "string") {
1742
+ throw new Error(`Panoptic ${label} must be a string.`);
1743
+ }
1744
+ return value;
1745
+ }
1746
+ function requirePlainResult(value, label) {
1747
+ if (!isRecord4(value)) {
1748
+ throw new Error(`Panoptic ${label} must be an object.`);
1749
+ }
1750
+ const prototype = Object.getPrototypeOf(value);
1751
+ if (prototype !== Object.prototype && prototype !== null) {
1752
+ throw new Error(`Panoptic ${label} must be a plain object.`);
1753
+ }
1754
+ return value;
1755
+ }
1756
+ function requireSdkFunction(sdkModule, name, label) {
1757
+ const defaultExport = isRecord4(sdkModule.default) ? sdkModule.default : void 0;
1758
+ const sdkExport = sdkModule[name] ?? defaultExport?.[name];
1759
+ if (typeof sdkExport !== "function") {
1760
+ throw new Error(`Panoptic runtime dependency "${label}" does not provide ${name}.`);
1761
+ }
1762
+ return sdkExport;
1763
+ }
1764
+ async function prepareRuntimeSourceContext(deps, request, options) {
1765
+ return preparePanopticSourceContext(
1766
+ request,
1767
+ await deps.viem(),
1768
+ options.sourceRegistry,
1769
+ options.operation,
1770
+ options.clientCache
1771
+ );
1772
+ }
1773
+ function withSource(value, sourceContext, blockNumberRole, label, blockNumber, reconciled) {
1774
+ const projectedValue = omitSdkMeta(requirePlainResult(value, label));
1775
+ const sourceMeta = buildMethodSourceMeta(sourceContext, blockNumberRole, blockNumber, reconciled);
1776
+ return {
1777
+ ...projectedValue,
1778
+ source: sourceMeta
1779
+ };
1780
+ }
1781
+ function isRecord4(value) {
1782
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1783
+ }
1784
+ function omitSdkMeta(value) {
1785
+ const { _meta: _ignored, ...publicValue } = value;
1786
+ void _ignored;
1787
+ return publicValue;
1788
+ }
1789
+ function buildMethodSourceMeta(sourceContext, blockNumberRole, blockNumber, reconciled) {
1790
+ const { blockNumber: preparedBlockNumber, ...baseMeta } = sourceContext.sourceMeta;
1791
+ const sourceBlockNumber = blockNumber || preparedBlockNumber;
1792
+ return {
1793
+ ...baseMeta,
1794
+ ...blockNumberRole === "preflight" ? { preflightBlockNumber: sourceBlockNumber } : { blockNumber: sourceBlockNumber },
1795
+ blockNumberRole,
1796
+ ...reconciled === void 0 ? {} : { reconciled }
1797
+ };
1798
+ }
1799
+
1800
+ // src/internal/panoptic/reads/account.ts
1801
+ async function getPosition({
1802
+ deps,
1803
+ method,
1804
+ request,
1805
+ options
1806
+ }) {
1807
+ const input = parseTokenIdRequest(request, method);
1808
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
1809
+ const sdkGetPosition = await loadSdkV2Function(deps, "getPosition");
1810
+ return withSource(
1811
+ await sdkGetPosition({
1812
+ ...ownerReadParams(sourceContext, input.account),
1813
+ poolAddress: input.poolAddress,
1814
+ tokenId: input.tokenId
1815
+ }),
1816
+ sourceContext,
1817
+ "pinned",
1818
+ `${method} result`
1819
+ );
1820
+ }
1821
+ async function getPositions({
1822
+ deps,
1823
+ method,
1824
+ request,
1825
+ options
1826
+ }) {
1827
+ const input = parseTokenIdsRequest(request, method);
1828
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
1829
+ const sdkGetPositions = await loadSdkV2Function(deps, "getPositions");
1830
+ return withSource(
1831
+ await sdkGetPositions({
1832
+ ...ownerReadParams(sourceContext, input.account),
1833
+ poolAddress: input.poolAddress,
1834
+ tokenIds: input.tokenIds
1835
+ }),
1836
+ sourceContext,
1837
+ "pinned",
1838
+ `${method} result`
1839
+ );
1840
+ }
1841
+ async function getOpenPositionIds({
1842
+ deps,
1843
+ method,
1844
+ request,
1845
+ options
1846
+ }) {
1847
+ const input = parseOpenPositionIdsRequest(request, method);
1848
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
1849
+ const sdkGetOpenPositionIds = await loadSdkV2Function(deps, "getOpenPositionIds");
1850
+ const tokenIds = await sdkGetOpenPositionIds({
1851
+ client: sourceContext.client,
1852
+ chainId: BigInt(sourceContext.source.chainId),
1853
+ poolAddress: input.poolAddress,
1854
+ account: input.account,
1855
+ lastDispatchTxHash: input.lastDispatchTxHash
1856
+ });
1857
+ return withSource({ tokenIds }, sourceContext, "preflight", `${method} result`, void 0, false);
1858
+ }
1859
+ async function getAccountCollateral({
1860
+ deps,
1861
+ method,
1862
+ request,
1863
+ options
1864
+ }) {
1865
+ const input = parseAccountCollateralRequest(request, method);
1866
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
1867
+ const sdkGetAccountCollateral = await loadSdkV2Function(deps, "getAccountCollateral");
1868
+ return withSource(
1869
+ await sdkGetAccountCollateral({
1870
+ ...accountReadParams(sourceContext, input.account),
1871
+ poolAddress: input.poolAddress,
1872
+ collateralAddresses: input.collateralAddresses
1873
+ }),
1874
+ sourceContext,
1875
+ "pinned",
1876
+ `${method} result`
1877
+ );
1878
+ }
1879
+ async function getAccountSummaryBasic({
1880
+ deps,
1881
+ method,
1882
+ request,
1883
+ options
1884
+ }) {
1885
+ const input = parseAccountSummaryBasicRequest(request, method);
1886
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
1887
+ const sdkGetAccountSummaryBasic = await loadSdkV2Function(deps, "getAccountSummaryBasic");
1888
+ return withSource(
1889
+ await sdkGetAccountSummaryBasic({
1890
+ ...accountReadParams(sourceContext, input.account, true),
1891
+ poolAddress: input.poolAddress,
1892
+ tokenIds: input.tokenIds,
1893
+ poolMetadata: input.poolMetadata
1894
+ }),
1895
+ sourceContext,
1896
+ "pinned",
1897
+ `${method} result`
1898
+ );
1899
+ }
1900
+ async function getAccountSummaryRisk({
1901
+ deps,
1902
+ method,
1903
+ request,
1904
+ options
1905
+ }) {
1906
+ const input = parseAccountSummaryRiskRequest(request, method);
1907
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
1908
+ const sdkGetAccountSummaryRisk = await loadSdkV2Function(deps, "getAccountSummaryRisk");
1909
+ return withSource(
1910
+ await sdkGetAccountSummaryRisk({
1911
+ ...accountReadParams(sourceContext, input.account, true),
1912
+ poolAddress: input.poolAddress,
1913
+ tokenIds: input.tokenIds,
1914
+ queryAddress: input.queryAddress,
1915
+ atTick: input.atTick,
1916
+ includePendingPremium: input.includePendingPremium,
1917
+ poolMetadata: input.poolMetadata
1918
+ }),
1919
+ sourceContext,
1920
+ "pinned",
1921
+ `${method} result`
1922
+ );
1923
+ }
1924
+ async function getNetLiquidationValue({
1925
+ deps,
1926
+ method,
1927
+ request,
1928
+ options
1929
+ }) {
1930
+ const input = parseNetLiquidationValueRequest(request, method);
1931
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
1932
+ const sdkGetNetLiquidationValue = await loadSdkV2Function(deps, "getNetLiquidationValue");
1933
+ return withSource(
1934
+ await sdkGetNetLiquidationValue({
1935
+ ...accountReadParams(sourceContext, input.account),
1936
+ poolAddress: input.poolAddress,
1937
+ tokenIds: input.tokenIds,
1938
+ queryAddress: input.queryAddress,
1939
+ atTick: input.atTick,
1940
+ includePendingPremium: input.includePendingPremium
1941
+ }),
1942
+ sourceContext,
1943
+ "pinned",
1944
+ `${method} result`
1945
+ );
1946
+ }
1947
+ async function getNetLiquidationValues({
1948
+ deps,
1949
+ method,
1950
+ request,
1951
+ options
1952
+ }) {
1953
+ const input = parseNetLiquidationValuesRequest(request, method);
1954
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
1955
+ const sdkGetNetLiquidationValues = await loadSdkV2Function(deps, "getNetLiquidationValues");
1956
+ return withSource(
1957
+ await sdkGetNetLiquidationValues({
1958
+ ...accountReadParams(sourceContext, input.account),
1959
+ poolAddress: input.poolAddress,
1960
+ tokenIds: input.tokenIds,
1961
+ queryAddress: input.queryAddress,
1962
+ atTicks: input.atTicks,
1963
+ includePendingPremium: input.includePendingPremium
1964
+ }),
1965
+ sourceContext,
1966
+ "pinned",
1967
+ `${method} result`
1968
+ );
1969
+ }
1970
+ async function getLiquidationPrices({
1971
+ deps,
1972
+ method,
1973
+ request,
1974
+ options
1975
+ }) {
1976
+ const input = parseLiquidationPricesRequest(request, method);
1977
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
1978
+ const sdkGetLiquidationPrices = await loadSdkV2Function(deps, "getLiquidationPrices");
1979
+ return withSource(
1980
+ await sdkGetLiquidationPrices({
1981
+ ...accountReadParams(sourceContext, input.account),
1982
+ poolAddress: input.poolAddress,
1983
+ tokenIds: input.tokenIds,
1984
+ queryAddress: input.queryAddress
1985
+ }),
1986
+ sourceContext,
1987
+ "pinned",
1988
+ `${method} result`
1989
+ );
1990
+ }
1991
+ function parseTokenIdRequest(request, method) {
1992
+ const { account, args } = accountArgs(request, method, ["poolAddress", "tokenId"]);
1993
+ return { account, poolAddress: poolAddress(args.poolAddress, method), tokenId: uint256Arg(args, "tokenId") };
1994
+ }
1995
+ function parseTokenIdsRequest(request, method) {
1996
+ const { account, args } = accountArgs(request, method, ["poolAddress", "tokenIds"]);
1997
+ return { account, poolAddress: poolAddress(args.poolAddress, method), tokenIds: uint256ArrayArg(args, "tokenIds") };
1998
+ }
1999
+ function parseOpenPositionIdsRequest(request, method) {
2000
+ rejectLatestOnlyBlockNumber(request, method);
2001
+ const { account, args } = accountArgs(request, method, ["poolAddress", "lastDispatchTxHash"]);
2002
+ return {
2003
+ account,
2004
+ poolAddress: poolAddress(args.poolAddress, method),
2005
+ lastDispatchTxHash: normalizePanopticHex(
2006
+ requireArgString(args, "lastDispatchTxHash", method),
2007
+ `${method} args.lastDispatchTxHash`
2008
+ )
2009
+ };
2010
+ }
2011
+ function parseAccountCollateralRequest(request, method) {
2012
+ const { account, args } = accountArgs(request, method, ["poolAddress", "collateralAddresses"]);
2013
+ return {
2014
+ account,
2015
+ poolAddress: poolAddress(args.poolAddress, method),
2016
+ ...args.collateralAddresses === void 0 ? {} : {
2017
+ collateralAddresses: collateralAddressesValue(args.collateralAddresses, `${method} args.collateralAddresses`)
2018
+ }
2019
+ };
2020
+ }
2021
+ function parseAccountSummaryBasicRequest(request, method) {
2022
+ const { account, args } = accountArgs(request, method, ["poolAddress", "tokenIds", "poolMetadata"]);
2023
+ return {
2024
+ account,
2025
+ poolAddress: poolAddress(args.poolAddress, method),
2026
+ tokenIds: uint256ArrayArg(args, "tokenIds"),
2027
+ ...args.poolMetadata === void 0 ? {} : { poolMetadata: poolMetadataValue(args.poolMetadata, `${method} args.poolMetadata`) }
2028
+ };
2029
+ }
2030
+ function parseAccountSummaryRiskRequest(request, method) {
2031
+ const { account, args } = accountArgs(request, method, [
2032
+ "poolAddress",
2033
+ "tokenIds",
2034
+ "queryAddress",
2035
+ "atTick",
2036
+ "includePendingPremium",
2037
+ "poolMetadata"
2038
+ ]);
2039
+ return {
2040
+ account,
2041
+ poolAddress: poolAddress(args.poolAddress, method),
2042
+ tokenIds: uint256ArrayArg(args, "tokenIds"),
2043
+ queryAddress: normalizePanopticAddress(args.queryAddress, `${method} args.queryAddress`),
2044
+ atTick: optionalSignedDecimalArg(args, "atTick"),
2045
+ includePendingPremium: optionalBooleanArg(args, "includePendingPremium"),
2046
+ ...args.poolMetadata === void 0 ? {} : { poolMetadata: poolMetadataValue(args.poolMetadata, `${method} args.poolMetadata`) }
2047
+ };
2048
+ }
2049
+ function parseNetLiquidationValueRequest(request, method) {
2050
+ const { account, args } = accountArgs(request, method, [
2051
+ "poolAddress",
2052
+ "tokenIds",
2053
+ "queryAddress",
2054
+ "atTick",
2055
+ "includePendingPremium"
2056
+ ]);
2057
+ return {
2058
+ account,
2059
+ poolAddress: poolAddress(args.poolAddress, method),
2060
+ tokenIds: uint256ArrayArg(args, "tokenIds"),
2061
+ queryAddress: normalizePanopticAddress(args.queryAddress, `${method} args.queryAddress`),
2062
+ atTick: optionalSignedDecimalArg(args, "atTick"),
2063
+ includePendingPremium: optionalBooleanArg(args, "includePendingPremium")
2064
+ };
2065
+ }
2066
+ function parseNetLiquidationValuesRequest(request, method) {
2067
+ const { account, args } = accountArgs(request, method, [
2068
+ "poolAddress",
2069
+ "tokenIds",
2070
+ "queryAddress",
2071
+ "atTicks",
2072
+ "includePendingPremium"
2073
+ ]);
2074
+ return {
2075
+ account,
2076
+ poolAddress: poolAddress(args.poolAddress, method),
2077
+ tokenIds: uint256ArrayArg(args, "tokenIds"),
2078
+ queryAddress: normalizePanopticAddress(args.queryAddress, `${method} args.queryAddress`),
2079
+ atTicks: signedDecimalArrayArg(args, "atTicks"),
2080
+ includePendingPremium: optionalBooleanArg(args, "includePendingPremium")
2081
+ };
2082
+ }
2083
+ function parseLiquidationPricesRequest(request, method) {
2084
+ const { account, args } = accountArgs(request, method, ["poolAddress", "tokenIds", "queryAddress"]);
2085
+ return {
2086
+ account,
2087
+ poolAddress: poolAddress(args.poolAddress, method),
2088
+ tokenIds: uint256ArrayArg(args, "tokenIds"),
2089
+ queryAddress: normalizePanopticAddress(args.queryAddress, `${method} args.queryAddress`)
2090
+ };
2091
+ }
2092
+ function accountArgs(request, method, allowedKeys) {
2093
+ requireSourceContext(request, method);
2094
+ const account = requireAccount(request, method);
2095
+ const args = requestArgs(request, method);
2096
+ rejectExtraKeys(args, allowedKeys, method);
2097
+ return { account, args };
2098
+ }
2099
+ function requireAccount(request, method) {
2100
+ const account = request?.context?.account;
2101
+ if (!account) {
2102
+ throw new Error(`Panoptic ${method} requires context.account.`);
2103
+ }
2104
+ return normalizePanopticAddress(account, `${method} context.account`);
2105
+ }
2106
+ function rejectLatestOnlyBlockNumber(request, method) {
2107
+ if (request.context?.blockNumber !== void 0) {
2108
+ throw new Error(`Panoptic ${method} does not accept context.blockNumber because its block policy is latestOnly.`);
2109
+ }
2110
+ }
2111
+ function ownerReadParams(sourceContext, account) {
2112
+ return { client: sourceContext.client, blockNumber: BigInt(sourceContext.blockNumber), owner: account };
2113
+ }
2114
+ function accountReadParams(sourceContext, account, includeChainId = false) {
2115
+ return {
2116
+ client: sourceContext.client,
2117
+ ...includeChainId ? { chainId: BigInt(sourceContext.source.chainId) } : {},
2118
+ blockNumber: BigInt(sourceContext.blockNumber),
2119
+ account
2120
+ };
2121
+ }
2122
+ async function loadSdkV2Function(deps, name) {
2123
+ return requireSdkFunction(await deps.sdkV2(), name, "@panoptic-eng/sdk/v2");
2124
+ }
2125
+ function poolAddress(value, method) {
2126
+ return normalizePanopticAddress(value, `${method} args.poolAddress`);
2127
+ }
2128
+ function requireArgString(args, fieldName, method) {
2129
+ const value = args[fieldName];
2130
+ if (value === void 0) {
2131
+ throw new Error(`Panoptic ${method} args.${fieldName} is required.`);
2132
+ }
2133
+ if (typeof value !== "string") {
2134
+ throw new Error(`Panoptic ${method} args.${fieldName} must be a string.`);
2135
+ }
2136
+ return value;
2137
+ }
2138
+
2139
+ // src/internal/panoptic/reads/greeks.ts
2140
+ async function getPositionGreeks({
2141
+ deps,
2142
+ method,
2143
+ request,
2144
+ options
2145
+ }) {
2146
+ const input = parseGetPositionGreeksRequest(request, method);
2147
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2148
+ const sdkGetPositionGreeks = await loadSdkFunction(deps, "getPositionGreeks");
2149
+ const rawResult = await sdkGetPositionGreeks({
2150
+ client: sourceContext.client,
2151
+ blockNumber: BigInt(sourceContext.blockNumber),
2152
+ poolAddress: input.poolAddress,
2153
+ owner: input.account,
2154
+ tokenId: input.tokenId,
2155
+ atTick: input.atTick
2156
+ });
2157
+ return withSource(rawResult, sourceContext, "pinned", "greeks.getPositionGreeks result");
2158
+ }
2159
+ async function calculatePositionGreeks({ deps, method, request }) {
2160
+ const input = parseCalculatePositionGreeksRequest(request, method);
2161
+ const sdkV2 = await deps.sdkV2();
2162
+ const sdkCalculatePositionGreeks = requireSdkFunction(sdkV2, "calculatePositionGreeks", "@panoptic-eng/sdk/v2");
2163
+ const result = await sdkCalculatePositionGreeks(input);
2164
+ if (input.swapAtMint !== void 0) {
2165
+ const calculatePositionDeltaWithSwap = requireSdkFunction(
2166
+ sdkV2,
2167
+ "calculatePositionDeltaWithSwap",
2168
+ "@panoptic-eng/sdk/v2"
2169
+ );
2170
+ const delta = await calculatePositionDeltaWithSwap(input);
2171
+ if (isRecord3(result)) {
2172
+ return { ...result, delta };
2173
+ }
2174
+ }
2175
+ return result;
2176
+ }
2177
+ async function calculateAccountGreeksPure({ deps, method, request }) {
2178
+ const input = parseCalculateAccountGreeksPureRequest(request, method);
2179
+ const sdkCalculateAccountGreeksPure = await loadSdkFunction(deps, "calculateAccountGreeksPure");
2180
+ return sdkCalculateAccountGreeksPure(input);
2181
+ }
2182
+ function parseGetPositionGreeksRequest(request, method) {
2183
+ requireSourceContext(request, method);
2184
+ const account = requireAccount2(request, method);
2185
+ const args = requestArgs(request, method);
2186
+ rejectExtraKeys(args, ["poolAddress", "tokenId", "atTick"], method);
2187
+ return {
2188
+ account,
2189
+ poolAddress: normalizePanopticAddress(args.poolAddress, `${method} args.poolAddress`),
2190
+ tokenId: uint256Arg(args, "tokenId"),
2191
+ atTick: optionalSignedDecimalArg(args, "atTick")
2192
+ };
2193
+ }
2194
+ function parseCalculatePositionGreeksRequest(request, method) {
2195
+ rejectContext(request, method);
2196
+ const args = requestArgs(request, method);
2197
+ rejectExtraKeys(
2198
+ args,
2199
+ ["legs", "currentTick", "mintTick", "positionSize", "poolTickSpacing", "assetIndex", "swapAtMint"],
2200
+ method
2201
+ );
2202
+ return {
2203
+ legs: tokenIdLegArrayArg(args, "legs"),
2204
+ currentTick: signedDecimalArg(args, "currentTick"),
2205
+ mintTick: signedDecimalArg(args, "mintTick"),
2206
+ positionSize: decimalArg(args, "positionSize"),
2207
+ poolTickSpacing: decimalArg(args, "poolTickSpacing"),
2208
+ ...args.assetIndex === void 0 ? {} : { assetIndex: optionalDecimalArg(args, "assetIndex") },
2209
+ ...args.swapAtMint === void 0 ? {} : { swapAtMint: optionalBooleanArg(args, "swapAtMint") }
2210
+ };
2211
+ }
2212
+ function parseCalculateAccountGreeksPureRequest(request, method) {
2213
+ rejectContext(request, method);
2214
+ const args = requestArgs(request, method);
2215
+ rejectExtraKeys(args, ["positions", "tickSpacing", "atTicks", "collateralAssets", "assetIndex"], method);
2216
+ return {
2217
+ positions: storedPositionArrayArg(args, "positions"),
2218
+ tickSpacing: decimalArg(args, "tickSpacing"),
2219
+ atTicks: signedDecimalArrayArg(args, "atTicks"),
2220
+ ...args.collateralAssets === void 0 ? {} : { collateralAssets: optionalDecimalArrayArg(args, "collateralAssets") },
2221
+ ...args.assetIndex === void 0 ? {} : { assetIndex: optionalDecimalArg(args, "assetIndex") }
2222
+ };
2223
+ }
2224
+ async function loadSdkFunction(deps, name) {
2225
+ return requireSdkFunction(await deps.sdkV2(), name, "@panoptic-eng/sdk/v2");
2226
+ }
2227
+ function requireAccount2(request, method) {
2228
+ const account = request.context?.account;
2229
+ if (!account) {
2230
+ throw new Error(`Panoptic ${method} requires context.account.`);
2231
+ }
2232
+ return normalizePanopticAddress(account, `${method} context.account`);
2233
+ }
2234
+
2235
+ // src/internal/panoptic/reads/hypovault.ts
2236
+ async function buildVaultManagerInputAtBlock({
2237
+ deps,
2238
+ method,
2239
+ request,
2240
+ options
2241
+ }) {
2242
+ const input = parseBuildVaultManagerInputAtBlockRequest(request, method);
2243
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2244
+ const sdkBuildManagerInputAtBlock = requireSdkFunction(
2245
+ await deps.sdk(),
2246
+ "buildManagerInputAtBlock",
2247
+ "@panoptic-eng/sdk"
2248
+ );
2249
+ const managerInput = await sdkBuildManagerInputAtBlock({
2250
+ viemClient: sourceContext.client,
2251
+ poolInfos: input.poolInfos,
2252
+ tokenIds: input.tokenIds,
2253
+ underlyingToken: input.underlyingToken,
2254
+ wethAddress: input.wethAddress,
2255
+ blockNumber: BigInt(sourceContext.blockNumber),
2256
+ erc4626Vaults: input.erc4626Vaults
2257
+ });
2258
+ return withSource({ managerInput }, sourceContext, "pinned", "hypovault.buildVaultManagerInputAtBlock result");
2259
+ }
2260
+ async function verifyVaultOpenTokenIdsAtBlock({
2261
+ deps,
2262
+ method,
2263
+ request,
2264
+ options
2265
+ }) {
2266
+ const input = parseVerifyVaultOpenTokenIdsAtBlockRequest(request, method);
2267
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2268
+ const sdkVerifyVaultOpenTokenIdsAtBlock = requireSdkFunction(
2269
+ await deps.sdk(),
2270
+ "verifyVaultOpenTokenIdsAtBlock",
2271
+ "@panoptic-eng/sdk"
2272
+ );
2273
+ const tokenIdsByPool = await sdkVerifyVaultOpenTokenIdsAtBlock({
2274
+ viemClient: sourceContext.client,
2275
+ vaultAddress: input.vaultAddress,
2276
+ candidatesByPool: input.candidatesByPool,
2277
+ blockNumber: BigInt(sourceContext.blockNumber)
2278
+ });
2279
+ return withSource({ tokenIdsByPool }, sourceContext, "pinned", "hypovault.verifyVaultOpenTokenIdsAtBlock result");
2280
+ }
2281
+ async function getOpenPositionIds2({
2282
+ deps,
2283
+ method,
2284
+ request,
2285
+ options
2286
+ }) {
2287
+ const input = parseGetOpenPositionIdsRequest(request, method);
2288
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2289
+ const sdkGetOpenPositionIds = requireSdkFunction(await deps.sdkV2(), "getOpenPositionIds", "@panoptic-eng/sdk/v2");
2290
+ const tokenIds = await sdkGetOpenPositionIds({
2291
+ client: sourceContext.client,
2292
+ chainId: BigInt(sourceContext.source.chainId),
2293
+ poolAddress: input.poolAddress,
2294
+ account: input.account,
2295
+ lastDispatchTxHash: input.lastDispatchTxHash
2296
+ });
2297
+ return withSource({ tokenIds }, sourceContext, "preflight", "hypovault.getOpenPositionIds result", void 0, false);
2298
+ }
2299
+ async function getEpochContext({
2300
+ deps,
2301
+ method,
2302
+ request,
2303
+ options
2304
+ }) {
2305
+ const input = parseGetEpochContextRequest(request, method);
2306
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2307
+ const readContract = readContractFunction(sourceContext.client, method);
2308
+ const [depositEpoch, withdrawalEpoch, totalSupply] = await Promise.all([
2309
+ readContract({
2310
+ address: input.vaultAddress,
2311
+ abi: HYPOVAULT_READ_ABI,
2312
+ functionName: "depositEpoch",
2313
+ args: [],
2314
+ blockNumber: BigInt(sourceContext.blockNumber)
2315
+ }),
2316
+ readContract({
2317
+ address: input.vaultAddress,
2318
+ abi: HYPOVAULT_READ_ABI,
2319
+ functionName: "withdrawalEpoch",
2320
+ args: [],
2321
+ blockNumber: BigInt(sourceContext.blockNumber)
2322
+ }),
2323
+ readContract({
2324
+ address: input.vaultAddress,
2325
+ abi: HYPOVAULT_READ_ABI,
2326
+ functionName: "totalSupply",
2327
+ args: [],
2328
+ blockNumber: BigInt(sourceContext.blockNumber)
2329
+ })
2330
+ ]);
2331
+ const depositEpochNumber = toBigInt(depositEpoch, `${method} depositEpoch`);
2332
+ const withdrawalEpochNumber = toBigInt(withdrawalEpoch, `${method} withdrawalEpoch`);
2333
+ const [depositState, withdrawalState, queuedDeposit, queuedWithdrawal, block] = await Promise.all([
2334
+ readContract({
2335
+ address: input.vaultAddress,
2336
+ abi: HYPOVAULT_READ_ABI,
2337
+ functionName: "depositEpochState",
2338
+ args: [depositEpochNumber],
2339
+ blockNumber: BigInt(sourceContext.blockNumber)
2340
+ }),
2341
+ readContract({
2342
+ address: input.vaultAddress,
2343
+ abi: HYPOVAULT_READ_ABI,
2344
+ functionName: "withdrawalEpochState",
2345
+ args: [withdrawalEpochNumber],
2346
+ blockNumber: BigInt(sourceContext.blockNumber)
2347
+ }),
2348
+ input.account ? readContract({
2349
+ address: input.vaultAddress,
2350
+ abi: HYPOVAULT_READ_ABI,
2351
+ functionName: "queuedDeposit",
2352
+ args: [input.account, depositEpochNumber],
2353
+ blockNumber: BigInt(sourceContext.blockNumber)
2354
+ }) : void 0,
2355
+ input.account ? readContract({
2356
+ address: input.vaultAddress,
2357
+ abi: HYPOVAULT_READ_ABI,
2358
+ functionName: "queuedWithdrawal",
2359
+ args: [input.account, withdrawalEpochNumber],
2360
+ blockNumber: BigInt(sourceContext.blockNumber)
2361
+ }) : void 0,
2362
+ getBlockIfAvailable(sourceContext.client, sourceContext.blockNumber)
2363
+ ]);
2364
+ const deposit = depositEpochState(depositState, method);
2365
+ const withdrawal = withdrawalEpochState(withdrawalState, method);
2366
+ return withSource(
2367
+ {
2368
+ vaultAddress: input.vaultAddress,
2369
+ ...input.account === void 0 ? {} : { account: input.account },
2370
+ totalSupply: toBigInt(totalSupply, `${method} totalSupply`).toString(10),
2371
+ ...block?.timestamp === void 0 ? {} : { currentTimestamp: block.timestamp.toString(10) },
2372
+ deposit: {
2373
+ epoch: depositEpochNumber.toString(10),
2374
+ ...deposit,
2375
+ pendingValue: nonnegativeDifference(deposit.assetsDeposited, deposit.assetsFulfilled).toString(10),
2376
+ ...queuedDeposit === void 0 ? {} : { queuedDeposit: toBigInt(queuedDeposit, `${method} queuedDeposit`).toString(10) }
2377
+ },
2378
+ withdrawal: {
2379
+ epoch: withdrawalEpochNumber.toString(10),
2380
+ ...withdrawal,
2381
+ pendingShares: nonnegativeDifference(withdrawal.sharesWithdrawn, withdrawal.sharesFulfilled).toString(10),
2382
+ ...queuedWithdrawal === void 0 ? {} : { queuedWithdrawal: queuedWithdrawalState(queuedWithdrawal, method) }
2383
+ }
2384
+ },
2385
+ sourceContext,
2386
+ "pinned",
2387
+ "hypovault.getEpochContext result"
2388
+ );
2389
+ }
2390
+ async function getPositionsHashStatus({
2391
+ deps,
2392
+ method,
2393
+ request,
2394
+ options
2395
+ }) {
2396
+ const input = parseGetPositionsHashStatusRequest(request, method);
2397
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2398
+ const readContract = readContractFunction(sourceContext.client, method);
2399
+ const positionsHash = normalizePanopticHex(
2400
+ await readContract({
2401
+ address: input.poolAddress,
2402
+ abi: PANOPTIC_POOL_READ_ABI,
2403
+ functionName: "positionsHash",
2404
+ args: [input.account],
2405
+ blockNumber: BigInt(sourceContext.blockNumber)
2406
+ }),
2407
+ `${method} positionsHash`
2408
+ );
2409
+ const tokenIds = input.tokenIds ?? await recoverTokenIds(deps, sourceContext, input, method);
2410
+ const computedHash = tokenIds === void 0 ? void 0 : await computePositionsHash(await deps.viem(), tokenIds, method);
2411
+ return withSource(
2412
+ {
2413
+ account: input.account,
2414
+ poolAddress: input.poolAddress,
2415
+ positionsHash,
2416
+ ...tokenIds === void 0 ? {} : { tokenIds },
2417
+ ...computedHash === void 0 ? {} : { computedHash, valid: computedHash === positionsHash }
2418
+ },
2419
+ sourceContext,
2420
+ "pinned",
2421
+ "hypovault.getPositionsHashStatus result"
2422
+ );
2423
+ }
2424
+ function parseBuildVaultManagerInputAtBlockRequest(request, method) {
2425
+ requireSourceContext(request, method);
2426
+ const args = requestArgs(request, method);
2427
+ rejectExtraKeys(
2428
+ args,
2429
+ ["vaultAddress", "underlyingToken", "poolInfos", "tokenIds", "managerAddress", "wethAddress", "erc4626Vaults"],
2430
+ method
2431
+ );
2432
+ return {
2433
+ vaultAddress: normalizePanopticAddress(args.vaultAddress, `${method} args.vaultAddress`),
2434
+ underlyingToken: normalizePanopticAddress(args.underlyingToken, `${method} args.underlyingToken`),
2435
+ poolInfos: poolInfoArrayArg(args, "poolInfos"),
2436
+ tokenIds: decimalMatrixArg(args, "tokenIds"),
2437
+ ...args.wethAddress === void 0 ? {} : { wethAddress: normalizePanopticAddress(args.wethAddress, `${method} args.wethAddress`) },
2438
+ ...args.erc4626Vaults === void 0 ? {} : { erc4626Vaults: optionalStringArrayArg(args, "erc4626Vaults") }
2439
+ };
2440
+ }
2441
+ function parseVerifyVaultOpenTokenIdsAtBlockRequest(request, method) {
2442
+ requireSourceContext(request, method);
2443
+ const args = requestArgs(request, method);
2444
+ rejectExtraKeys(args, ["vaultAddress", "candidatesByPool"], method);
2445
+ return {
2446
+ vaultAddress: normalizePanopticAddress(args.vaultAddress, `${method} args.vaultAddress`),
2447
+ candidatesByPool: vaultCandidatesByPoolArrayArg(args, "candidatesByPool")
2448
+ };
2449
+ }
2450
+ function parseGetOpenPositionIdsRequest(request, method) {
2451
+ requireSourceContext(request, method);
2452
+ rejectLatestOnlyBlockNumber2(request, method);
2453
+ const account = requireAccount3(request, method);
2454
+ const args = requestArgs(request, method);
2455
+ rejectExtraKeys(args, ["poolAddress", "lastDispatchTxHash"], method);
2456
+ return {
2457
+ account,
2458
+ poolAddress: normalizePanopticAddress(args.poolAddress, `${method} args.poolAddress`),
2459
+ lastDispatchTxHash: normalizePanopticHex(
2460
+ requireArgString2(args, "lastDispatchTxHash", method),
2461
+ `${method} args.lastDispatchTxHash`
2462
+ )
2463
+ };
2464
+ }
2465
+ function parseGetEpochContextRequest(request, method) {
2466
+ requireSourceContext(request, method);
2467
+ const args = requestArgs(request, method);
2468
+ rejectExtraKeys(args, ["vaultAddress", "account"], method);
2469
+ return {
2470
+ vaultAddress: normalizePanopticAddress(args.vaultAddress, `${method} args.vaultAddress`),
2471
+ ...args.account === void 0 ? {} : { account: normalizePanopticAddress(args.account, `${method} args.account`) }
2472
+ };
2473
+ }
2474
+ function parseGetPositionsHashStatusRequest(request, method) {
2475
+ requireSourceContext(request, method);
2476
+ const args = requestArgs(request, method);
2477
+ rejectExtraKeys(args, ["poolAddress", "account", "tokenIds", "lastDispatchTxHash"], method);
2478
+ return {
2479
+ poolAddress: normalizePanopticAddress(args.poolAddress, `${method} args.poolAddress`),
2480
+ account: normalizePanopticAddress(args.account ?? request.context?.account, `${method} args.account`),
2481
+ ...args.tokenIds === void 0 ? {} : { tokenIds: decimalMatrixArg({ tokenIds: [args.tokenIds] }, "tokenIds")[0].map((id) => id.toString(10)) },
2482
+ ...args.lastDispatchTxHash === void 0 ? {} : {
2483
+ lastDispatchTxHash: normalizePanopticHex(
2484
+ requireArgString2(args, "lastDispatchTxHash", method),
2485
+ `${method} args.lastDispatchTxHash`
2486
+ )
2487
+ }
2488
+ };
2489
+ }
2490
+ function requireAccount3(request, method) {
2491
+ const account = request.context?.account;
2492
+ if (!account) {
2493
+ throw new Error(`Panoptic ${method} requires context.account.`);
2494
+ }
2495
+ return normalizePanopticAddress(account, `${method} context.account`);
2496
+ }
2497
+ function requireArgString2(args, fieldName, method) {
2498
+ const value = args[fieldName];
2499
+ if (value === void 0) {
2500
+ throw new Error(`Panoptic ${method} args.${fieldName} is required.`);
2501
+ }
2502
+ if (typeof value !== "string") {
2503
+ throw new Error(`Panoptic ${method} args.${fieldName} must be a string.`);
2504
+ }
2505
+ return value;
2506
+ }
2507
+ function rejectLatestOnlyBlockNumber2(request, method) {
2508
+ if (request.context?.blockNumber !== void 0) {
2509
+ throw new Error(`Panoptic ${method} does not accept context.blockNumber because its block policy is latestOnly.`);
2510
+ }
2511
+ }
2512
+ var HYPOVAULT_READ_ABI = [
2513
+ { type: "function", name: "depositEpoch", stateMutability: "view", inputs: [], outputs: [{ type: "uint128" }] },
2514
+ { type: "function", name: "withdrawalEpoch", stateMutability: "view", inputs: [], outputs: [{ type: "uint128" }] },
2515
+ { type: "function", name: "totalSupply", stateMutability: "view", inputs: [], outputs: [{ type: "uint256" }] },
2516
+ {
2517
+ type: "function",
2518
+ name: "depositEpochState",
2519
+ stateMutability: "view",
2520
+ inputs: [{ type: "uint256" }],
2521
+ outputs: [
2522
+ { name: "assetsDeposited", type: "uint128" },
2523
+ { name: "assetsFulfilled", type: "uint128" },
2524
+ { name: "sharesReceived", type: "uint128" }
2525
+ ]
2526
+ },
2527
+ {
2528
+ type: "function",
2529
+ name: "withdrawalEpochState",
2530
+ stateMutability: "view",
2531
+ inputs: [{ type: "uint256" }],
2532
+ outputs: [
2533
+ { name: "sharesWithdrawn", type: "uint128" },
2534
+ { name: "sharesFulfilled", type: "uint128" },
2535
+ { name: "assetsPaid", type: "uint128" }
2536
+ ]
2537
+ },
2538
+ {
2539
+ type: "function",
2540
+ name: "queuedDeposit",
2541
+ stateMutability: "view",
2542
+ inputs: [{ type: "address" }, { type: "uint256" }],
2543
+ outputs: [{ type: "uint128" }]
2544
+ },
2545
+ {
2546
+ type: "function",
2547
+ name: "queuedWithdrawal",
2548
+ stateMutability: "view",
2549
+ inputs: [{ type: "address" }, { type: "uint256" }],
2550
+ outputs: [
2551
+ { name: "amount", type: "uint128" },
2552
+ { name: "basis", type: "uint128" },
2553
+ { name: "shouldRedeposit", type: "bool" }
2554
+ ]
2555
+ }
2556
+ ];
2557
+ var PANOPTIC_POOL_READ_ABI = [
2558
+ {
2559
+ type: "function",
2560
+ name: "positionsHash",
2561
+ stateMutability: "view",
2562
+ inputs: [{ type: "address" }],
2563
+ outputs: [{ type: "bytes32" }]
2564
+ }
2565
+ ];
2566
+ function readContractFunction(client, method) {
2567
+ if (!isRecord4(client) || typeof client.readContract !== "function") {
2568
+ throw new Error(`Panoptic ${method} requires a viem public client with readContract.`);
2569
+ }
2570
+ return client.readContract;
2571
+ }
2572
+ async function getBlockIfAvailable(client, blockNumber) {
2573
+ if (!isRecord4(client) || typeof client.getBlock !== "function") {
2574
+ return void 0;
2575
+ }
2576
+ const block = await client.getBlock({
2577
+ blockNumber: BigInt(blockNumber)
2578
+ });
2579
+ if (!isRecord4(block) || block.timestamp === void 0) {
2580
+ return void 0;
2581
+ }
2582
+ return { timestamp: toBigInt(block.timestamp, "block.timestamp") };
2583
+ }
2584
+ function depositEpochState(value, method) {
2585
+ return {
2586
+ assetsDeposited: tupleBigInt(value, "assetsDeposited", 0, `${method} depositEpochState`).toString(10),
2587
+ assetsFulfilled: tupleBigInt(value, "assetsFulfilled", 1, `${method} depositEpochState`).toString(10),
2588
+ sharesReceived: tupleBigInt(value, "sharesReceived", 2, `${method} depositEpochState`).toString(10)
2589
+ };
2590
+ }
2591
+ function withdrawalEpochState(value, method) {
2592
+ return {
2593
+ sharesWithdrawn: tupleBigInt(value, "sharesWithdrawn", 0, `${method} withdrawalEpochState`).toString(10),
2594
+ sharesFulfilled: tupleBigInt(value, "sharesFulfilled", 1, `${method} withdrawalEpochState`).toString(10),
2595
+ assetsPaid: tupleBigInt(value, "assetsPaid", 2, `${method} withdrawalEpochState`).toString(10)
2596
+ };
2597
+ }
2598
+ function queuedWithdrawalState(value, method) {
2599
+ return {
2600
+ amount: tupleBigInt(value, "amount", 0, `${method} queuedWithdrawal`).toString(10),
2601
+ basis: tupleBigInt(value, "basis", 1, `${method} queuedWithdrawal`).toString(10),
2602
+ shouldRedeposit: tupleBoolean(value, "shouldRedeposit", 2, `${method} queuedWithdrawal`)
2603
+ };
2604
+ }
2605
+ function tupleBigInt(value, field, index, label) {
2606
+ if (Array.isArray(value)) {
2607
+ return toBigInt(value[index], `${label}[${index}]`);
2608
+ }
2609
+ if (isRecord4(value)) {
2610
+ return toBigInt(value[field], `${label}.${field}`);
2611
+ }
2612
+ throw new Error(`Panoptic ${label} must be a tuple-like value.`);
2613
+ }
2614
+ function tupleBoolean(value, field, index, label) {
2615
+ const raw = Array.isArray(value) ? value[index] : isRecord4(value) ? value[field] : void 0;
2616
+ if (typeof raw !== "boolean") {
2617
+ throw new Error(`Panoptic ${label}.${field} must be a boolean.`);
2618
+ }
2619
+ return raw;
2620
+ }
2621
+ function toBigInt(value, label) {
2622
+ if (typeof value === "bigint") return value;
2623
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return BigInt(value);
2624
+ if (typeof value === "string" && /^(0|[1-9][0-9]*)$/.test(value)) return BigInt(value);
2625
+ throw new Error(`Panoptic ${label} must be a uint-like value.`);
2626
+ }
2627
+ function nonnegativeDifference(left, right) {
2628
+ const difference = BigInt(left) - BigInt(right);
2629
+ return difference < BigInt(0) ? BigInt(0) : difference;
2630
+ }
2631
+ async function recoverTokenIds(deps, sourceContext, input, method) {
2632
+ if (!input.lastDispatchTxHash) return void 0;
2633
+ const sdkGetOpenPositionIds = requireSdkFunction(await deps.sdkV2(), "getOpenPositionIds", "@panoptic-eng/sdk/v2");
2634
+ const tokenIds = await sdkGetOpenPositionIds({
2635
+ client: sourceContext.client,
2636
+ chainId: BigInt(sourceContext.source.chainId),
2637
+ poolAddress: input.poolAddress,
2638
+ account: input.account,
2639
+ lastDispatchTxHash: input.lastDispatchTxHash
2640
+ });
2641
+ if (!Array.isArray(tokenIds)) {
2642
+ throw new Error(`Panoptic ${method} getOpenPositionIds result must be an array.`);
2643
+ }
2644
+ return tokenIds.map((tokenId, index) => toBigInt(tokenId, `${method} tokenIds[${index}]`).toString(10));
2645
+ }
2646
+ async function computePositionsHash(viem, tokenIds, method) {
2647
+ const keccak256 = requireSdkFunction(viem, "keccak256", "viem");
2648
+ let hash = BigInt(0);
2649
+ for (const [index, tokenId] of tokenIds.entries()) {
2650
+ const encodedTokenId = `0x${BigInt(tokenId).toString(16).padStart(64, "0")}`;
2651
+ const tokenHash = normalizePanopticHex(await keccak256(encodedTokenId), `${method} tokenIds[${index}] hash`);
2652
+ hash ^= BigInt(tokenHash);
2653
+ }
2654
+ return `0x${hash.toString(16).padStart(64, "0")}`;
2655
+ }
2656
+
2657
+ // src/internal/panoptic/reads/pool.ts
2658
+ async function getPool({
2659
+ deps,
2660
+ method,
2661
+ request,
2662
+ options
2663
+ }) {
2664
+ const input = parseGetPoolRequest(request, method);
2665
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2666
+ const sdkGetPool = await loadSdkFunction2(deps, "getPool");
2667
+ const rawResult = await sdkGetPool({
2668
+ client: sourceContext.client,
2669
+ chainId: BigInt(sourceContext.source.chainId),
2670
+ blockNumber: BigInt(sourceContext.blockNumber),
2671
+ poolAddress: input.poolAddress,
2672
+ poolMetadata: input.poolMetadata,
2673
+ stateViewAddress: input.stateViewAddress
2674
+ });
2675
+ return withSource(rawResult, sourceContext, "pinned", "pool.getPool result");
2676
+ }
2677
+ async function fetchPoolId({
2678
+ deps,
2679
+ method,
2680
+ request,
2681
+ options
2682
+ }) {
2683
+ const input = parsePoolAddressRequest(["poolAddress"])(request, method);
2684
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2685
+ const sdkFetchPoolId = await loadSdkFunction2(deps, "fetchPoolId");
2686
+ const rawResult = await sdkFetchPoolId({ client: sourceContext.client, poolAddress: input.poolAddress });
2687
+ const sdkBlockNumber = readSdkResultBlockNumber(rawResult);
2688
+ return withSource(
2689
+ rawResult,
2690
+ sourceContext,
2691
+ sdkBlockNumber ? "sdkResult" : "preflight",
2692
+ "pool.fetchPoolId result",
2693
+ sdkBlockNumber || void 0,
2694
+ sdkBlockNumber ? void 0 : false
2695
+ );
2696
+ }
2697
+ async function getPoolMetadata({
2698
+ deps,
2699
+ method,
2700
+ request,
2701
+ options
2702
+ }) {
2703
+ const input = parsePoolAddressRequest(["poolAddress"])(request, method);
2704
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2705
+ const sdkGetPoolMetadata = await loadSdkFunction2(deps, "getPoolMetadata");
2706
+ return withSource(
2707
+ await sdkGetPoolMetadata({ client: sourceContext.client, poolAddress: input.poolAddress }),
2708
+ sourceContext,
2709
+ "staticReference",
2710
+ "pool.getPoolMetadata result"
2711
+ );
2712
+ }
2713
+ async function getRiskParameters({
2714
+ deps,
2715
+ method,
2716
+ request,
2717
+ options
2718
+ }) {
2719
+ const input = parseRiskParametersRequest(request, method);
2720
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2721
+ const sdkGetRiskParameters = await loadSdkFunction2(deps, "getRiskParameters");
2722
+ return withSource(
2723
+ await sdkGetRiskParameters({
2724
+ client: sourceContext.client,
2725
+ blockNumber: BigInt(sourceContext.blockNumber),
2726
+ poolAddress: input.poolAddress,
2727
+ builderCode: input.builderCode,
2728
+ riskEngineAddress: input.riskEngineAddress
2729
+ }),
2730
+ sourceContext,
2731
+ "pinned",
2732
+ "pool.getRiskParameters result"
2733
+ );
2734
+ }
2735
+ async function getUtilization({
2736
+ deps,
2737
+ method,
2738
+ request,
2739
+ options
2740
+ }) {
2741
+ const input = parseUtilizationRequest(request, method);
2742
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2743
+ const sdkGetUtilization = await loadSdkFunction2(deps, "getUtilization");
2744
+ return withSource(
2745
+ await sdkGetUtilization({
2746
+ client: sourceContext.client,
2747
+ blockNumber: BigInt(sourceContext.blockNumber),
2748
+ poolAddress: input.poolAddress,
2749
+ collateralAddresses: input.collateralAddresses
2750
+ }),
2751
+ sourceContext,
2752
+ "pinned",
2753
+ "pool.getUtilization result"
2754
+ );
2755
+ }
2756
+ async function getOracleState({
2757
+ deps,
2758
+ method,
2759
+ request,
2760
+ options
2761
+ }) {
2762
+ const input = parsePoolAddressRequest(["poolAddress"])(request, method);
2763
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2764
+ const sdkGetOracleState = await loadSdkFunction2(deps, "getOracleState");
2765
+ return withSource(
2766
+ await sdkGetOracleState({
2767
+ client: sourceContext.client,
2768
+ blockNumber: BigInt(sourceContext.blockNumber),
2769
+ poolAddress: input.poolAddress
2770
+ }),
2771
+ sourceContext,
2772
+ "pinned",
2773
+ "pool.getOracleState result"
2774
+ );
2775
+ }
2776
+ async function getTickSpacing({ deps, method, request }) {
2777
+ const input = parseGetTickSpacingRequest(request, method);
2778
+ const sdkGetTickSpacing = await loadSdkFunction2(deps, "getTickSpacing");
2779
+ return sdkGetTickSpacing(input.feeBps);
2780
+ }
2781
+ async function getPricesAtTick({ deps, method, request }) {
2782
+ const input = parsePricesAtTickRequest(request, method);
2783
+ const sdkGetPricesAtTick = await loadSdkFunction2(deps, "getPricesAtTick");
2784
+ return sdkGetPricesAtTick(input.tick, input.decimals0, input.decimals1, input.precision);
2785
+ }
2786
+ function parseGetTickSpacingRequest(request, method) {
2787
+ rejectContext(request, method);
2788
+ const args = requestArgs(request, method);
2789
+ rejectExtraKeys(args, ["feeBps"], method);
2790
+ return { feeBps: uint256Arg(args, "feeBps") };
2791
+ }
2792
+ function parseGetPoolRequest(request, method) {
2793
+ requireSourceContext(request, method);
2794
+ const args = requestArgs(request, method);
2795
+ rejectExtraKeys(args, ["poolAddress", "poolMetadata", "stateViewAddress"], method);
2796
+ return {
2797
+ poolAddress: normalizePanopticAddress(args.poolAddress, `${method} args.poolAddress`),
2798
+ ...args.poolMetadata === void 0 ? {} : { poolMetadata: poolMetadataValue(args.poolMetadata, `${method} args.poolMetadata`) },
2799
+ ...args.stateViewAddress === void 0 ? {} : { stateViewAddress: normalizePanopticAddress(args.stateViewAddress, `${method} args.stateViewAddress`) }
2800
+ };
2801
+ }
2802
+ function parsePoolAddressRequest(allowedKeys) {
2803
+ return (request, method) => {
2804
+ requireSourceContext(request, method);
2805
+ rejectLatestOnlyBlockNumber3(request, method);
2806
+ const args = requestArgs(request, method);
2807
+ rejectExtraKeys(args, allowedKeys, method);
2808
+ return { poolAddress: normalizePanopticAddress(args.poolAddress, `${method} args.poolAddress`) };
2809
+ };
2810
+ }
2811
+ function parseRiskParametersRequest(request, method) {
2812
+ requireSourceContext(request, method);
2813
+ const args = requestArgs(request, method);
2814
+ rejectExtraKeys(args, ["poolAddress", "builderCode", "riskEngineAddress"], method);
2815
+ return {
2816
+ poolAddress: normalizePanopticAddress(args.poolAddress, `${method} args.poolAddress`),
2817
+ builderCode: optionalUint256Arg(args, "builderCode"),
2818
+ ...args.riskEngineAddress === void 0 ? {} : { riskEngineAddress: normalizePanopticAddress(args.riskEngineAddress, `${method} args.riskEngineAddress`) }
2819
+ };
2820
+ }
2821
+ function parseUtilizationRequest(request, method) {
2822
+ requireSourceContext(request, method);
2823
+ const args = requestArgs(request, method);
2824
+ rejectExtraKeys(args, ["poolAddress", "collateralAddresses"], method);
2825
+ return {
2826
+ poolAddress: normalizePanopticAddress(args.poolAddress, `${method} args.poolAddress`),
2827
+ ...args.collateralAddresses === void 0 ? {} : {
2828
+ collateralAddresses: collateralAddressesValue(args.collateralAddresses, `${method} args.collateralAddresses`)
2829
+ }
2830
+ };
2831
+ }
2832
+ function parsePricesAtTickRequest(request, method) {
2833
+ rejectContext(request, method);
2834
+ const args = requestArgs(request, method);
2835
+ rejectExtraKeys(args, ["tick", "decimals0", "decimals1", "precision"], method);
2836
+ return {
2837
+ tick: signedDecimalValue(args.tick, `${method} args.tick`),
2838
+ decimals0: uint256Arg(args, "decimals0"),
2839
+ decimals1: uint256Arg(args, "decimals1"),
2840
+ precision: uint256Arg(args, "precision")
2841
+ };
2842
+ }
2843
+ async function loadSdkFunction2(deps, name) {
2844
+ return requireSdkFunction(await deps.sdkV2(), name, "@panoptic-eng/sdk/v2");
2845
+ }
2846
+ function rejectLatestOnlyBlockNumber3(request, method) {
2847
+ if (method === "pool.fetchPoolId" && request.context?.blockNumber !== void 0) {
2848
+ throw new Error(`Panoptic ${method} does not accept context.blockNumber because its block policy is latestOnly.`);
2849
+ }
2850
+ }
2851
+ function readSdkResultBlockNumber(value) {
2852
+ if (!isRecord4(value) || !isRecord4(value._meta)) {
2853
+ return null;
2854
+ }
2855
+ return normalizeBlockNumberValue(value._meta.blockNumber);
2856
+ }
2857
+ function normalizeBlockNumberValue(value) {
2858
+ if (typeof value === "bigint") {
2859
+ return value.toString(10);
2860
+ }
2861
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) {
2862
+ return value.toString(10);
2863
+ }
2864
+ if (typeof value === "string") {
2865
+ if (/^0x[0-9a-f]+$/i.test(value)) {
2866
+ return BigInt(value).toString(10);
2867
+ }
2868
+ if (/^(0|[1-9][0-9]*)$/.test(value)) {
2869
+ return BigInt(value).toString(10);
2870
+ }
2871
+ }
2872
+ return null;
2873
+ }
2874
+
2875
+ // src/internal/panoptic/reads/uniswap.ts
2876
+ async function resolveSwapRoute({
2877
+ deps,
2878
+ method,
2879
+ request,
2880
+ options
2881
+ }) {
2882
+ const input = parseResolveSwapRouteRequest(request, method);
2883
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2884
+ const sdkResolveSwapRoute = await loadUniswapFunction(deps, "resolveSwapRoute");
2885
+ return withSource(
2886
+ await sdkResolveSwapRoute({
2887
+ ...pinnedParams(sourceContext),
2888
+ poolAddress: input.poolAddress,
2889
+ tokenIn: input.tokenIn
2890
+ }),
2891
+ sourceContext,
2892
+ "pinned",
2893
+ `${method} result`
2894
+ );
2895
+ }
2896
+ async function quoteSwapExactInViaRouter({
2897
+ deps,
2898
+ method,
2899
+ request,
2900
+ options
2901
+ }) {
2902
+ const input = parseQuoteSwapExactInRequest(request, method);
2903
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2904
+ const sdkQuoteSwapExactInViaRouter = await loadUniswapFunction(deps, "quoteSwapExactInViaRouter");
2905
+ return withSource(
2906
+ await sdkQuoteSwapExactInViaRouter({
2907
+ ...pinnedParams(sourceContext),
2908
+ poolAddress: input.poolAddress,
2909
+ tokenIn: input.tokenIn,
2910
+ amountIn: input.amountIn,
2911
+ slippageBps: input.slippageBps,
2912
+ addresses: input.addresses
2913
+ }),
2914
+ sourceContext,
2915
+ "pinned",
2916
+ `${method} result`
2917
+ );
2918
+ }
2919
+ async function quoteSwapExactOutViaRouter({
2920
+ deps,
2921
+ method,
2922
+ request,
2923
+ options
2924
+ }) {
2925
+ const input = parseQuoteSwapExactOutRequest(request, method);
2926
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2927
+ const sdkQuoteSwapExactOutViaRouter = await loadUniswapFunction(deps, "quoteSwapExactOutViaRouter");
2928
+ return withSource(
2929
+ await sdkQuoteSwapExactOutViaRouter({
2930
+ ...pinnedParams(sourceContext),
2931
+ poolAddress: input.poolAddress,
2932
+ tokenIn: input.tokenIn,
2933
+ amountOut: input.amountOut,
2934
+ slippageBps: input.slippageBps,
2935
+ addresses: input.addresses
2936
+ }),
2937
+ sourceContext,
2938
+ "pinned",
2939
+ `${method} result`
2940
+ );
2941
+ }
2942
+ async function checkRouterApproval({
2943
+ deps,
2944
+ method,
2945
+ request,
2946
+ options
2947
+ }) {
2948
+ const input = parseCheckApprovalRequest(request, method);
2949
+ const sourceContext = await prepareRuntimeSourceContext(deps, request, options);
2950
+ const sdkCheckRouterApproval = await loadUniswapFunction(deps, "checkRouterApproval");
2951
+ return withSource(
2952
+ await sdkCheckRouterApproval({
2953
+ client: sourceContext.client,
2954
+ chainId: BigInt(sourceContext.source.chainId),
2955
+ tokenIn: input.tokenIn,
2956
+ owner: input.owner,
2957
+ amount: input.amount,
2958
+ addresses: input.addresses
2959
+ }),
2960
+ sourceContext,
2961
+ "preflight",
2962
+ `${method} result`,
2963
+ void 0,
2964
+ false
2965
+ );
2966
+ }
2967
+ function parseResolveSwapRouteRequest(request, method) {
2968
+ const args = readArgs(request, method, ["poolAddress", "tokenIn"]);
2969
+ return {
2970
+ poolAddress: normalizePanopticAddress(args.poolAddress, `${method} args.poolAddress`),
2971
+ tokenIn: normalizePanopticAddress(args.tokenIn, `${method} args.tokenIn`)
2972
+ };
2973
+ }
2974
+ function parseQuoteSwapExactInRequest(request, method) {
2975
+ const args = readArgs(request, method, ["poolAddress", "tokenIn", "amountIn", "slippageBps", "addresses"]);
2976
+ return {
2977
+ poolAddress: normalizePanopticAddress(args.poolAddress, `${method} args.poolAddress`),
2978
+ tokenIn: normalizePanopticAddress(args.tokenIn, `${method} args.tokenIn`),
2979
+ amountIn: decimalArg(args, "amountIn"),
2980
+ slippageBps: decimalArg(args, "slippageBps"),
2981
+ ...args.addresses === void 0 ? {} : { addresses: uniswapAddressesValue(args.addresses, `${method} args.addresses`) }
2982
+ };
2983
+ }
2984
+ function parseQuoteSwapExactOutRequest(request, method) {
2985
+ const args = readArgs(request, method, ["poolAddress", "tokenIn", "amountOut", "slippageBps", "addresses"]);
2986
+ return {
2987
+ poolAddress: normalizePanopticAddress(args.poolAddress, `${method} args.poolAddress`),
2988
+ tokenIn: normalizePanopticAddress(args.tokenIn, `${method} args.tokenIn`),
2989
+ amountOut: decimalArg(args, "amountOut"),
2990
+ slippageBps: decimalArg(args, "slippageBps"),
2991
+ ...args.addresses === void 0 ? {} : { addresses: uniswapAddressesValue(args.addresses, `${method} args.addresses`) }
2992
+ };
2993
+ }
2994
+ function parseCheckApprovalRequest(request, method) {
2995
+ requireSourceContext(request, method);
2996
+ rejectLatestOnlyBlockNumber4(request, method);
2997
+ const args = requestArgs(request, method);
2998
+ rejectExtraKeys(args, ["tokenIn", "owner", "amount", "addresses"], method);
2999
+ return {
3000
+ tokenIn: normalizePanopticAddress(args.tokenIn, `${method} args.tokenIn`),
3001
+ owner: normalizePanopticAddress(args.owner, `${method} args.owner`),
3002
+ amount: decimalArg(args, "amount"),
3003
+ ...args.addresses === void 0 ? {} : { addresses: uniswapAddressesValue(args.addresses, `${method} args.addresses`) }
3004
+ };
3005
+ }
3006
+ function readArgs(request, method, allowedKeys) {
3007
+ requireSourceContext(request, method);
3008
+ const args = requestArgs(request, method);
3009
+ rejectExtraKeys(args, allowedKeys, method);
3010
+ return args;
3011
+ }
3012
+ function pinnedParams(sourceContext) {
3013
+ return {
3014
+ client: sourceContext.client,
3015
+ chainId: BigInt(sourceContext.source.chainId),
3016
+ blockNumber: BigInt(sourceContext.blockNumber)
3017
+ };
3018
+ }
3019
+ function rejectLatestOnlyBlockNumber4(request, method) {
3020
+ if (request.context?.blockNumber !== void 0) {
3021
+ throw new Error(`Panoptic ${method} does not accept context.blockNumber because its block policy is latestOnly.`);
3022
+ }
3023
+ }
3024
+ async function loadUniswapFunction(deps, name) {
3025
+ return requireSdkFunction(await deps.uniswap(), name, "@panoptic-eng/sdk/uniswap");
3026
+ }
3027
+
3028
+ // src/internal/panoptic/dynamicJobs/fragments.ts
3029
+ function makeDynamicJobFragment(input) {
3030
+ return validateDynamicJobFragment(input, "fragment");
3031
+ }
3032
+ function validateDynamicJobFragment(value, label) {
3033
+ if (!isRecord5(value)) {
3034
+ throw new Error(`Panoptic ${label} must be an object.`);
3035
+ }
3036
+ rejectExtraKeys2(value, ["target", "userProvidedData", "strategyProvidedData", "value"], label);
3037
+ const fragment = {
3038
+ target: normalizePanopticAddress(value.target, `${label}.target`),
3039
+ userProvidedData: normalizePanopticHex(value.userProvidedData, `${label}.userProvidedData`),
3040
+ strategyProvidedData: normalizePanopticHex(value.strategyProvidedData, `${label}.strategyProvidedData`),
3041
+ value: normalizePanopticDecimalString(value.value, `${label}.value`)
3042
+ };
3043
+ if (fragment.userProvidedData.length < 10 || (fragment.userProvidedData.length - 10) % 64 !== 0) {
3044
+ throw new Error(`Panoptic ${label}.userProvidedData must be a 4-byte selector followed by zero or more ABI words.`);
3045
+ }
3046
+ if (fragment.value !== "0") {
3047
+ throw new Error(`Panoptic ${label}.value must be 0 because DynamicJobs.executeJob does not forward native value.`);
3048
+ }
3049
+ return fragment;
3050
+ }
3051
+ function isRecord5(value) {
3052
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3053
+ }
3054
+ function rejectExtraKeys2(value, allowedKeys, label) {
3055
+ const allowed = new Set(allowedKeys);
3056
+ for (const key of Object.keys(value)) {
3057
+ if (!allowed.has(key)) {
3058
+ throw new Error(`Panoptic ${label}.${key} is not supported by DynamicJobFragment.`);
3059
+ }
3060
+ }
3061
+ }
3062
+
3063
+ // src/internal/panoptic/fragments/support.ts
3064
+ function splitCalldata(value, method, options = {}) {
3065
+ const record = isRecord6(value) ? value : void 0;
3066
+ const rawCalldata = record ? record.data : value;
3067
+ const calldata = normalizePanopticHex(rawCalldata, `${method} calldata`).toLowerCase();
3068
+ const target = record?.to === void 0 ? void 0 : normalizePanopticAddress(record.to, `${method} SDK target`);
3069
+ const staticArgWords = options.staticArgWords || 0;
3070
+ const prefixLength = 10 + staticArgWords * 64;
3071
+ if (calldata.length < 10) {
3072
+ throw new Error(`Panoptic ${method} calldata must include a selector.`);
3073
+ }
3074
+ const selector = calldata.slice(0, 10);
3075
+ const expectedSelector = options.expectedSelector?.toLowerCase();
3076
+ if (expectedSelector && selector !== expectedSelector) {
3077
+ throw new Error(
3078
+ `Panoptic ${method} calldata selector ${selector} does not match expected selector ${expectedSelector}.`
3079
+ );
3080
+ }
3081
+ if (calldata.length < prefixLength) {
3082
+ throw new Error(`Panoptic ${method} calldata must include ${staticArgWords} static argument word(s).`);
3083
+ }
3084
+ const userProvidedData = calldata.slice(0, prefixLength);
3085
+ const strategyProvidedData = `0x${calldata.slice(prefixLength)}`;
3086
+ if (options.requireStrategyData !== false && strategyProvidedData === "0x") {
3087
+ throw new Error(`Panoptic ${method} calldata must include ABI-encoded arguments.`);
3088
+ }
3089
+ return target ? { calldata, userProvidedData, strategyProvidedData, target } : { calldata, userProvidedData, strategyProvidedData };
3090
+ }
3091
+ function assertUserProvidedData(value, expected, method) {
3092
+ if (value.toLowerCase() !== expected.toLowerCase()) {
3093
+ throw new Error(`Panoptic ${method} generated calldata does not match the requested static argument prefix.`);
3094
+ }
3095
+ }
3096
+ function addressAbiWord(address) {
3097
+ return address.slice(2).toLowerCase().padStart(64, "0");
3098
+ }
3099
+ function uint256AbiWord(value) {
3100
+ if (value < BigInt(0) || value >= BigInt(1) << BigInt(256)) {
3101
+ throw new Error("Panoptic ABI uint256 value exceeds range.");
3102
+ }
3103
+ return value.toString(16).padStart(64, "0");
3104
+ }
3105
+ function isRecord6(value) {
3106
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3107
+ }
3108
+
3109
+ // src/internal/panoptic/fragments/erc20.ts
3110
+ var ERC20_APPROVE_SELECTOR = "0x095ea7b3";
3111
+ async function approveFragment({ deps, method, request, options }) {
3112
+ void options;
3113
+ const input = parseApproveRequest(request, method);
3114
+ const encodeApproveFunctionData = requireSdkFunction(
3115
+ await deps.sdk(),
3116
+ "encodeApproveFunctionData",
3117
+ "@panoptic-eng/sdk"
3118
+ );
3119
+ const calldata = await encodeApproveFunctionData({
3120
+ spender: input.spender,
3121
+ amount: input.amount
3122
+ });
3123
+ const split = splitCalldata(calldata, method, {
3124
+ expectedSelector: ERC20_APPROVE_SELECTOR,
3125
+ staticArgWords: 1
3126
+ });
3127
+ assertUserProvidedData(split.userProvidedData, `${ERC20_APPROVE_SELECTOR}${addressAbiWord(input.spender)}`, method);
3128
+ return makeDynamicJobFragment({
3129
+ target: input.token,
3130
+ userProvidedData: split.userProvidedData,
3131
+ strategyProvidedData: split.strategyProvidedData,
3132
+ value: "0"
3133
+ });
3134
+ }
3135
+ function parseApproveRequest(request, method) {
3136
+ rejectContext(request, method);
3137
+ const args = requestArgs(request, method);
3138
+ rejectExtraKeys(args, ["token", "spender", "amount"], method);
3139
+ return {
3140
+ token: normalizePanopticAddress(args.token, `${method} args.token`),
3141
+ spender: normalizePanopticAddress(args.spender, `${method} args.spender`),
3142
+ amount: uint256Arg(args, "amount")
3143
+ };
3144
+ }
3145
+
3146
+ // src/internal/panoptic/fragments/collateral.ts
3147
+ var DEPOSIT_SELECTOR = "0x6e553f65";
3148
+ var WITHDRAW_SELECTOR = "0xb460af94";
3149
+ var WITHDRAW_WITH_POSITIONS_SELECTOR = "0xe51161ba";
3150
+ var WITHDRAW_WITH_POSITIONS_ABI = [
3151
+ {
3152
+ type: "function",
3153
+ name: "withdraw",
3154
+ stateMutability: "nonpayable",
3155
+ inputs: [
3156
+ { name: "assets", type: "uint256" },
3157
+ { name: "receiver", type: "address" },
3158
+ { name: "owner", type: "address" },
3159
+ { name: "positionIdList", type: "uint256[]" },
3160
+ { name: "usePremiaAsCollateral", type: "bool" }
3161
+ ],
3162
+ outputs: [{ name: "shares", type: "uint256" }]
3163
+ }
3164
+ ];
3165
+ async function depositFragment({ deps, method, request, options }) {
3166
+ void options;
3167
+ const input = parseDepositRequest(request, method);
3168
+ const encodeDepositFunctionData = requireSdkFunction(
3169
+ await deps.sdk(),
3170
+ "encodeDepositFunctionData",
3171
+ "@panoptic-eng/sdk"
3172
+ );
3173
+ const split = splitCalldata(
3174
+ await encodeDepositFunctionData({
3175
+ assets: input.assets,
3176
+ receiver: input.receiver
3177
+ }),
3178
+ method,
3179
+ { expectedSelector: DEPOSIT_SELECTOR }
3180
+ );
3181
+ return makeDynamicJobFragment({
3182
+ target: input.collateralTracker,
3183
+ userProvidedData: split.userProvidedData,
3184
+ strategyProvidedData: split.strategyProvidedData,
3185
+ value: "0"
3186
+ });
3187
+ }
3188
+ async function withdrawFragment({ deps, method, request, options }) {
3189
+ void options;
3190
+ const input = parseWithdrawRequest(request, method);
3191
+ const encodeWithdrawFunctionData = requireSdkFunction(
3192
+ await deps.sdk(),
3193
+ "encodeWithdrawFunctionData",
3194
+ "@panoptic-eng/sdk"
3195
+ );
3196
+ const split = splitCalldata(
3197
+ await encodeWithdrawFunctionData({
3198
+ assets: input.assets,
3199
+ receiver: input.receiver,
3200
+ owner: input.owner
3201
+ }),
3202
+ method,
3203
+ { expectedSelector: WITHDRAW_SELECTOR }
3204
+ );
3205
+ return makeDynamicJobFragment({
3206
+ target: input.collateralTracker,
3207
+ userProvidedData: split.userProvidedData,
3208
+ strategyProvidedData: split.strategyProvidedData,
3209
+ value: "0"
3210
+ });
3211
+ }
3212
+ async function withdrawWithPositionsFragment({ deps, method, request, options }) {
3213
+ void options;
3214
+ const input = parseWithdrawWithPositionsRequest(request, method);
3215
+ const encodeFunctionData = requireSdkFunction(await deps.viem(), "encodeFunctionData", "viem");
3216
+ const split = splitCalldata(
3217
+ await encodeFunctionData({
3218
+ abi: WITHDRAW_WITH_POSITIONS_ABI,
3219
+ functionName: "withdraw",
3220
+ args: [input.assets, input.receiver, input.owner, input.positionIdList, input.usePremiaAsCollateral]
3221
+ }),
3222
+ method,
3223
+ { expectedSelector: WITHDRAW_WITH_POSITIONS_SELECTOR }
3224
+ );
3225
+ return makeDynamicJobFragment({
3226
+ target: input.collateralTracker,
3227
+ userProvidedData: split.userProvidedData,
3228
+ strategyProvidedData: split.strategyProvidedData,
3229
+ value: "0"
3230
+ });
3231
+ }
3232
+ function parseDepositRequest(request, method) {
3233
+ rejectContext(request, method);
3234
+ const args = requestArgs(request, method);
3235
+ rejectExtraKeys(args, ["collateralTracker", "assets", "receiver"], method);
3236
+ return {
3237
+ collateralTracker: normalizePanopticAddress(args.collateralTracker, `${method} args.collateralTracker`),
3238
+ assets: uint256Arg(args, "assets"),
3239
+ receiver: normalizePanopticAddress(args.receiver, `${method} args.receiver`)
3240
+ };
3241
+ }
3242
+ function parseWithdrawRequest(request, method) {
3243
+ rejectContext(request, method);
3244
+ const args = requestArgs(request, method);
3245
+ rejectExtraKeys(args, ["collateralTracker", "assets", "receiver", "owner"], method);
3246
+ return {
3247
+ collateralTracker: normalizePanopticAddress(args.collateralTracker, `${method} args.collateralTracker`),
3248
+ assets: uint256Arg(args, "assets"),
3249
+ receiver: normalizePanopticAddress(args.receiver, `${method} args.receiver`),
3250
+ owner: normalizePanopticAddress(args.owner, `${method} args.owner`)
3251
+ };
3252
+ }
3253
+ function parseWithdrawWithPositionsRequest(request, method) {
3254
+ const input = parseWithdrawWithPositionBase(request, method);
3255
+ const { args, ...base } = input;
3256
+ return {
3257
+ ...base,
3258
+ positionIdList: uint256ArrayArg(args, "positionIdList"),
3259
+ usePremiaAsCollateral: booleanArg(args.usePremiaAsCollateral, `${method} args.usePremiaAsCollateral`)
3260
+ };
3261
+ }
3262
+ function parseWithdrawWithPositionBase(request, method) {
3263
+ rejectContext(request, method);
3264
+ const args = requestArgs(request, method);
3265
+ rejectExtraKeys(
3266
+ args,
3267
+ ["collateralTracker", "assets", "receiver", "owner", "positionIdList", "usePremiaAsCollateral"],
3268
+ method
3269
+ );
3270
+ return {
3271
+ args,
3272
+ collateralTracker: normalizePanopticAddress(args.collateralTracker, `${method} args.collateralTracker`),
3273
+ assets: uint256Arg(args, "assets"),
3274
+ receiver: normalizePanopticAddress(args.receiver, `${method} args.receiver`),
3275
+ owner: normalizePanopticAddress(args.owner, `${method} args.owner`)
3276
+ };
3277
+ }
3278
+ function booleanArg(value, label) {
3279
+ if (typeof value !== "boolean") {
3280
+ throw new Error(`Panoptic ${label} must be a boolean.`);
3281
+ }
3282
+ return value;
3283
+ }
3284
+
3285
+ // src/internal/panoptic/fragments/hypovault.ts
3286
+ var FULFILL_DEPOSITS_SELECTOR = "0x50dcdee9";
3287
+ var FULFILL_WITHDRAWALS_SELECTOR = "0x69838516";
3288
+ var MANAGE_SELECTOR = "0xf6e715d0";
3289
+ var MANAGE_ABI = [
3290
+ {
3291
+ type: "function",
3292
+ name: "manage",
3293
+ stateMutability: "payable",
3294
+ inputs: [
3295
+ { name: "target", type: "address" },
3296
+ { name: "data", type: "bytes" },
3297
+ { name: "value", type: "uint256" }
3298
+ ],
3299
+ outputs: []
3300
+ }
3301
+ ];
3302
+ async function fulfillDepositsFragment({ deps, method, request, options }) {
3303
+ void options;
3304
+ const input = parseFulfillDepositsRequest(request, method);
3305
+ const encodeFulfillDepositsFunctionData = requireSdkFunction(
3306
+ await deps.sdk(),
3307
+ "encodeFulfillDepositsFunctionData",
3308
+ "@panoptic-eng/sdk"
3309
+ );
3310
+ const split = splitCalldata(
3311
+ await encodeFulfillDepositsFunctionData({
3312
+ assetsToFulfill: input.assetsToFulfill,
3313
+ managerInput: input.managerInput
3314
+ }),
3315
+ method,
3316
+ { expectedSelector: FULFILL_DEPOSITS_SELECTOR }
3317
+ );
3318
+ return makeDynamicJobFragment({
3319
+ target: input.vaultManager,
3320
+ userProvidedData: split.userProvidedData,
3321
+ strategyProvidedData: split.strategyProvidedData,
3322
+ value: "0"
3323
+ });
3324
+ }
3325
+ async function fulfillWithdrawalsFragment({ deps, method, request, options }) {
3326
+ void options;
3327
+ const input = parseFulfillWithdrawalsRequest(request, method);
3328
+ const encodeFulfillWithdrawalsFunctionData = requireSdkFunction(
3329
+ await deps.sdk(),
3330
+ "encodeFulfillWithdrawalsFunctionData",
3331
+ "@panoptic-eng/sdk"
3332
+ );
3333
+ const split = splitCalldata(
3334
+ await encodeFulfillWithdrawalsFunctionData({
3335
+ sharesToFulfill: input.sharesToFulfill,
3336
+ maxAssetsReceived: input.maxAssetsReceived,
3337
+ managerInput: input.managerInput
3338
+ }),
3339
+ method,
3340
+ { expectedSelector: FULFILL_WITHDRAWALS_SELECTOR }
3341
+ );
3342
+ return makeDynamicJobFragment({
3343
+ target: input.vaultManager,
3344
+ userProvidedData: split.userProvidedData,
3345
+ strategyProvidedData: split.strategyProvidedData,
3346
+ value: "0"
3347
+ });
3348
+ }
3349
+ async function manageCalldataParts({ deps, method, request, options }) {
3350
+ void options;
3351
+ const input = parseManageRequest(request, method, false);
3352
+ const split = splitCalldata(await encodeManageCalldata(deps, input), method, { expectedSelector: MANAGE_SELECTOR });
3353
+ return {
3354
+ functionName: "manage",
3355
+ calldata: split.calldata,
3356
+ userProvidedData: split.userProvidedData,
3357
+ strategyProvidedData: split.strategyProvidedData,
3358
+ value: "0"
3359
+ };
3360
+ }
3361
+ async function manageFragment({ deps, method, request, options }) {
3362
+ void options;
3363
+ const input = parseManageRequest(request, method, true);
3364
+ const split = splitCalldata(await encodeManageCalldata(deps, input), method, { expectedSelector: MANAGE_SELECTOR });
3365
+ return makeDynamicJobFragment({
3366
+ target: input.manager,
3367
+ userProvidedData: split.userProvidedData,
3368
+ strategyProvidedData: split.strategyProvidedData,
3369
+ value: "0"
3370
+ });
3371
+ }
3372
+ async function encodeManageCalldata(deps, input) {
3373
+ const encodeFunctionData = requireSdkFunction(await deps.viem(), "encodeFunctionData", "viem");
3374
+ return encodeFunctionData({
3375
+ abi: MANAGE_ABI,
3376
+ functionName: "manage",
3377
+ args: [input.innerTarget, input.innerData, input.value]
3378
+ });
3379
+ }
3380
+ function parseFulfillDepositsRequest(request, method) {
3381
+ rejectContext(request, method);
3382
+ const args = requestArgs(request, method);
3383
+ rejectExtraKeys(args, ["vaultManager", "assetsToFulfill", "managerInput"], method);
3384
+ return {
3385
+ vaultManager: normalizePanopticAddress(args.vaultManager, `${method} args.vaultManager`),
3386
+ assetsToFulfill: uint256Arg(args, "assetsToFulfill"),
3387
+ managerInput: normalizePanopticHex(args.managerInput, `${method} args.managerInput`)
3388
+ };
3389
+ }
3390
+ function parseFulfillWithdrawalsRequest(request, method) {
3391
+ rejectContext(request, method);
3392
+ const args = requestArgs(request, method);
3393
+ rejectExtraKeys(args, ["vaultManager", "sharesToFulfill", "maxAssetsReceived", "managerInput"], method);
3394
+ return {
3395
+ vaultManager: normalizePanopticAddress(args.vaultManager, `${method} args.vaultManager`),
3396
+ sharesToFulfill: uint256Arg(args, "sharesToFulfill"),
3397
+ maxAssetsReceived: uint256Arg(args, "maxAssetsReceived"),
3398
+ managerInput: normalizePanopticHex(args.managerInput, `${method} args.managerInput`)
3399
+ };
3400
+ }
3401
+ function parseManageRequest(request, method, requireManager) {
3402
+ rejectContext(request, method);
3403
+ const args = requestArgs(request, method);
3404
+ rejectExtraKeys(
3405
+ args,
3406
+ requireManager ? ["manager", "innerTarget", "innerData", "value"] : ["innerTarget", "innerData", "value"],
3407
+ method
3408
+ );
3409
+ return {
3410
+ ...requireManager ? { manager: normalizePanopticAddress(args.manager, `${method} args.manager`) } : {},
3411
+ innerTarget: normalizePanopticAddress(args.innerTarget, `${method} args.innerTarget`),
3412
+ innerData: normalizePanopticHex(args.innerData, `${method} args.innerData`),
3413
+ value: args.value === void 0 ? BigInt(0) : uint256Arg(args, "value")
3414
+ };
3415
+ }
3416
+
3417
+ // src/internal/panoptic/fragments/merkle.ts
3418
+ var MANAGE_VAULT_WITH_MERKLE_VERIFICATION_SELECTOR = "0x244b0f6a";
3419
+ var MANAGE_VAULT_WITH_MERKLE_VERIFICATION_ABI = [
3420
+ {
3421
+ type: "function",
3422
+ name: "manageVaultWithMerkleVerification",
3423
+ stateMutability: "nonpayable",
3424
+ inputs: [
3425
+ { name: "manageProofs", type: "bytes32[][]" },
3426
+ { name: "decodersAndSanitizers", type: "address[]" },
3427
+ { name: "targets", type: "address[]" },
3428
+ { name: "targetData", type: "bytes[]" },
3429
+ { name: "values", type: "uint256[]" }
3430
+ ],
3431
+ outputs: []
3432
+ }
3433
+ ];
3434
+ async function manageVaultWithVerificationFragment({ deps, method, request, options }) {
3435
+ void options;
3436
+ const input = parseManageVaultWithVerificationRequest(request, method);
3437
+ const encodeFunctionData = requireSdkFunction(await deps.viem(), "encodeFunctionData", "viem");
3438
+ const split = splitCalldata(
3439
+ await encodeFunctionData({
3440
+ abi: MANAGE_VAULT_WITH_MERKLE_VERIFICATION_ABI,
3441
+ functionName: "manageVaultWithMerkleVerification",
3442
+ args: [input.proofs, input.decoders, input.innerTargets, input.innerDatas, input.values]
3443
+ }),
3444
+ method,
3445
+ { expectedSelector: MANAGE_VAULT_WITH_MERKLE_VERIFICATION_SELECTOR }
3446
+ );
3447
+ return makeDynamicJobFragment({
3448
+ target: input.manager,
3449
+ userProvidedData: split.userProvidedData,
3450
+ strategyProvidedData: split.strategyProvidedData,
3451
+ value: "0"
3452
+ });
3453
+ }
3454
+ function findLeaf({ request, method }) {
3455
+ const input = parseFindLeafRequest(request, method);
3456
+ const leaf = findArtifactLeaf(input.artifact, input.query, method);
3457
+ return projectLeafWithProof(input.artifact, leaf, method);
3458
+ }
3459
+ function buildManageArgs({ request, method }) {
3460
+ const input = parseBuildManageArgsRequest(request, method);
3461
+ const proofs = [];
3462
+ const decoders = [];
3463
+ const innerTargets = [];
3464
+ const innerDatas = [];
3465
+ const values = [];
3466
+ const leaves = [];
3467
+ for (const [index, action] of input.actions.entries()) {
3468
+ const label = `${method} args.actions[${index}]`;
3469
+ const leaf = findArtifactLeaf(input.artifact, action.query, label);
3470
+ const projected = projectLeafWithProof(input.artifact, leaf, label);
3471
+ proofs.push(projected.proof);
3472
+ decoders.push(projected.decoder);
3473
+ innerTargets.push(projected.target);
3474
+ innerDatas.push(action.data);
3475
+ values.push(action.value);
3476
+ leaves.push(projected);
3477
+ }
3478
+ return {
3479
+ proofs,
3480
+ decoders,
3481
+ innerTargets,
3482
+ innerDatas,
3483
+ values,
3484
+ leaves
3485
+ };
3486
+ }
3487
+ function parseManageVaultWithVerificationRequest(request, method) {
3488
+ rejectContext(request, method);
3489
+ const args = requestArgs(request, method);
3490
+ rejectExtraKeys(args, ["manager", "proofs", "decoders", "innerTargets", "innerDatas", "values"], method);
3491
+ const proofs = bytes32MatrixArg(args, "proofs", method);
3492
+ const decoders = addressArrayArg(args, "decoders", method);
3493
+ const innerTargets = addressArrayArg(args, "innerTargets", method);
3494
+ const innerDatas = hexArrayArg(args, "innerDatas", method);
3495
+ const values = uint256Array(args, "values");
3496
+ const length = proofs.length;
3497
+ for (const [field, value] of [
3498
+ ["decoders", decoders],
3499
+ ["innerTargets", innerTargets],
3500
+ ["innerDatas", innerDatas],
3501
+ ["values", values]
3502
+ ]) {
3503
+ if (value.length !== length) {
3504
+ throw new Error(`Panoptic ${method} args.${field} length must match args.proofs length.`);
3505
+ }
3506
+ }
3507
+ if (length === 0) {
3508
+ throw new Error(`Panoptic ${method} args.proofs must include at least one proof.`);
3509
+ }
3510
+ return {
3511
+ manager: normalizePanopticAddress(args.manager, `${method} args.manager`),
3512
+ proofs,
3513
+ decoders,
3514
+ innerTargets,
3515
+ innerDatas,
3516
+ values
3517
+ };
3518
+ }
3519
+ function parseFindLeafRequest(request, method) {
3520
+ rejectContext(request, method);
3521
+ const args = requestArgs(request, method);
3522
+ rejectExtraKeys(
3523
+ args,
3524
+ ["artifact", "action", "description", "functionSignature", "functionSelector", "target"],
3525
+ method
3526
+ );
3527
+ return {
3528
+ artifact: recordValue(args.artifact, `args.artifact`),
3529
+ query: parseLeafQuery(args, method, "args")
3530
+ };
3531
+ }
3532
+ function parseBuildManageArgsRequest(request, method) {
3533
+ rejectContext(request, method);
3534
+ const args = requestArgs(request, method);
3535
+ rejectExtraKeys(args, ["artifact", "actions"], method);
3536
+ return {
3537
+ artifact: recordValue(args.artifact, `args.artifact`),
3538
+ actions: arrayValue(args.actions, "args.actions").map((item, index) => {
3539
+ const action = recordValue(item, `args.actions[${index}]`);
3540
+ rejectExtraKeys(
3541
+ action,
3542
+ ["action", "description", "functionSignature", "functionSelector", "target", "data", "value"],
3543
+ method
3544
+ );
3545
+ return {
3546
+ query: parseLeafQuery(action, method, `args.actions[${index}]`),
3547
+ data: normalizePanopticHex(action.data, `${method} args.actions[${index}].data`),
3548
+ value: action.value === void 0 ? BigInt(0) : decimalValue(action.value, `args.actions[${index}].value`)
3549
+ };
3550
+ })
3551
+ };
3552
+ }
3553
+ function parseLeafQuery(args, method, label) {
3554
+ const query = {
3555
+ ...args.action === void 0 ? {} : { action: stringValue(args.action, `${label}.action`) },
3556
+ ...args.description === void 0 ? {} : { description: stringValue(args.description, `${label}.description`) },
3557
+ ...args.functionSignature === void 0 ? {} : { functionSignature: stringValue(args.functionSignature, `${label}.functionSignature`) },
3558
+ ...args.functionSelector === void 0 ? {} : { functionSelector: normalizePanopticHex(args.functionSelector, `${method} ${label}.functionSelector`) },
3559
+ ...args.target === void 0 ? {} : { target: normalizePanopticAddress(args.target, `${method} ${label}.target`) }
3560
+ };
3561
+ if (Object.keys(query).length === 0) {
3562
+ throw new Error(`Panoptic ${method} ${label} must include at least one leaf selector.`);
3563
+ }
3564
+ return query;
3565
+ }
3566
+ function findArtifactLeaf(artifact, query, method) {
3567
+ const leaves = artifactLeafs(artifact, method);
3568
+ const matches = leaves.filter((leaf) => leafMatches(leaf, query, method));
3569
+ if (matches.length === 0) {
3570
+ throw new Error(`Panoptic ${method} could not find a matching Merkle leaf.`);
3571
+ }
3572
+ if (matches.length > 1) {
3573
+ throw new Error(`Panoptic ${method} found multiple matching Merkle leaves; provide a more specific selector.`);
3574
+ }
3575
+ return matches[0];
3576
+ }
3577
+ function artifactLeafs(artifact, method) {
3578
+ const rawLeaves = artifact.leafs ?? artifact.uniqueLeafs ?? (isJsonRecord3(artifact.artifact) ? artifact.artifact.leafs : void 0);
3579
+ return arrayValue(rawLeaves, `${method} artifact.leafs`).map(
3580
+ (item, index) => recordValue(item, `${method} artifact.leafs[${index}]`)
3581
+ );
3582
+ }
3583
+ function leafMatches(leaf, query, method) {
3584
+ if (query.action !== void 0 && leafString(leaf, "Action", method) !== query.action) return false;
3585
+ if (query.description !== void 0 && leafString(leaf, "Description", method) !== query.description) return false;
3586
+ if (query.functionSignature !== void 0 && leafString(leaf, "FunctionSignature", method) !== query.functionSignature)
3587
+ return false;
3588
+ if (query.functionSelector !== void 0 && normalizePanopticHex(leaf.FunctionSelector, `${method} leaf.FunctionSelector`) !== query.functionSelector)
3589
+ return false;
3590
+ if (query.target !== void 0 && normalizePanopticAddress(leaf.TargetAddress, `${method} leaf.TargetAddress`) !== query.target)
3591
+ return false;
3592
+ return true;
3593
+ }
3594
+ function projectLeafWithProof(artifact, leaf, method) {
3595
+ const action = leafString(leaf, "Action", method);
3596
+ const leafDigest = normalizePanopticHex(leaf.LeafDigest, `${method} leaf.LeafDigest`);
3597
+ return {
3598
+ action,
3599
+ description: leafString(leaf, "Description", method),
3600
+ leafDigest,
3601
+ decoder: normalizePanopticAddress(leaf.DecoderAndSanitizerAddress, `${method} leaf.DecoderAndSanitizerAddress`),
3602
+ target: normalizePanopticAddress(leaf.TargetAddress, `${method} leaf.TargetAddress`),
3603
+ functionSignature: leafString(leaf, "FunctionSignature", method),
3604
+ functionSelector: normalizePanopticHex(leaf.FunctionSelector, `${method} leaf.FunctionSelector`),
3605
+ canSendValue: leaf.CanSendValue === true,
3606
+ proof: proofForLeaf(artifact, action, leafDigest, method)
3607
+ };
3608
+ }
3609
+ function proofForLeaf(artifact, action, leafDigest, method) {
3610
+ const byAction = isJsonRecord3(artifact.proofsByAction) ? artifact.proofsByAction[action] : void 0;
3611
+ const byDigest = isJsonRecord3(artifact.proofsByDigest) ? artifact.proofsByDigest[leafDigest] : void 0;
3612
+ const proof = byAction ?? byDigest;
3613
+ return proof === void 0 ? [] : arrayValue(proof, `${method} proof`).map((item, index) => bytes32Value(item, `${method} proof[${index}]`));
3614
+ }
3615
+ function leafString(leaf, field, method) {
3616
+ return stringValue(leaf[field], `${method} leaf.${field}`);
3617
+ }
3618
+ function bytes32Value(value, label) {
3619
+ const hex = normalizePanopticHex(value, label);
3620
+ if (hex.length !== 66) {
3621
+ throw new Error(`Panoptic ${label} must be bytes32.`);
3622
+ }
3623
+ return hex;
3624
+ }
3625
+ function bytes32MatrixArg(args, fieldName, method) {
3626
+ return arrayValue(args[fieldName], `args.${fieldName}`).map(
3627
+ (row, rowIndex) => arrayValue(row, `args.${fieldName}[${rowIndex}]`).map((item, index) => {
3628
+ const proof = normalizePanopticHex(item, `${method} args.${fieldName}[${rowIndex}][${index}]`);
3629
+ if (proof.length !== 66) {
3630
+ throw new Error(`Panoptic ${method} args.${fieldName}[${rowIndex}][${index}] must be bytes32.`);
3631
+ }
3632
+ return proof;
3633
+ })
3634
+ );
3635
+ }
3636
+ function addressArrayArg(args, fieldName, method) {
3637
+ return arrayValue(args[fieldName], `args.${fieldName}`).map(
3638
+ (item, index) => normalizePanopticAddress(item, `${method} args.${fieldName}[${index}]`)
3639
+ );
3640
+ }
3641
+ function hexArrayArg(args, fieldName, method) {
3642
+ return arrayValue(args[fieldName], `args.${fieldName}`).map(
3643
+ (item, index) => normalizePanopticHex(item, `${method} args.${fieldName}[${index}]`)
3644
+ );
3645
+ }
3646
+ function uint256Array(args, fieldName) {
3647
+ return arrayValue(args[fieldName], `args.${fieldName}`).map(
3648
+ (item, index) => decimalValue(item, `args.${fieldName}[${index}]`)
3649
+ );
3650
+ }
3651
+ function isJsonRecord3(value) {
3652
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3653
+ }
3654
+
3655
+ // src/internal/panoptic/fragments/panoptic.ts
3656
+ var PANOPTIC_DISPATCH_SELECTOR = "0xc25813aa";
3657
+ var MAX_EXISTING_POSITION_IDS = 64;
3658
+ var UINT128_MAX2 = (BigInt(1) << BigInt(128)) - BigInt(1);
3659
+ var INT24_MIN2 = -(BigInt(1) << BigInt(23));
3660
+ var INT24_MAX2 = (BigInt(1) << BigInt(23)) - BigInt(1);
3661
+ var DISPATCH_EXPLICIT_ABI = [
3662
+ {
3663
+ type: "function",
3664
+ name: "dispatch",
3665
+ stateMutability: "nonpayable",
3666
+ inputs: [
3667
+ { name: "positionIdList", type: "uint256[]" },
3668
+ { name: "finalPositionIdList", type: "uint256[]" },
3669
+ { name: "positionSizes", type: "uint128[]" },
3670
+ { name: "tickAndSpreadLimits", type: "int24[3][]" },
3671
+ { name: "usePremiaAsCollateral", type: "bool" },
3672
+ { name: "builderCode", type: "uint256" }
3673
+ ],
3674
+ outputs: []
3675
+ }
3676
+ ];
3677
+ async function dispatchCalldataParts({ deps, request, method }) {
3678
+ const input = parseDispatchRequest(request, method);
3679
+ const sdkV2 = await deps.sdkV2();
3680
+ const buildOpenPositionCalldata = requireSdkFunction(sdkV2, "buildOpenPositionCalldata", "@panoptic-eng/sdk/v2");
3681
+ const poolAddress2 = requireString(input.poolAddress, `${method} args.poolAddress`);
3682
+ const split = splitDispatchCalldata(
3683
+ await buildOpenPositionCalldata(buildOpenPositionParams(input, poolAddress2)),
3684
+ method
3685
+ );
3686
+ return {
3687
+ functionName: "dispatch",
3688
+ userProvidedData: split.userProvidedData,
3689
+ strategyProvidedData: split.strategyProvidedData,
3690
+ calldata: split.calldata
3691
+ };
3692
+ }
3693
+ async function dispatchFragment({ deps, request, options, method }) {
3694
+ void options;
3695
+ const input = parseDispatchRequest(request, method);
3696
+ const sdkV2 = await deps.sdkV2();
3697
+ const buildOpenPositionCalldata = requireSdkFunction(sdkV2, "buildOpenPositionCalldata", "@panoptic-eng/sdk/v2");
3698
+ const targetAddress = input.poolAddress;
3699
+ const split = splitDispatchCalldata(
3700
+ await buildOpenPositionCalldata(buildOpenPositionParams(input, input.poolAddress)),
3701
+ method
3702
+ );
3703
+ if (split.target && split.target !== targetAddress) {
3704
+ throw new Error(`Panoptic ${method} SDK returned a target that does not match args.poolAddress.`);
3705
+ }
3706
+ return makeDynamicJobFragment({
3707
+ target: targetAddress,
3708
+ userProvidedData: split.userProvidedData,
3709
+ strategyProvidedData: split.strategyProvidedData,
3710
+ value: "0"
3711
+ });
3712
+ }
3713
+ async function dispatchExplicitCalldataParts({ deps, request, method }) {
3714
+ const input = parseExplicitDispatchRequest(request, method);
3715
+ const split = splitDispatchCalldata(await encodeExplicitDispatchCalldata(deps, input), method);
3716
+ return {
3717
+ functionName: "dispatch",
3718
+ userProvidedData: split.userProvidedData,
3719
+ strategyProvidedData: split.strategyProvidedData,
3720
+ calldata: split.calldata,
3721
+ value: "0"
3722
+ };
3723
+ }
3724
+ async function dispatchExplicitFragment({ deps, request, options, method }) {
3725
+ void options;
3726
+ const input = parseExplicitDispatchRequest(request, method);
3727
+ const split = splitDispatchCalldata(await encodeExplicitDispatchCalldata(deps, input), method);
3728
+ return makeDynamicJobFragment({
3729
+ target: input.poolAddress,
3730
+ userProvidedData: split.userProvidedData,
3731
+ strategyProvidedData: split.strategyProvidedData,
3732
+ value: "0"
3733
+ });
3734
+ }
3735
+ async function encodeExplicitDispatchCalldata(deps, input) {
3736
+ const encodeFunctionData = requireSdkFunction(await deps.viem(), "encodeFunctionData", "viem");
3737
+ return encodeFunctionData({
3738
+ abi: DISPATCH_EXPLICIT_ABI,
3739
+ functionName: "dispatch",
3740
+ args: [
3741
+ input.positionIdList,
3742
+ input.finalPositionIdList,
3743
+ input.positionSizes,
3744
+ input.tickAndSpreadLimits,
3745
+ input.usePremiaAsCollateral,
3746
+ input.builderCode
3747
+ ]
3748
+ });
3749
+ }
3750
+ function parseDispatchRequest(request, method) {
3751
+ rejectContext(request, method);
3752
+ const args = requestArgs(request, method);
3753
+ rejectExtraKeys(args, dispatchKeys, method);
3754
+ return parseDispatchCommon(args, method);
3755
+ }
3756
+ function parseExplicitDispatchRequest(request, method) {
3757
+ rejectContext(request, method);
3758
+ const args = requestArgs(request, method);
3759
+ rejectExtraKeys(args, explicitDispatchKeys, method);
3760
+ const positionIdList = positionIdsArg(args, "positionIdList", method);
3761
+ const positionSizes = uint128ArrayArg(args, "positionSizes", method);
3762
+ const tickAndSpreadLimits = int24TripleArrayArg(args.tickAndSpreadLimits, `${method} args.tickAndSpreadLimits`);
3763
+ if (positionSizes.length !== positionIdList.length) {
3764
+ throw new Error(`Panoptic ${method} args.positionSizes length must match args.positionIdList length.`);
3765
+ }
3766
+ if (tickAndSpreadLimits.length !== positionIdList.length) {
3767
+ throw new Error(`Panoptic ${method} args.tickAndSpreadLimits length must match args.positionIdList length.`);
3768
+ }
3769
+ return {
3770
+ poolAddress: normalizePanopticAddress(args.poolAddress, `${method} args.poolAddress`),
3771
+ positionIdList,
3772
+ finalPositionIdList: uint256ArrayArg(args, "finalPositionIdList"),
3773
+ positionSizes,
3774
+ tickAndSpreadLimits,
3775
+ usePremiaAsCollateral: requiredBooleanArg(args.usePremiaAsCollateral, `${method} args.usePremiaAsCollateral`),
3776
+ builderCode: optionalUint256Arg(args, "builderCode") ?? BigInt(0)
3777
+ };
3778
+ }
3779
+ function parseDispatchCommon(args, method) {
3780
+ return {
3781
+ poolAddress: normalizePanopticAddress(args.poolAddress, `${method} args.poolAddress`),
3782
+ existingPositionIds: positionIdsArg(args, "existingPositionIds", method),
3783
+ tokenId: uint256Arg(args, "tokenId"),
3784
+ positionSize: uint128Arg(args, "positionSize"),
3785
+ tickLimitLow: int24Arg(args, "tickLimitLow"),
3786
+ tickLimitHigh: int24Arg(args, "tickLimitHigh"),
3787
+ spreadLimit: optionalInt24Arg(args, "spreadLimit"),
3788
+ swapAtMint: optionalBooleanArg2(args, "swapAtMint", method),
3789
+ usePremiaAsCollateral: optionalBooleanArg2(args, "usePremiaAsCollateral", method),
3790
+ builderCode: optionalUint256Arg(args, "builderCode")
3791
+ };
3792
+ }
3793
+ function buildOpenPositionParams(input, poolAddress2) {
3794
+ return {
3795
+ poolAddress: poolAddress2,
3796
+ existingPositionIds: input.existingPositionIds,
3797
+ tokenId: input.tokenId,
3798
+ positionSize: input.positionSize,
3799
+ tickLimitLow: input.tickLimitLow,
3800
+ tickLimitHigh: input.tickLimitHigh,
3801
+ spreadLimit: input.spreadLimit,
3802
+ swapAtMint: input.swapAtMint,
3803
+ usePremiaAsCollateral: input.usePremiaAsCollateral,
3804
+ builderCode: input.builderCode
3805
+ };
3806
+ }
3807
+ function positionIdsArg(args, fieldName, method) {
3808
+ const positionIds = uint256ArrayArg(args, fieldName);
3809
+ if (positionIds.length > MAX_EXISTING_POSITION_IDS) {
3810
+ throw new Error(`Panoptic ${method} args.${fieldName} must contain at most ${MAX_EXISTING_POSITION_IDS} items.`);
3811
+ }
3812
+ return positionIds;
3813
+ }
3814
+ function splitDispatchCalldata(value, method) {
3815
+ return splitCalldata(value, method, { expectedSelector: PANOPTIC_DISPATCH_SELECTOR });
3816
+ }
3817
+ function optionalBooleanArg2(args, fieldName, method) {
3818
+ const value = args[fieldName];
3819
+ if (value === void 0) {
3820
+ return void 0;
3821
+ }
3822
+ if (typeof value !== "boolean") {
3823
+ throw new Error(`Panoptic ${method} args.${fieldName} must be a boolean.`);
3824
+ }
3825
+ return value;
3826
+ }
3827
+ function requiredBooleanArg(value, label) {
3828
+ if (typeof value !== "boolean") {
3829
+ throw new Error(`Panoptic ${label} must be a boolean.`);
3830
+ }
3831
+ return value;
3832
+ }
3833
+ function uint128ArrayArg(args, fieldName, method) {
3834
+ const values = uint256ArrayArg(args, fieldName);
3835
+ for (const [index, value] of values.entries()) {
3836
+ if (value > UINT128_MAX2) {
3837
+ throw new Error(`Panoptic ${method} args.${fieldName}[${index}] exceeds uint128 range.`);
3838
+ }
3839
+ }
3840
+ return values;
3841
+ }
3842
+ function int24TripleArrayArg(value, label) {
3843
+ if (!Array.isArray(value)) {
3844
+ throw new Error(`Panoptic ${label} must be an array.`);
3845
+ }
3846
+ return value.map((row, rowIndex) => {
3847
+ if (!Array.isArray(row) || row.length !== 3) {
3848
+ throw new Error(`Panoptic ${label}[${rowIndex}] must be an int24 triple.`);
3849
+ }
3850
+ return row.map((item, index) => signedInt24Value(item, `${label}[${rowIndex}][${index}]`));
3851
+ });
3852
+ }
3853
+ function signedInt24Value(value, label) {
3854
+ if (typeof value !== "string" || !/^-?(0|[1-9][0-9]*)$/.test(value)) {
3855
+ throw new Error(`Panoptic ${label} must be a signed decimal string.`);
3856
+ }
3857
+ const parsed = BigInt(value);
3858
+ if (parsed < INT24_MIN2 || parsed > INT24_MAX2) {
3859
+ throw new Error(`Panoptic ${label} exceeds int24 range.`);
3860
+ }
3861
+ return parsed;
3862
+ }
3863
+ var dispatchKeys = [
3864
+ "poolAddress",
3865
+ "existingPositionIds",
3866
+ "tokenId",
3867
+ "positionSize",
3868
+ "tickLimitLow",
3869
+ "tickLimitHigh",
3870
+ "spreadLimit",
3871
+ "swapAtMint",
3872
+ "usePremiaAsCollateral",
3873
+ "builderCode"
3874
+ ];
3875
+ var explicitDispatchKeys = [
3876
+ "poolAddress",
3877
+ "positionIdList",
3878
+ "finalPositionIdList",
3879
+ "positionSizes",
3880
+ "tickAndSpreadLimits",
3881
+ "usePremiaAsCollateral",
3882
+ "builderCode"
3883
+ ];
3884
+
3885
+ // src/internal/panoptic/fragments/permit2.ts
3886
+ var PERMIT2_APPROVE_ABI = [
3887
+ {
3888
+ type: "function",
3889
+ name: "approve",
3890
+ stateMutability: "nonpayable",
3891
+ inputs: [
3892
+ { name: "token", type: "address" },
3893
+ { name: "spender", type: "address" },
3894
+ { name: "amount", type: "uint160" },
3895
+ { name: "expiration", type: "uint48" }
3896
+ ],
3897
+ outputs: []
3898
+ }
3899
+ ];
3900
+ var PERMIT2_APPROVE_SELECTOR = "0x87517c45";
3901
+ async function approveFragment2({ deps, method, request, options }) {
3902
+ void options;
3903
+ const input = parseApproveRequest2(request, method);
3904
+ const encodeFunctionData = requireSdkFunction(await deps.viem(), "encodeFunctionData", "viem");
3905
+ const calldata = await encodeFunctionData({
3906
+ abi: PERMIT2_APPROVE_ABI,
3907
+ functionName: "approve",
3908
+ args: [input.token, input.spender, input.amount, input.expiration]
3909
+ });
3910
+ const split = splitCalldata(calldata, method, {
3911
+ expectedSelector: PERMIT2_APPROVE_SELECTOR,
3912
+ staticArgWords: 2
3913
+ });
3914
+ assertUserProvidedData(
3915
+ split.userProvidedData,
3916
+ `${PERMIT2_APPROVE_SELECTOR}${addressAbiWord(input.token)}${addressAbiWord(input.spender)}`,
3917
+ method
3918
+ );
3919
+ return makeDynamicJobFragment({
3920
+ target: input.permit2,
3921
+ userProvidedData: split.userProvidedData,
3922
+ strategyProvidedData: split.strategyProvidedData,
3923
+ value: "0"
3924
+ });
3925
+ }
3926
+ function parseApproveRequest2(request, method) {
3927
+ rejectContext(request, method);
3928
+ const args = requestArgs(request, method);
3929
+ rejectExtraKeys(args, ["permit2", "token", "spender", "amount", "expiration"], method);
3930
+ return {
3931
+ permit2: normalizePanopticAddress(args.permit2, `${method} args.permit2`),
3932
+ token: normalizePanopticAddress(args.token, `${method} args.token`),
3933
+ spender: normalizePanopticAddress(args.spender, `${method} args.spender`),
3934
+ amount: uint160Arg(args, "amount"),
3935
+ expiration: uint48Arg(args, "expiration")
3936
+ };
3937
+ }
3938
+
3939
+ // src/internal/panoptic/fragments/uniswap.ts
3940
+ var UNIVERSAL_ROUTER_EXECUTE_SELECTOR = "0x24856bc3";
3941
+ var UNIVERSAL_ROUTER_EXECUTE_DEADLINE_SELECTOR = "0x3593564c";
3942
+ var V3_SWAP_EXACT_IN_COMMAND = "0x00";
3943
+ var V3_EXACT_IN_INPUT_ABI = [
3944
+ { name: "recipient", type: "address" },
3945
+ { name: "amountIn", type: "uint256" },
3946
+ { name: "amountOutMinimum", type: "uint256" },
3947
+ { name: "path", type: "bytes" },
3948
+ { name: "payerIsUser", type: "bool" }
3949
+ ];
3950
+ var UNIVERSAL_ROUTER_EXECUTE_ABI = [
3951
+ {
3952
+ type: "function",
3953
+ name: "execute",
3954
+ stateMutability: "payable",
3955
+ inputs: [
3956
+ { name: "commands", type: "bytes" },
3957
+ { name: "inputs", type: "bytes[]" }
3958
+ ],
3959
+ outputs: []
3960
+ }
3961
+ ];
3962
+ var UNIVERSAL_ROUTER_EXECUTE_DEADLINE_ABI = [
3963
+ {
3964
+ type: "function",
3965
+ name: "execute",
3966
+ stateMutability: "payable",
3967
+ inputs: [
3968
+ { name: "commands", type: "bytes" },
3969
+ { name: "inputs", type: "bytes[]" },
3970
+ { name: "deadline", type: "uint256" }
3971
+ ],
3972
+ outputs: []
3973
+ }
3974
+ ];
3975
+ async function buildV3ExactInExecuteCalldataParts({ deps, request, method, options }) {
3976
+ void options;
3977
+ const input = parseV3ExactInRequest(request, method);
3978
+ const calldata = await buildV3ExactInCalldata(deps, input);
3979
+ const split = splitCalldata(calldata, method, {
3980
+ expectedSelector: input.deadline === void 0 ? UNIVERSAL_ROUTER_EXECUTE_SELECTOR : UNIVERSAL_ROUTER_EXECUTE_DEADLINE_SELECTOR
3981
+ });
3982
+ return {
3983
+ functionName: input.deadline === void 0 ? "execute(bytes,bytes[])" : "execute(bytes,bytes[],uint256)",
3984
+ calldata: split.calldata,
3985
+ userProvidedData: split.userProvidedData,
3986
+ strategyProvidedData: split.strategyProvidedData,
3987
+ value: "0"
3988
+ };
3989
+ }
3990
+ async function buildV3ExactInExecuteFragment({ deps, request, method, options }) {
3991
+ void options;
3992
+ const input = parseV3ExactInRequest(request, method);
3993
+ if (!input.router) {
3994
+ throw new Error(`Panoptic ${method} requires args.router.`);
3995
+ }
3996
+ const calldata = await buildV3ExactInCalldata(deps, input);
3997
+ const split = splitCalldata(calldata, method, {
3998
+ expectedSelector: input.deadline === void 0 ? UNIVERSAL_ROUTER_EXECUTE_SELECTOR : UNIVERSAL_ROUTER_EXECUTE_DEADLINE_SELECTOR
3999
+ });
4000
+ return makeDynamicJobFragment({
4001
+ target: input.router,
4002
+ userProvidedData: split.userProvidedData,
4003
+ strategyProvidedData: split.strategyProvidedData,
4004
+ value: "0"
4005
+ });
4006
+ }
4007
+ async function buildV3ExactInCalldata(deps, input) {
4008
+ const viem = await deps.viem();
4009
+ const encodeAbiParameters = requireSdkFunction(viem, "encodeAbiParameters", "viem");
4010
+ const encodeFunctionData = requireSdkFunction(viem, "encodeFunctionData", "viem");
4011
+ const path = encodeV3Path(input.tokenIn, input.fee, input.tokenOut);
4012
+ const exactInInput = await encodeAbiParameters(V3_EXACT_IN_INPUT_ABI, [
4013
+ input.recipient,
4014
+ input.amountIn,
4015
+ input.amountOutMin,
4016
+ path,
4017
+ input.payerIsUser
4018
+ ]);
4019
+ if (input.deadline === void 0) {
4020
+ return encodeFunctionData({
4021
+ abi: UNIVERSAL_ROUTER_EXECUTE_ABI,
4022
+ functionName: "execute",
4023
+ args: [V3_SWAP_EXACT_IN_COMMAND, [exactInInput]]
4024
+ });
4025
+ }
4026
+ return encodeFunctionData({
4027
+ abi: UNIVERSAL_ROUTER_EXECUTE_DEADLINE_ABI,
4028
+ functionName: "execute",
4029
+ args: [V3_SWAP_EXACT_IN_COMMAND, [exactInInput], input.deadline]
4030
+ });
4031
+ }
4032
+ function parseV3ExactInRequest(request, method) {
4033
+ rejectContext(request, method);
4034
+ const args = requestArgs(request, method);
4035
+ rejectExtraKeys(
4036
+ args,
4037
+ ["router", "tokenIn", "tokenOut", "fee", "recipient", "amountIn", "amountOutMin", "payerIsUser", "deadline"],
4038
+ method
4039
+ );
4040
+ return {
4041
+ ...args.router === void 0 ? {} : { router: normalizePanopticAddress(args.router, `${method} args.router`) },
4042
+ tokenIn: normalizePanopticAddress(args.tokenIn, `${method} args.tokenIn`),
4043
+ tokenOut: normalizePanopticAddress(args.tokenOut, `${method} args.tokenOut`),
4044
+ fee: uint24Arg(args.fee, `${method} args.fee`),
4045
+ recipient: normalizePanopticAddress(args.recipient, `${method} args.recipient`),
4046
+ amountIn: decimalValue(args.amountIn, "args.amountIn"),
4047
+ amountOutMin: decimalValue(args.amountOutMin, "args.amountOutMin"),
4048
+ payerIsUser: booleanValue(args.payerIsUser, "args.payerIsUser"),
4049
+ deadline: optionalDecimalArg(args, "deadline")
4050
+ };
4051
+ }
4052
+ function uint24Arg(value, label) {
4053
+ const parsed = decimalValue(value, label);
4054
+ if (parsed > BigInt(16777215)) {
4055
+ throw new Error(`Panoptic ${label} exceeds uint24 range.`);
4056
+ }
4057
+ return parsed;
4058
+ }
4059
+ function encodeV3Path(tokenIn, fee, tokenOut) {
4060
+ return `0x${tokenIn.slice(2)}${fee.toString(16).padStart(6, "0")}${tokenOut.slice(2)}`.toLowerCase();
4061
+ }
4062
+
4063
+ // src/internal/panoptic/fragments/weth.ts
4064
+ var WETH_DEPOSIT_SELECTOR = "0xd0e30db0";
4065
+ var WETH_WITHDRAW_SELECTOR = "0x2e1a7d4d";
4066
+ function depositCalldataParts({ request, method }) {
4067
+ const input = parseAmountRequest(request, method);
4068
+ return {
4069
+ functionName: "deposit",
4070
+ calldata: WETH_DEPOSIT_SELECTOR,
4071
+ userProvidedData: WETH_DEPOSIT_SELECTOR,
4072
+ strategyProvidedData: "0x",
4073
+ value: input.amount.toString(10)
4074
+ };
4075
+ }
4076
+ function withdrawCalldataParts({ request, method }) {
4077
+ const input = parseAmountRequest(request, method);
4078
+ const strategyProvidedData = `0x${uint256AbiWord(input.amount)}`;
4079
+ return {
4080
+ functionName: "withdraw",
4081
+ calldata: `${WETH_WITHDRAW_SELECTOR}${strategyProvidedData.slice(2)}`,
4082
+ userProvidedData: WETH_WITHDRAW_SELECTOR,
4083
+ strategyProvidedData,
4084
+ value: "0"
4085
+ };
4086
+ }
4087
+ function hypovaultWethDepositInnerCall({ request, method }) {
4088
+ const input = parseWethTargetAmountRequest(request, method);
4089
+ return {
4090
+ functionName: "deposit",
4091
+ target: input.weth,
4092
+ data: WETH_DEPOSIT_SELECTOR,
4093
+ value: input.amount.toString(10)
4094
+ };
4095
+ }
4096
+ function hypovaultWethWithdrawInnerCall({ request, method }) {
4097
+ const input = parseWethTargetAmountRequest(request, method);
4098
+ const data = `${WETH_WITHDRAW_SELECTOR}${uint256AbiWord(input.amount)}`;
4099
+ return {
4100
+ functionName: "withdraw",
4101
+ target: input.weth,
4102
+ data,
4103
+ value: "0"
4104
+ };
4105
+ }
4106
+ function parseAmountRequest(request, method) {
4107
+ rejectContext(request, method);
4108
+ const args = requestArgs(request, method);
4109
+ rejectExtraKeys(args, ["amount"], method);
4110
+ return { amount: uint256Arg(args, "amount") };
4111
+ }
4112
+ function parseWethTargetAmountRequest(request, method) {
4113
+ rejectContext(request, method);
4114
+ const args = requestArgs(request, method);
4115
+ rejectExtraKeys(args, ["weth", "amount"], method);
4116
+ return {
4117
+ weth: normalizePanopticAddress(args.weth, `${method} args.weth`),
4118
+ amount: uint256Arg(args, "amount")
4119
+ };
4120
+ }
4121
+
4122
+ // src/internal/panoptic/dynamicJobs/renderExecuteJob.ts
4123
+ function renderExecuteJob({ request, method }) {
4124
+ const { fragments } = parseRenderExecuteJobRequest(request, method);
4125
+ return {
4126
+ functionName: "executeJob(address[],bytes[],bytes[])",
4127
+ typesArray: ["address[]", "bytes[]", "bytes[]"],
4128
+ valuesArray: [
4129
+ fragments.map((fragment) => fragment.target),
4130
+ fragments.map((fragment) => fragment.userProvidedData),
4131
+ fragments.map((fragment) => fragment.strategyProvidedData)
4132
+ ]
4133
+ };
4134
+ }
4135
+ function parseRenderExecuteJobRequest(request, method) {
4136
+ const args = requestArgs(request, method);
4137
+ rejectExtraKeys(args, ["fragments"], method);
4138
+ if (!Array.isArray(args.fragments)) {
4139
+ throw new Error(`Panoptic ${method} args.fragments must be an array.`);
4140
+ }
4141
+ if (args.fragments.length === 0) {
4142
+ throw new Error(`Panoptic ${method} args.fragments must include at least one fragment.`);
4143
+ }
4144
+ if (args.fragments.length > 64) {
4145
+ throw new Error(`Panoptic ${method} args.fragments exceeds maximum array length 64.`);
4146
+ }
4147
+ return {
4148
+ fragments: args.fragments.map(
4149
+ (fragment, index) => validateDynamicJobFragment(fragment, `${method} args.fragments[${index}]`)
4150
+ )
4151
+ };
4152
+ }
4153
+
4154
+ // src/internal/panoptic/handlers.ts
4155
+ var RPC_HANDLERS = Object.freeze({
4156
+ "account.getAccountCollateral": getAccountCollateral,
4157
+ "account.getAccountSummaryBasic": getAccountSummaryBasic,
4158
+ "account.getAccountSummaryRisk": getAccountSummaryRisk,
4159
+ "account.getLiquidationPrices": getLiquidationPrices,
4160
+ "account.getNetLiquidationValue": getNetLiquidationValue,
4161
+ "account.getNetLiquidationValues": getNetLiquidationValues,
4162
+ "account.getOpenPositionIds": getOpenPositionIds,
4163
+ "account.getPosition": getPosition,
4164
+ "account.getPositions": getPositions,
4165
+ "greeks.getPositionGreeks": getPositionGreeks,
4166
+ "hypovault.buildVaultManagerInputAtBlock": buildVaultManagerInputAtBlock,
4167
+ "hypovault.getEpochContext": getEpochContext,
4168
+ "hypovault.getOpenPositionIds": getOpenPositionIds2,
4169
+ "hypovault.getPositionsHashStatus": getPositionsHashStatus,
4170
+ "hypovault.verifyVaultOpenTokenIdsAtBlock": verifyVaultOpenTokenIdsAtBlock,
4171
+ "pool.fetchPoolId": fetchPoolId,
4172
+ "pool.getOracleState": getOracleState,
4173
+ "pool.getPool": getPool,
4174
+ "pool.getPoolMetadata": getPoolMetadata,
4175
+ "pool.getRiskParameters": getRiskParameters,
4176
+ "pool.getUtilization": getUtilization,
4177
+ "uniswap.checkRouterApproval": checkRouterApproval,
4178
+ "uniswap.quoteSwapExactInViaRouter": quoteSwapExactInViaRouter,
4179
+ "uniswap.quoteSwapExactOutViaRouter": quoteSwapExactOutViaRouter,
4180
+ "uniswap.resolveSwapRoute": resolveSwapRoute
4181
+ });
4182
+ var LOCAL_HANDLERS = Object.freeze({
4183
+ "collateral.depositFragment": depositFragment,
4184
+ "collateral.withdrawFragment": withdrawFragment,
4185
+ "collateral.withdrawWithPositionsFragment": withdrawWithPositionsFragment,
4186
+ "dynamicJobs.renderExecuteJob": renderExecuteJob,
4187
+ "erc20.approveFragment": approveFragment,
4188
+ "greeks.calculateAccountGreeksPure": calculateAccountGreeksPure,
4189
+ "greeks.calculatePositionGreeks": calculatePositionGreeks,
4190
+ "hypovault.fulfillDepositsFragment": fulfillDepositsFragment,
4191
+ "hypovault.fulfillWithdrawalsFragment": fulfillWithdrawalsFragment,
4192
+ "hypovault.manageCalldataParts": manageCalldataParts,
4193
+ "hypovault.manageFragment": manageFragment,
4194
+ "hypovault.wethDepositInnerCall": hypovaultWethDepositInnerCall,
4195
+ "hypovault.wethWithdrawInnerCall": hypovaultWethWithdrawInnerCall,
4196
+ "merkle.buildManageArgs": buildManageArgs,
4197
+ "merkle.findLeaf": findLeaf,
4198
+ "merkle.manageVaultWithVerificationFragment": manageVaultWithVerificationFragment,
4199
+ "panoptic.dispatchCalldataParts": dispatchCalldataParts,
4200
+ "panoptic.dispatchExplicitCalldataParts": dispatchExplicitCalldataParts,
4201
+ "panoptic.dispatchExplicitFragment": dispatchExplicitFragment,
4202
+ "panoptic.dispatchFragment": dispatchFragment,
4203
+ "permit2.approveFragment": approveFragment2,
4204
+ "pool.getPricesAtTick": getPricesAtTick,
4205
+ "pool.getTickSpacing": getTickSpacing,
4206
+ "uniswap.buildV3ExactInExecuteCalldataParts": buildV3ExactInExecuteCalldataParts,
4207
+ "uniswap.buildV3ExactInExecuteFragment": buildV3ExactInExecuteFragment,
4208
+ "weth.depositCalldataParts": depositCalldataParts,
4209
+ "weth.withdrawCalldataParts": withdrawCalldataParts
4210
+ });
4211
+ var HANDLERS = Object.freeze({
4212
+ ...RPC_HANDLERS,
4213
+ ...LOCAL_HANDLERS
4214
+ });
4215
+ var STABLE_PANOPTIC_METHOD_NAMES = Object.freeze(Object.keys(HANDLERS).sort());
4216
+ function getPanopticHandler(method) {
4217
+ return Object.prototype.hasOwnProperty.call(HANDLERS, method) ? HANDLERS[method] : void 0;
4218
+ }
4219
+ function getPanopticHandlerNames() {
4220
+ return [...STABLE_PANOPTIC_METHOD_NAMES].sort();
4221
+ }
4222
+ async function executePanopticHandler(input) {
4223
+ const runHandler = () => Promise.resolve(
4224
+ input.handler({
4225
+ deps: input.deps,
4226
+ method: input.method,
4227
+ request: input.request,
4228
+ options: input.options || {},
4229
+ operationOptions: input.operationOptions
4230
+ })
4231
+ );
4232
+ const rawResult = Object.prototype.hasOwnProperty.call(RPC_HANDLERS, input.method) ? await runPanopticOperation(`Panoptic handler ${input.method}`, runHandler, input.operationOptions) : await runHandler();
4233
+ const result = projectPanopticSerializableValue(rawResult, input.responseLimits, `${input.method} result`);
4234
+ return panopticSuccess(result);
4235
+ }
4236
+
4237
+ // src/internal/panopticRuntime.ts
4238
+ var PANOPTIC_RUNTIME_METHOD_NAMES = Object.freeze(getPanopticHandlerNames());
4239
+ var RENAMED_METHODS = /* @__PURE__ */ new Map([
4240
+ ["dynamicJobs.renderRegisteredExecuteJob", "dynamicJobs.renderExecuteJob"],
4241
+ ["hypovault.encodeFulfillDeposits", "hypovault.fulfillDepositsFragment"],
4242
+ ["hypovault.encodeFulfillWithdrawals", "hypovault.fulfillWithdrawalsFragment"],
4243
+ ["router.checkApproval", "uniswap.checkRouterApproval"],
4244
+ ["panoptic.dispatchArgs", "panoptic.dispatchCalldataParts"]
4245
+ ]);
4246
+ var UNSUPPORTED_PLANNED_METHODS = /* @__PURE__ */ new Map([
4247
+ ["greeks.getAccountGreeks", "requires a serializable storage snapshot DTO"],
4248
+ ["hypovault.resolveVaultHistoricalCandidatesByPool", "requires host-owned subgraph paging and reconciliation policy"],
4249
+ ["merkle.encodeManageVaultWithMerkleVerification", "requires Merkle artifact provenance and nested target policy"]
4250
+ ]);
4251
+ for (const method of PANOPTIC_RUNTIME_METHOD_NAMES) {
4252
+ if (!getPanopticHandler(method)) {
4253
+ throw new Error(`Panoptic stable runtime method is not backed by a handler: ${method}`);
4254
+ }
4255
+ }
4256
+ async function callNodePanoptic(method, request, options = {}) {
4257
+ const handler = getPanopticHandler(method);
4258
+ if (handler) {
4259
+ return executePanopticHandler({
4260
+ method,
4261
+ handler,
4262
+ request,
4263
+ deps: createPanopticDependencies(),
4264
+ options,
4265
+ operationOptions: options.operation
4266
+ });
4267
+ }
4268
+ if (isLegacyCalldataMethod(method)) {
4269
+ throw new Error(
4270
+ `Panoptic runtime method is not part of the stable DynamicJobs RuntimeAdapter API: ${method}. Use protocol fragment namespaces instead.`
4271
+ );
4272
+ }
4273
+ const renamedMethod = RENAMED_METHODS.get(method);
4274
+ if (renamedMethod) {
4275
+ throw new Error(
4276
+ `Panoptic runtime method has been renamed for the stable DynamicJobs RuntimeAdapter API: ${method}. Use ${renamedMethod}.`
4277
+ );
4278
+ }
4279
+ const unsupportedReason = UNSUPPORTED_PLANNED_METHODS.get(method);
4280
+ if (unsupportedReason) {
4281
+ throw new Error(
4282
+ `Panoptic runtime method is not part of the stable DynamicJobs RuntimeAdapter API: ${method} (${unsupportedReason}).`
4283
+ );
4284
+ }
4285
+ throw new Error(`Unsupported Panoptic runtime method: ${method}`);
4286
+ }
4287
+ function createNodePanopticAdapter(options = {}) {
4288
+ return (method, request) => callNodePanoptic(method, request, options);
4289
+ }
4290
+ function isLegacyCalldataMethod(method) {
4291
+ return method.startsWith("calldata.");
4292
+ }
4293
+
4294
+ // src/index.ts
4295
+ function loadWasmSync(input, imports = {}, options = {}) {
4296
+ return instantiate(new WebAssembly.Module(input), imports, {
4297
+ getFetch: getRuntimeFetch,
4298
+ getCcxt: getRuntimeCcxt,
4299
+ callPanoptic: createRuntimePanopticAdapter(options)
4300
+ });
4301
+ }
4302
+ async function loadWasm(input, imports = {}, options = {}) {
4303
+ const module = typeof input === "string" ? await compileFromString(input) : await WebAssembly.compile(input);
4304
+ return instantiate(module, imports, {
4305
+ getFetch: getRuntimeFetch,
4306
+ getCcxt: getRuntimeCcxt,
4307
+ callPanoptic: createRuntimePanopticAdapter(options)
4308
+ });
4309
+ }
4310
+ async function compileFromString(input) {
4311
+ if (!isNodeRuntime()) {
4312
+ return compileFromUrl(input);
4313
+ }
4314
+ if (isHttpUrl(input)) {
4315
+ return compileFromUrl(input);
4316
+ }
4317
+ const fs = await importRuntimeModule("fs/promises");
4318
+ return WebAssembly.compile(await fs.readFile(input));
4319
+ }
4320
+ async function compileFromUrl(url) {
4321
+ const fetchImpl = await getRuntimeFetch();
4322
+ const response = await fetchImpl(url);
4323
+ if (typeof WebAssembly.compileStreaming === "function") {
4324
+ try {
4325
+ return await WebAssembly.compileStreaming(Promise.resolve(response.clone()));
4326
+ } catch {
4327
+ }
4328
+ }
4329
+ return WebAssembly.compile(await response.arrayBuffer());
4330
+ }
4331
+ async function getRuntimeFetch() {
4332
+ if (typeof globalThis.fetch === "function") {
4333
+ return globalThis.fetch.bind(globalThis);
4334
+ }
4335
+ if (!isNodeRuntime()) {
4336
+ throw new Error("Fetch is not available in this browser runtime.");
4337
+ }
4338
+ throw new Error("Fetch is not available in this Node runtime. Node 18+ is required.");
4339
+ }
4340
+ async function getRuntimeCcxt() {
4341
+ if (isNodeRuntime()) {
4342
+ const ccxt2 = await importRuntimeModule("ccxt");
4343
+ return ccxt2.default ?? ccxt2;
4344
+ }
4345
+ const ccxt = globalThis.ccxt;
4346
+ if (!ccxt) {
4347
+ throw new Error("ccxt is not available in this browser runtime.");
4348
+ }
4349
+ return ccxt;
4350
+ }
4351
+ function createRuntimePanopticAdapter(options) {
4352
+ if (!isNodeRuntime()) {
4353
+ if (options.panoptic) {
4354
+ throw new Error("Panoptic runtime adapter is Node-only until browser support lands.");
4355
+ }
4356
+ return callBrowserPanoptic;
4357
+ }
4358
+ return createNodePanopticAdapter(options.panoptic);
779
4359
  }
780
4360
  function isNodeRuntime() {
781
4361
  return typeof process !== "undefined" && !!process.versions?.node;