@steerprotocol/app-loader 2.1.1 → 3.0.1

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.
@@ -0,0 +1,757 @@
1
+ // src/internal/instantiate.ts
2
+ import { ethers } from "ethers";
3
+
4
+ // src/timestring.ts
5
+ var DEFAULT_OPTS = {
6
+ hoursPerDay: 24,
7
+ daysPerWeek: 7,
8
+ weeksPerMonth: 4,
9
+ monthsPerYear: 12,
10
+ daysPerYear: 365.25
11
+ };
12
+ var UNIT_MAP = {
13
+ ms: ["ms", "milli", "millisecond", "milliseconds"],
14
+ s: ["s", "sec", "secs", "second", "seconds"],
15
+ m: ["m", "min", "mins", "minute", "minutes"],
16
+ h: ["h", "hr", "hrs", "hour", "hours"],
17
+ d: ["d", "day", "days"],
18
+ w: ["w", "week", "weeks"],
19
+ mth: ["mon", "mth", "mths", "month", "months"],
20
+ y: ["y", "yr", "yrs", "year", "years"]
21
+ };
22
+ function parseTimestring(value, returnUnit, opts) {
23
+ const options = Object.assign({}, DEFAULT_OPTS, opts || {});
24
+ let strValue;
25
+ if (typeof value === "number") {
26
+ strValue = parseInt(value.toString()) + "ms";
27
+ } else if (value.match(/^[-+]?[0-9.]+$/g)) {
28
+ strValue = parseInt(value) + "ms";
29
+ } else {
30
+ strValue = value;
31
+ }
32
+ let totalSeconds = 0;
33
+ const unitValues = getUnitValues(options);
34
+ const groups = strValue.toLowerCase().replace(/[^.\w+-]+/g, "").match(/[-+]?[0-9.]+[a-z]+/g);
35
+ if (groups === null) {
36
+ throw new Error(`The value [${strValue}] could not be parsed by timestring`);
37
+ }
38
+ groups.forEach((group) => {
39
+ const valMatch = group.match(/[0-9.]+/g);
40
+ const unitMatch = group.match(/[a-z]+/g);
41
+ if (valMatch && unitMatch) {
42
+ const val = parseFloat(valMatch[0]);
43
+ const unit = unitMatch[0];
44
+ totalSeconds += getSeconds(val, unit, unitValues);
45
+ }
46
+ });
47
+ if (returnUnit) {
48
+ return convert(totalSeconds, returnUnit, unitValues);
49
+ }
50
+ return totalSeconds;
51
+ }
52
+ function getUnitValues(opts) {
53
+ const unitValues = {
54
+ ms: 1e-3,
55
+ s: 1,
56
+ m: 60,
57
+ h: 3600,
58
+ d: 0,
59
+ w: 0,
60
+ mth: 0,
61
+ y: 0
62
+ };
63
+ unitValues.d = opts.hoursPerDay * unitValues.h;
64
+ unitValues.w = opts.daysPerWeek * unitValues.d;
65
+ unitValues.mth = opts.daysPerYear / opts.monthsPerYear * unitValues.d;
66
+ unitValues.y = opts.daysPerYear * unitValues.d;
67
+ return unitValues;
68
+ }
69
+ function getUnitKey(unit) {
70
+ for (const key of Object.keys(UNIT_MAP)) {
71
+ if (UNIT_MAP[key].indexOf(unit) > -1) {
72
+ return key;
73
+ }
74
+ }
75
+ throw new Error(`The unit [${unit}] is not supported by timestring`);
76
+ }
77
+ function getSeconds(value, unit, unitValues) {
78
+ return value * unitValues[getUnitKey(unit)];
79
+ }
80
+ function convert(value, unit, unitValues) {
81
+ return value / unitValues[getUnitKey(unit)];
82
+ }
83
+
84
+ // src/Candle.ts
85
+ var Candle = class {
86
+ /**
87
+ * Creates a candle instance.
88
+ * @param timestamp - Candle open timestamp in milliseconds.
89
+ * @param high - Highest traded price.
90
+ * @param low - Lowest traded price.
91
+ * @param open - Opening price.
92
+ * @param close - Closing price.
93
+ * @param volume - Total traded volume.
94
+ */
95
+ constructor(timestamp, high, low, open, close, volume) {
96
+ this.timestamp = timestamp;
97
+ this.high = high;
98
+ this.low = low;
99
+ this.open = open;
100
+ this.close = close;
101
+ this.volume = volume;
102
+ }
103
+ /**
104
+ * Serializes the candle as JSON.
105
+ * @returns The candle as a JSON string.
106
+ */
107
+ toString() {
108
+ return JSON.stringify(this);
109
+ }
110
+ };
111
+ function generateCandles(data, candleSize) {
112
+ const candleWidth = parseTimestring(candleSize, "ms", {});
113
+ if (data.length === 0) {
114
+ throw new Error("Input data is empty");
115
+ }
116
+ const _data = data.map((point) => {
117
+ return Object.assign(Object.assign({}, point), {
118
+ // Older inputs may still provide 10-digit second timestamps instead of milliseconds.
119
+ timestamp: point.timestamp && String(point.timestamp).length == 10 ? point.timestamp * 1e3 : point.timestamp
120
+ });
121
+ });
122
+ if (_data[0] === void 0 || Object.keys(_data[0]).length === 0) {
123
+ return [];
124
+ }
125
+ const ohlcvData = [];
126
+ let i = 0;
127
+ let currentTimestamp = Math.floor(_data[0].timestamp / candleWidth) * candleWidth;
128
+ let open = _data[0].price;
129
+ let high = _data[0].price;
130
+ let low = _data[0].price;
131
+ let close = _data[0].price;
132
+ let volume = 0;
133
+ while (i < _data.length) {
134
+ open = close;
135
+ high = close;
136
+ low = close;
137
+ volume = 0;
138
+ let innerI = i;
139
+ while (innerI < _data.length && _data[innerI].timestamp < currentTimestamp + candleWidth) {
140
+ open = innerI === 0 ? _data[innerI].price : open;
141
+ high = Math.max(high, _data[innerI].price);
142
+ low = Math.min(low, _data[innerI].price);
143
+ close = _data[innerI].price;
144
+ volume += _data[innerI].volume;
145
+ innerI++;
146
+ }
147
+ ohlcvData.push({
148
+ timestamp: currentTimestamp,
149
+ high,
150
+ low,
151
+ open,
152
+ close,
153
+ volume
154
+ });
155
+ currentTimestamp += candleWidth;
156
+ i = innerI;
157
+ }
158
+ return ohlcvData;
159
+ }
160
+
161
+ // src/RawTradeData.ts
162
+ var RawTradeData = class {
163
+ /**
164
+ * Creates a raw trade data point.
165
+ * @param timestamp - Trade timestamp.
166
+ * @param price - Trade price.
167
+ * @param volume - Trade volume.
168
+ */
169
+ constructor(timestamp, price, volume) {
170
+ this.timestamp = timestamp;
171
+ this.price = price;
172
+ this.volume = volume;
173
+ }
174
+ };
175
+
176
+ // src/internal/instantiate.ts
177
+ function instantiate(module, imports = {}, runtime = {}) {
178
+ let WASM_MEMORY;
179
+ let WASM_EXPORTS;
180
+ let WASM_DV;
181
+ let ASYNCIFY_PTR = 0;
182
+ let ASYNCIFY_MEM;
183
+ let ASYNCIFY_INITIALIZED = false;
184
+ let fetchFn = null;
185
+ let ccxtFn = null;
186
+ let detachedValue = null;
187
+ let executeInFlight = false;
188
+ const pinScopes = [];
189
+ const adaptedImports = Object.assign(
190
+ {
191
+ console: {
192
+ /**
193
+ * Logs a lifted AssemblyScript string.
194
+ * @param text - Pointer to the message string.
195
+ */
196
+ log(text) {
197
+ console.log(__liftString(text));
198
+ }
199
+ },
200
+ ethers: {
201
+ /**
202
+ * Hashes a lifted string with `keccak256`.
203
+ * @param str_ptr - Pointer to the input string.
204
+ * @returns Pointer to the hashed string result.
205
+ */
206
+ keccak256_str(str_ptr) {
207
+ const str = __liftString(str_ptr);
208
+ const hash = ethers.keccak256(str);
209
+ return withAutoPinScope(() => __lowerString(hash));
210
+ },
211
+ /**
212
+ * Hashes a lifted buffer with `keccak256`.
213
+ * @param buf_ptr - Pointer to the input buffer.
214
+ * @returns Pointer to the hashed string result.
215
+ */
216
+ keccak256_buf(buf_ptr) {
217
+ const buf = __liftBuffer(buf_ptr);
218
+ const hash = ethers.keccak256(new Uint8Array(buf));
219
+ return withAutoPinScope(() => __lowerString(hash));
220
+ }
221
+ },
222
+ // @ts-ignore
223
+ env: {
224
+ /**
225
+ * Raises a JavaScript error for an AssemblyScript abort.
226
+ * @param message - Pointer to the abort message.
227
+ * @param fileName - Pointer to the source filename.
228
+ * @param lineNumber - Source line number.
229
+ * @param columnNumber - Source column number.
230
+ */
231
+ abort(message, fileName, lineNumber, columnNumber) {
232
+ (() => {
233
+ throw Error(`${__liftString(message)} in ${__liftString(fileName)}:${lineNumber}:${columnNumber}`);
234
+ })();
235
+ },
236
+ /**
237
+ * Initializes Asyncify bookkeeping for host callbacks.
238
+ * @param frame_ptr - Asyncify frame pointer.
239
+ * @param stack_ptr - Asyncify stack pointer.
240
+ */
241
+ _initAsyncify(frame_ptr, stack_ptr) {
242
+ if (!WASM_EXPORTS["asyncify_get_state"])
243
+ throw new Error(
244
+ "Asyncify initialized, but not enabled when run! Compile with the --runPasses asyncify flag or asyncify-shim transform!"
245
+ );
246
+ if (ASYNCIFY_INITIALIZED) return;
247
+ ASYNCIFY_PTR = frame_ptr;
248
+ ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;
249
+ ASYNCIFY_MEM[ASYNCIFY_PTR + 4 >> 2] = stack_ptr;
250
+ ASYNCIFY_INITIALIZED = true;
251
+ },
252
+ /**
253
+ * Aggregates lifted trade data into candles.
254
+ * @param data - Pointer to the serialized trade array.
255
+ * @param candleSize - Pointer to the candle size string.
256
+ * @returns Pointer to the serialized candle array.
257
+ */
258
+ generateCandles(data, candleSize) {
259
+ const _data = __liftString(data) || "[]";
260
+ const _candleSize = __liftString(candleSize) || "69m";
261
+ const candles = generateCandles(JSON.parse(_data), _candleSize);
262
+ return withAutoPinScope(() => __lowerString(JSON.stringify(candles)));
263
+ },
264
+ /**
265
+ * Logs a lifted AssemblyScript string.
266
+ * @param text - Pointer to the message string.
267
+ */
268
+ "console.log": (text) => {
269
+ console.log(__liftString(text));
270
+ },
271
+ /**
272
+ * Schedules an async OHLCV request for asyncified execution.
273
+ * @param exchangeId - Pointer to the exchange id string.
274
+ * @param symbol - Pointer to the market symbol string.
275
+ * @param timeframe - Pointer to the timeframe string.
276
+ * @param limit - Maximum number of rows.
277
+ * @param since - Optional start timestamp.
278
+ * @returns Pointer to the rewound OHLCV matrix when replaying.
279
+ */
280
+ ccxt_fetchOHLCV: (exchangeId, symbol, timeframe, limit, since) => {
281
+ const currentState = WASM_EXPORTS.asyncify_get_state();
282
+ if (currentState === 2 /* Rewinding */) {
283
+ WASM_EXPORTS.asyncify_stop_rewind();
284
+ const ptr = __lowerStaticArray(
285
+ (pointer, value) => {
286
+ __setU32(pointer, __lowerStaticArray(__setF64, 7, 3, value, Float64Array));
287
+ },
288
+ 8,
289
+ 2,
290
+ detachedValue
291
+ );
292
+ return ptr;
293
+ }
294
+ const _exchange = __liftString(exchangeId);
295
+ const _symbol = __liftString(symbol);
296
+ const _timeframe = __liftString(timeframe);
297
+ ccxtFn = async () => {
298
+ if (!_exchange || !_symbol || !_timeframe)
299
+ throw new Error("Exchange, Symbol, or Timeframe not provided when fetching OHCLV data.");
300
+ const ccxt = await getCcxtOrThrow(runtime);
301
+ const data = await new ccxt[_exchange]({
302
+ apiKey: "",
303
+ secret: ""
304
+ }).fetchOHLCV(_symbol, _timeframe, since, limit);
305
+ return data;
306
+ };
307
+ WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);
308
+ }
309
+ },
310
+ "as-fetch": {
311
+ /**
312
+ * Initializes Asyncify bookkeeping for as-fetch host calls.
313
+ * @param frame_ptr - Asyncify frame pointer.
314
+ * @param stack_ptr - Asyncify stack pointer.
315
+ */
316
+ _initAsyncify(frame_ptr, stack_ptr) {
317
+ if (!WASM_EXPORTS["asyncify_get_state"])
318
+ throw new Error(
319
+ "Asyncify initialized, but not enabled when run! Compile with the --runPasses asyncify flag or asyncify-shim transform!"
320
+ );
321
+ if (ASYNCIFY_INITIALIZED) return;
322
+ ASYNCIFY_PTR = frame_ptr;
323
+ ASYNCIFY_MEM[ASYNCIFY_PTR >> 2] = ASYNCIFY_PTR + 8;
324
+ ASYNCIFY_MEM[ASYNCIFY_PTR + 4 >> 2] = stack_ptr;
325
+ ASYNCIFY_INITIALIZED = true;
326
+ },
327
+ /**
328
+ * Executes a synchronous asyncified POST request.
329
+ * @param url - Pointer to the request URL.
330
+ * @param mode - Numeric fetch mode.
331
+ * @param headers - Pointer to the header array.
332
+ * @param body - Pointer to the request body.
333
+ * @returns Pointer to the response body when replaying.
334
+ */
335
+ _fetchPOSTSync(url, mode, headers, body) {
336
+ const currentState = WASM_EXPORTS.asyncify_get_state();
337
+ if (currentState === 2 /* Rewinding */) {
338
+ WASM_EXPORTS.asyncify_stop_rewind();
339
+ const ptr = __lowerBuffer(detachedValue);
340
+ detachedValue = null;
341
+ return ptr;
342
+ }
343
+ fetchFn = async () => {
344
+ const fetchImpl = await getFetchOrThrow(runtime);
345
+ const res = await fetchImpl(__liftString(url) || "", {
346
+ method: "POST",
347
+ mode: modeToString(mode) || "cors",
348
+ headers: __liftArray(
349
+ (pointer) => __liftArray((pointer2) => __liftString(__getU32(pointer2)), 2, __getU32(pointer)),
350
+ 2,
351
+ headers
352
+ ) || [],
353
+ body: __liftBuffer(body)
354
+ });
355
+ const value = await res.arrayBuffer();
356
+ return value;
357
+ };
358
+ WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);
359
+ },
360
+ /**
361
+ * Executes a synchronous asyncified GET request.
362
+ * @param url - Pointer to the request URL.
363
+ * @param mode - Numeric fetch mode.
364
+ * @param headers - Pointer to the header array.
365
+ * @returns Pointer to the response body when replaying.
366
+ */
367
+ _fetchGETSync(url, mode, headers) {
368
+ const currentState = WASM_EXPORTS.asyncify_get_state();
369
+ if (currentState === 2 /* Rewinding */) {
370
+ WASM_EXPORTS.asyncify_stop_rewind();
371
+ const ptr = __lowerBuffer(detachedValue);
372
+ detachedValue = null;
373
+ return ptr;
374
+ }
375
+ fetchFn = async () => {
376
+ const fetchImpl = await getFetchOrThrow(runtime);
377
+ const res = await fetchImpl(__liftString(url) || "", {
378
+ method: "GET",
379
+ mode: modeToString(mode) || "cors",
380
+ headers: __liftArray(
381
+ (pointer) => __liftArray((pointer2) => __liftString(__getU32(pointer2)), 2, __getU32(pointer)),
382
+ 2,
383
+ headers
384
+ ) || []
385
+ });
386
+ const value = await res.arrayBuffer();
387
+ return value;
388
+ };
389
+ WASM_EXPORTS.asyncify_start_unwind(ASYNCIFY_PTR);
390
+ },
391
+ /**
392
+ * Executes an asynchronous GET request and forwards the response to wasm.
393
+ * @param url - Pointer to the request URL.
394
+ * @param mode - Numeric fetch mode.
395
+ * @param headers - Pointer to the header array.
396
+ * @param callbackID - Wasm callback identifier.
397
+ */
398
+ _fetchGET(url, mode, headers, callbackID) {
399
+ void (async () => {
400
+ try {
401
+ const fetchImpl = await getFetchOrThrow(runtime);
402
+ const res = await fetchImpl(__liftString(url) || "", {
403
+ method: "GET",
404
+ mode: modeToString(mode) || "cors",
405
+ headers: __liftArray(
406
+ (pointer) => __liftArray((pointer2) => __liftString(__getU32(pointer2)), 2, __getU32(pointer)),
407
+ 2,
408
+ headers
409
+ ) || []
410
+ });
411
+ const body = await res.arrayBuffer();
412
+ WASM_EXPORTS.responseHandler(body, res.status, res.redirected ? 1 : 0, callbackID);
413
+ } catch (error) {
414
+ console.error(error);
415
+ }
416
+ })();
417
+ },
418
+ /**
419
+ * Executes an asynchronous POST request and forwards the response to wasm.
420
+ * @param url - Pointer to the request URL.
421
+ * @param mode - Numeric fetch mode.
422
+ * @param headers - Pointer to the header array.
423
+ * @param body - Request body.
424
+ * @param callbackID - Wasm callback identifier.
425
+ */
426
+ _fetchPOST(url, mode, headers, body, callbackID) {
427
+ void (async () => {
428
+ try {
429
+ const fetchImpl = await getFetchOrThrow(runtime);
430
+ const res = await fetchImpl(__liftString(url) || "", {
431
+ method: "POST",
432
+ mode: modeToString(mode) || "cors",
433
+ body,
434
+ headers: __liftArray(
435
+ (pointer) => __liftArray((pointer2) => __liftString(__getU32(pointer2)), 2, __getU32(pointer)),
436
+ 2,
437
+ headers
438
+ ) || []
439
+ });
440
+ const responseBody = await res.arrayBuffer();
441
+ WASM_EXPORTS.responseHandler(responseBody, res.status, res.redirected ? 1 : 0, callbackID);
442
+ } catch (error) {
443
+ console.error(error);
444
+ }
445
+ })();
446
+ }
447
+ }
448
+ },
449
+ imports
450
+ );
451
+ const mod = new WebAssembly.Instance(module, adaptedImports);
452
+ WASM_EXPORTS = mod.exports;
453
+ WASM_MEMORY = WASM_EXPORTS.memory || adaptedImports.env.memory;
454
+ ASYNCIFY_MEM = new Uint32Array(WASM_MEMORY.buffer);
455
+ const handledExports = Object.setPrototypeOf(
456
+ {
457
+ /**
458
+ * Forwards an HTTP response body into the wasm export.
459
+ * @param body - Response body.
460
+ * @param statusCode - HTTP status code.
461
+ * @param redirected - Whether the request redirected.
462
+ * @param callbackID - Wasm callback identifier.
463
+ */
464
+ responseHandler(body, statusCode, redirected, callbackID) {
465
+ if (!WASM_EXPORTS["responseHandler"])
466
+ throw new Error(
467
+ 'Unable to call .responseHandler on wasm module. Add the line export { responseHandler } from "as-fetch/assembly" to your entry file.'
468
+ );
469
+ withPinScope(() => {
470
+ WASM_EXPORTS.responseHandler(__lowerBuffer(body), statusCode, redirected ? 1 : 0, callbackID);
471
+ });
472
+ },
473
+ /**
474
+ * Initializes the wasm module with a JSON configuration payload.
475
+ * @param config - Serialized connector configuration.
476
+ * @returns `true` when initialization succeeds.
477
+ */
478
+ initialize(config) {
479
+ if (!WASM_EXPORTS["initialize"])
480
+ throw new Error("Unable to call .initialize on wasm module. Are you sure this is a data connector?");
481
+ try {
482
+ withPinScope(() => {
483
+ WASM_EXPORTS.initialize(__lowerString(config));
484
+ });
485
+ return true;
486
+ } catch (e) {
487
+ console.error(e);
488
+ return false;
489
+ }
490
+ },
491
+ /**
492
+ * Executes the wasm module, replaying arguments across asyncify rewinds.
493
+ * @param params - Logical execute arguments.
494
+ * @returns The lifted execute result.
495
+ */
496
+ async execute(...params) {
497
+ if (!WASM_EXPORTS["execute"])
498
+ throw new Error("Unable to call .execute on wasm module. Are you sure this is a data connector?");
499
+ if (executeInFlight) {
500
+ throw new Error("Concurrent execute calls are not supported on the same wasm instance.");
501
+ }
502
+ executeInFlight = true;
503
+ const replayArgs = snapshotLogicalArgs(params);
504
+ try {
505
+ let result;
506
+ try {
507
+ result = executeWithReplayArgs(replayArgs);
508
+ } catch (error) {
509
+ if (params.length !== 0) {
510
+ throw error;
511
+ }
512
+ replayArgs.splice(0, replayArgs.length, "");
513
+ result = executeWithReplayArgs(replayArgs);
514
+ }
515
+ if (ASYNCIFY_INITIALIZED) {
516
+ while (WASM_EXPORTS.asyncify_get_state() === 1 /* Unwinding */) {
517
+ WASM_EXPORTS.asyncify_stop_unwind();
518
+ if (fetchFn) {
519
+ const pendingFetch = fetchFn;
520
+ fetchFn = null;
521
+ detachedValue = await pendingFetch();
522
+ }
523
+ if (ccxtFn) {
524
+ const pendingCcxt = ccxtFn;
525
+ ccxtFn = null;
526
+ detachedValue = await pendingCcxt();
527
+ }
528
+ WASM_EXPORTS.asyncify_start_rewind(ASYNCIFY_PTR);
529
+ result = executeWithReplayArgs(replayArgs);
530
+ }
531
+ }
532
+ return __liftString(result);
533
+ } finally {
534
+ fetchFn = null;
535
+ ccxtFn = null;
536
+ detachedValue = null;
537
+ executeInFlight = false;
538
+ }
539
+ },
540
+ /**
541
+ * Reads the connector configuration schema from wasm.
542
+ * @returns The lifted configuration payload.
543
+ */
544
+ config() {
545
+ if (!WASM_EXPORTS["config"])
546
+ throw new Error("Unable to call .config on wasm module. Are you sure this is a data connector?");
547
+ return withPinScope(() => __liftString(WASM_EXPORTS.config()));
548
+ },
549
+ /**
550
+ * Reads the connector transform from wasm.
551
+ * @returns The lifted transform payload.
552
+ */
553
+ transform() {
554
+ if (!WASM_EXPORTS["transform"])
555
+ throw new Error("Unable to call .transform on wasm module. Are you sure this is a data connector?");
556
+ return withPinScope(() => __liftString(WASM_EXPORTS.transform()));
557
+ },
558
+ /**
559
+ * Resets wasm module state when supported.
560
+ */
561
+ reset() {
562
+ if (WASM_EXPORTS["reset"]) WASM_EXPORTS.reset();
563
+ }
564
+ },
565
+ WASM_EXPORTS
566
+ );
567
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
568
+ function __lower(val) {
569
+ if (typeof val === "number") {
570
+ return val;
571
+ } else if (typeof val === "string") {
572
+ return __lowerString(val);
573
+ } else if (val instanceof ArrayBuffer) {
574
+ return __lowerBuffer(val);
575
+ } else {
576
+ return 0;
577
+ }
578
+ }
579
+ function lowerArgs(values) {
580
+ const loweredArgs = new Array(values.length);
581
+ for (let i = 0; i < values.length; i++) {
582
+ loweredArgs[i] = __lower(values[i]);
583
+ }
584
+ return loweredArgs;
585
+ }
586
+ function snapshotLogicalArgs(values) {
587
+ return values.map((value) => {
588
+ if (value instanceof ArrayBuffer) {
589
+ return value.slice(0);
590
+ }
591
+ return value;
592
+ });
593
+ }
594
+ function executeWithReplayArgs(values) {
595
+ return withPinScope(() => WASM_EXPORTS.execute(...lowerArgs(values)));
596
+ }
597
+ function withPinScope(fn) {
598
+ pinScopes.push([]);
599
+ try {
600
+ return fn();
601
+ } finally {
602
+ const scope = pinScopes.pop() || [];
603
+ for (let i = scope.length - 1; i >= 0; i--) {
604
+ WASM_EXPORTS.__unpin(scope[i]);
605
+ }
606
+ }
607
+ }
608
+ function withAutoPinScope(fn) {
609
+ if (pinScopes.length > 0) {
610
+ return fn();
611
+ }
612
+ return withPinScope(fn);
613
+ }
614
+ function trackPinnedPointer(ptr) {
615
+ const scope = pinScopes[pinScopes.length - 1];
616
+ if (scope) {
617
+ scope.push(ptr);
618
+ }
619
+ return ptr;
620
+ }
621
+ function __liftString(ptr) {
622
+ if (!ptr) return null;
623
+ const end = ptr + new Uint32Array(WASM_MEMORY.buffer)[ptr - 4 >>> 2] >>> 1;
624
+ const memoryU16 = new Uint16Array(WASM_MEMORY.buffer);
625
+ let start = ptr >>> 1;
626
+ let string = "";
627
+ while (end - start > 1024) string += String.fromCharCode(...memoryU16.subarray(start, start += 1024));
628
+ return string + String.fromCharCode(...memoryU16.subarray(start, end));
629
+ }
630
+ function __lowerString(value) {
631
+ if (value == null) return 0;
632
+ const length = value.length;
633
+ const ptr = trackPinnedPointer(WASM_EXPORTS.__pin(WASM_EXPORTS.__new(length << 1, 2) >>> 0));
634
+ const memoryU16 = new Uint16Array(WASM_MEMORY.buffer);
635
+ for (let i = 0; i < length; ++i) memoryU16[(ptr >>> 1) + i] = value.charCodeAt(i);
636
+ return ptr;
637
+ }
638
+ function __liftBuffer(ptr) {
639
+ if (!ptr) return null;
640
+ return WASM_MEMORY.buffer.slice(ptr, ptr + new Uint32Array(WASM_MEMORY.buffer)[ptr - 4 >>> 2]);
641
+ }
642
+ function __lowerBuffer(value) {
643
+ if (value == null) return 0;
644
+ const ptr = trackPinnedPointer(WASM_EXPORTS.__pin(WASM_EXPORTS.__new(value.byteLength, 1) >>> 0));
645
+ new Uint8Array(WASM_MEMORY.buffer).set(new Uint8Array(value), ptr);
646
+ return ptr;
647
+ }
648
+ function __liftArray(liftElement, align, ptr) {
649
+ if (!ptr) return null;
650
+ const dataStart = __getU32(ptr + 4);
651
+ const length = WASM_DV.getUint32(ptr + 12, true);
652
+ const values = new Array(length);
653
+ for (let i = 0; i < length; ++i) values[i] = liftElement(dataStart + (i << align >>> 0));
654
+ return values;
655
+ }
656
+ function __lowerStaticArray(lowerElement, id, align, values, typedConstructor = null) {
657
+ if (values == null) return 0;
658
+ const length = values.length;
659
+ const buffer = trackPinnedPointer(WASM_EXPORTS.__pin(WASM_EXPORTS.__new(length << align, id)) >>> 0) >>> 0;
660
+ if (typedConstructor) {
661
+ new typedConstructor(WASM_MEMORY.buffer, buffer, length).set(values);
662
+ } else {
663
+ for (let i = 0; i < length; i++) lowerElement(buffer + (i << align >>> 0), values[i]);
664
+ }
665
+ return buffer;
666
+ }
667
+ function __setU32(ptr, value) {
668
+ try {
669
+ WASM_DV.setUint32(ptr, value, true);
670
+ } catch {
671
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
672
+ WASM_DV.setUint32(ptr, value, true);
673
+ }
674
+ }
675
+ function __setF64(ptr, value) {
676
+ try {
677
+ WASM_DV.setFloat64(ptr, value, true);
678
+ } catch {
679
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
680
+ WASM_DV.setFloat64(ptr, value, true);
681
+ }
682
+ }
683
+ function __getU32(ptr) {
684
+ try {
685
+ return WASM_DV.getUint32(ptr, true);
686
+ } catch {
687
+ WASM_DV = new DataView(WASM_MEMORY.buffer);
688
+ return WASM_DV.getUint32(ptr, true);
689
+ }
690
+ }
691
+ return handledExports;
692
+ }
693
+ async function getFetchOrThrow(runtime) {
694
+ if (!runtime.getFetch) {
695
+ throw new Error("Fetch is not available in this runtime.");
696
+ }
697
+ return runtime.getFetch();
698
+ }
699
+ async function getCcxtOrThrow(runtime) {
700
+ if (!runtime.getCcxt) {
701
+ throw new Error("ccxt is not available in this runtime.");
702
+ }
703
+ return runtime.getCcxt();
704
+ }
705
+ function modeToString(mode) {
706
+ if (mode == 1) return "cors";
707
+ if (mode == 2) return "no-cors";
708
+ if (mode == 3) return "same-origin";
709
+ if (mode == 4) return "navigate";
710
+ return null;
711
+ }
712
+
713
+ // src/browser.ts
714
+ function loadWasmSync(input, imports = {}) {
715
+ return instantiate(new WebAssembly.Module(input), imports, {
716
+ getFetch: getBrowserFetch,
717
+ getCcxt: getBrowserCcxt
718
+ });
719
+ }
720
+ async function loadWasm(input, imports = {}) {
721
+ const module = typeof input === "string" ? await compileFromUrl(input) : await WebAssembly.compile(input);
722
+ return instantiate(module, imports, {
723
+ getFetch: getBrowserFetch,
724
+ getCcxt: getBrowserCcxt
725
+ });
726
+ }
727
+ async function compileFromUrl(url) {
728
+ const fetchImpl = await getBrowserFetch();
729
+ const response = await fetchImpl(url);
730
+ if (typeof WebAssembly.compileStreaming === "function") {
731
+ try {
732
+ return await WebAssembly.compileStreaming(Promise.resolve(response.clone()));
733
+ } catch {
734
+ }
735
+ }
736
+ return WebAssembly.compile(await response.arrayBuffer());
737
+ }
738
+ async function getBrowserFetch() {
739
+ if (typeof globalThis.fetch !== "function") {
740
+ throw new Error("Fetch is not available in this browser runtime.");
741
+ }
742
+ return globalThis.fetch.bind(globalThis);
743
+ }
744
+ async function getBrowserCcxt() {
745
+ const ccxt = globalThis.ccxt;
746
+ if (!ccxt) {
747
+ throw new Error("ccxt is not available in this browser runtime.");
748
+ }
749
+ return ccxt;
750
+ }
751
+ export {
752
+ Candle,
753
+ RawTradeData,
754
+ loadWasm,
755
+ loadWasmSync
756
+ };
757
+ //# sourceMappingURL=browser.mjs.map