@streamflow/common 9.0.3 → 10.0.0-alpha.p313.3ce4d29

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.
@@ -1,13 +1,258 @@
1
1
  'use strict';
2
2
 
3
- require('@solana/web3.js');
3
+ var splToken = require('@solana/spl-token');
4
+ var web3_js = require('@solana/web3.js');
5
+ var bs58 = require('bs58');
4
6
  var BN = require('bn.js');
7
+ var buffer = require('buffer');
5
8
 
6
9
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
7
10
 
11
+ var bs58__default = /*#__PURE__*/_interopDefault(bs58);
8
12
  var BN__default = /*#__PURE__*/_interopDefault(BN);
9
13
 
10
- // types.ts
14
+ var __create = Object.create;
15
+ var __defProp = Object.defineProperty;
16
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
17
+ var __getOwnPropNames = Object.getOwnPropertyNames;
18
+ var __getProtoOf = Object.getPrototypeOf;
19
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
20
+ var __typeError = (msg) => {
21
+ throw TypeError(msg);
22
+ };
23
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
24
+ var __commonJS = (cb, mod) => function __require() {
25
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
26
+ };
27
+ var __copyProps = (to, from, except, desc) => {
28
+ if (from && typeof from === "object" || typeof from === "function") {
29
+ for (let key of __getOwnPropNames(from))
30
+ if (!__hasOwnProp.call(to, key) && key !== except)
31
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
32
+ }
33
+ return to;
34
+ };
35
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
36
+ // If the importer is in node compatibility mode or this is not an ESM
37
+ // file that has been converted to a CommonJS file using a Babel-
38
+ // compatible transform (i.e. "__esModule" has not been set), then set
39
+ // "default" to the CommonJS "module.exports" for node compatibility.
40
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
41
+ mod
42
+ ));
43
+ var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
44
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
45
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
46
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
47
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
48
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
49
+ var __privateWrapper = (obj, member, setter, getter) => ({
50
+ set _(value) {
51
+ __privateSet(obj, member, value);
52
+ },
53
+ get _() {
54
+ return __privateGet(obj, member, getter);
55
+ }
56
+ });
57
+
58
+ // ../../node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.js
59
+ var require_eventemitter3 = __commonJS({
60
+ "../../node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.js"(exports, module) {
61
+ var has = Object.prototype.hasOwnProperty;
62
+ var prefix2 = "~";
63
+ function Events() {
64
+ }
65
+ if (Object.create) {
66
+ Events.prototype = /* @__PURE__ */ Object.create(null);
67
+ if (!new Events().__proto__) prefix2 = false;
68
+ }
69
+ function EE(fn, context, once) {
70
+ this.fn = fn;
71
+ this.context = context;
72
+ this.once = once || false;
73
+ }
74
+ function addListener(emitter, event, fn, context, once) {
75
+ if (typeof fn !== "function") {
76
+ throw new TypeError("The listener must be a function");
77
+ }
78
+ var listener = new EE(fn, context || emitter, once), evt = prefix2 ? prefix2 + event : event;
79
+ if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
80
+ else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
81
+ else emitter._events[evt] = [emitter._events[evt], listener];
82
+ return emitter;
83
+ }
84
+ function clearEvent(emitter, evt) {
85
+ if (--emitter._eventsCount === 0) emitter._events = new Events();
86
+ else delete emitter._events[evt];
87
+ }
88
+ function EventEmitter2() {
89
+ this._events = new Events();
90
+ this._eventsCount = 0;
91
+ }
92
+ EventEmitter2.prototype.eventNames = function eventNames() {
93
+ var names = [], events, name;
94
+ if (this._eventsCount === 0) return names;
95
+ for (name in events = this._events) {
96
+ if (has.call(events, name)) names.push(prefix2 ? name.slice(1) : name);
97
+ }
98
+ if (Object.getOwnPropertySymbols) {
99
+ return names.concat(Object.getOwnPropertySymbols(events));
100
+ }
101
+ return names;
102
+ };
103
+ EventEmitter2.prototype.listeners = function listeners(event) {
104
+ var evt = prefix2 ? prefix2 + event : event, handlers = this._events[evt];
105
+ if (!handlers) return [];
106
+ if (handlers.fn) return [handlers.fn];
107
+ for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
108
+ ee[i] = handlers[i].fn;
109
+ }
110
+ return ee;
111
+ };
112
+ EventEmitter2.prototype.listenerCount = function listenerCount(event) {
113
+ var evt = prefix2 ? prefix2 + event : event, listeners = this._events[evt];
114
+ if (!listeners) return 0;
115
+ if (listeners.fn) return 1;
116
+ return listeners.length;
117
+ };
118
+ EventEmitter2.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
119
+ var evt = prefix2 ? prefix2 + event : event;
120
+ if (!this._events[evt]) return false;
121
+ var listeners = this._events[evt], len = arguments.length, args, i;
122
+ if (listeners.fn) {
123
+ if (listeners.once) this.removeListener(event, listeners.fn, void 0, true);
124
+ switch (len) {
125
+ case 1:
126
+ return listeners.fn.call(listeners.context), true;
127
+ case 2:
128
+ return listeners.fn.call(listeners.context, a1), true;
129
+ case 3:
130
+ return listeners.fn.call(listeners.context, a1, a2), true;
131
+ case 4:
132
+ return listeners.fn.call(listeners.context, a1, a2, a3), true;
133
+ case 5:
134
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
135
+ case 6:
136
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
137
+ }
138
+ for (i = 1, args = new Array(len - 1); i < len; i++) {
139
+ args[i - 1] = arguments[i];
140
+ }
141
+ listeners.fn.apply(listeners.context, args);
142
+ } else {
143
+ var length = listeners.length, j;
144
+ for (i = 0; i < length; i++) {
145
+ if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true);
146
+ switch (len) {
147
+ case 1:
148
+ listeners[i].fn.call(listeners[i].context);
149
+ break;
150
+ case 2:
151
+ listeners[i].fn.call(listeners[i].context, a1);
152
+ break;
153
+ case 3:
154
+ listeners[i].fn.call(listeners[i].context, a1, a2);
155
+ break;
156
+ case 4:
157
+ listeners[i].fn.call(listeners[i].context, a1, a2, a3);
158
+ break;
159
+ default:
160
+ if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) {
161
+ args[j - 1] = arguments[j];
162
+ }
163
+ listeners[i].fn.apply(listeners[i].context, args);
164
+ }
165
+ }
166
+ }
167
+ return true;
168
+ };
169
+ EventEmitter2.prototype.on = function on(event, fn, context) {
170
+ return addListener(this, event, fn, context, false);
171
+ };
172
+ EventEmitter2.prototype.once = function once(event, fn, context) {
173
+ return addListener(this, event, fn, context, true);
174
+ };
175
+ EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once) {
176
+ var evt = prefix2 ? prefix2 + event : event;
177
+ if (!this._events[evt]) return this;
178
+ if (!fn) {
179
+ clearEvent(this, evt);
180
+ return this;
181
+ }
182
+ var listeners = this._events[evt];
183
+ if (listeners.fn) {
184
+ if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
185
+ clearEvent(this, evt);
186
+ }
187
+ } else {
188
+ for (var i = 0, events = [], length = listeners.length; i < length; i++) {
189
+ if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
190
+ events.push(listeners[i]);
191
+ }
192
+ }
193
+ if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
194
+ else clearEvent(this, evt);
195
+ }
196
+ return this;
197
+ };
198
+ EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) {
199
+ var evt;
200
+ if (event) {
201
+ evt = prefix2 ? prefix2 + event : event;
202
+ if (this._events[evt]) clearEvent(this, evt);
203
+ } else {
204
+ this._events = new Events();
205
+ this._eventsCount = 0;
206
+ }
207
+ return this;
208
+ };
209
+ EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
210
+ EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
211
+ EventEmitter2.prefixed = prefix2;
212
+ EventEmitter2.EventEmitter = EventEmitter2;
213
+ if ("undefined" !== typeof module) {
214
+ module.exports = EventEmitter2;
215
+ }
216
+ }
217
+ });
218
+
219
+ // solana/account-filters.ts
220
+ var getFilters = (criteria, byteOffsets) => {
221
+ return Object.entries(criteria).reduce((acc, [key, value]) => {
222
+ const criteriaKey = key;
223
+ const effectiveByteOffset = byteOffsets[criteriaKey];
224
+ if (criteria[criteriaKey] && effectiveByteOffset) {
225
+ acc.push({
226
+ memcmp: {
227
+ offset: effectiveByteOffset,
228
+ bytes: value.toString()
229
+ }
230
+ });
231
+ }
232
+ return acc;
233
+ }, []);
234
+ };
235
+ var prepareWrappedAccount = async (connection, senderAddress, amount) => {
236
+ const tokenAccount = await splToken.getAssociatedTokenAddress(splToken.NATIVE_MINT, senderAddress, true);
237
+ const accInfo = await connection.getParsedAccountInfo(tokenAccount);
238
+ const instructions = (accInfo.value?.lamports ?? 0) > 0 ? [] : [splToken.createAssociatedTokenAccountInstruction(senderAddress, tokenAccount, senderAddress, splToken.NATIVE_MINT)];
239
+ return [
240
+ ...instructions,
241
+ web3_js.SystemProgram.transfer({
242
+ fromPubkey: senderAddress,
243
+ toPubkey: tokenAccount,
244
+ lamports: amount.toNumber()
245
+ }),
246
+ splToken.createSyncNativeInstruction(tokenAccount)
247
+ ];
248
+ };
249
+ var TransactionFailedError = class _TransactionFailedError extends Error {
250
+ constructor(m) {
251
+ super(m);
252
+ Object.setPrototypeOf(this, _TransactionFailedError.prototype);
253
+ this.name = "TransactionFailedError";
254
+ }
255
+ };
11
256
  var ICluster = /* @__PURE__ */ ((ICluster2) => {
12
257
  ICluster2["Mainnet"] = "mainnet";
13
258
  ICluster2["Devnet"] = "devnet";
@@ -15,15 +260,6 @@ var ICluster = /* @__PURE__ */ ((ICluster2) => {
15
260
  ICluster2["Local"] = "local";
16
261
  return ICluster2;
17
262
  })(ICluster || {});
18
- var IChain = /* @__PURE__ */ ((IChain2) => {
19
- IChain2["Solana"] = "Solana";
20
- IChain2["Aptos"] = "Aptos";
21
- IChain2["Ethereum"] = "Ethereum";
22
- IChain2["BNB"] = "BNB";
23
- IChain2["Polygon"] = "Polygon";
24
- IChain2["Sui"] = "Sui";
25
- return IChain2;
26
- })(IChain || {});
27
263
  var ContractError = class _ContractError extends Error {
28
264
  /**
29
265
  * Constructs the Error Wrapper
@@ -40,19 +276,454 @@ var ContractError = class _ContractError extends Error {
40
276
  }
41
277
  };
42
278
 
43
- // lib/assertions.ts
44
- var prefix = "Assertion failed";
45
- var invariant = (condition, message) => {
46
- if (condition) {
47
- return;
279
+ // ../../node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.mjs
280
+ var import_index = __toESM(require_eventemitter3());
281
+
282
+ // ../../node_modules/.pnpm/p-timeout@6.1.2/node_modules/p-timeout/index.js
283
+ var TimeoutError = class extends Error {
284
+ constructor(message) {
285
+ super(message);
286
+ this.name = "TimeoutError";
48
287
  }
49
- const provided = typeof message === "function" ? message() : message;
50
- const value = provided ? `${prefix}: ${provided}` : prefix;
51
- throw new Error(value);
52
288
  };
53
- function assertHasPublicKey(value, message) {
54
- invariant(value.publicKey, message ?? "publicKey is missing");
289
+ var AbortError = class extends Error {
290
+ constructor(message) {
291
+ super();
292
+ this.name = "AbortError";
293
+ this.message = message;
294
+ }
295
+ };
296
+ var getDOMException = (errorMessage) => globalThis.DOMException === void 0 ? new AbortError(errorMessage) : new DOMException(errorMessage);
297
+ var getAbortedReason = (signal) => {
298
+ const reason = signal.reason === void 0 ? getDOMException("This operation was aborted.") : signal.reason;
299
+ return reason instanceof Error ? reason : getDOMException(reason);
300
+ };
301
+ function pTimeout(promise, options) {
302
+ const {
303
+ milliseconds,
304
+ fallback,
305
+ message,
306
+ customTimers = { setTimeout, clearTimeout }
307
+ } = options;
308
+ let timer;
309
+ const wrappedPromise = new Promise((resolve, reject) => {
310
+ if (typeof milliseconds !== "number" || Math.sign(milliseconds) !== 1) {
311
+ throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``);
312
+ }
313
+ if (options.signal) {
314
+ const { signal } = options;
315
+ if (signal.aborted) {
316
+ reject(getAbortedReason(signal));
317
+ }
318
+ signal.addEventListener("abort", () => {
319
+ reject(getAbortedReason(signal));
320
+ });
321
+ }
322
+ if (milliseconds === Number.POSITIVE_INFINITY) {
323
+ promise.then(resolve, reject);
324
+ return;
325
+ }
326
+ const timeoutError = new TimeoutError();
327
+ timer = customTimers.setTimeout.call(void 0, () => {
328
+ if (fallback) {
329
+ try {
330
+ resolve(fallback());
331
+ } catch (error) {
332
+ reject(error);
333
+ }
334
+ return;
335
+ }
336
+ if (typeof promise.cancel === "function") {
337
+ promise.cancel();
338
+ }
339
+ if (message === false) {
340
+ resolve();
341
+ } else if (message instanceof Error) {
342
+ reject(message);
343
+ } else {
344
+ timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;
345
+ reject(timeoutError);
346
+ }
347
+ }, milliseconds);
348
+ (async () => {
349
+ try {
350
+ resolve(await promise);
351
+ } catch (error) {
352
+ reject(error);
353
+ }
354
+ })();
355
+ });
356
+ const cancelablePromise = wrappedPromise.finally(() => {
357
+ cancelablePromise.clear();
358
+ });
359
+ cancelablePromise.clear = () => {
360
+ customTimers.clearTimeout.call(void 0, timer);
361
+ timer = void 0;
362
+ };
363
+ return cancelablePromise;
364
+ }
365
+
366
+ // ../../node_modules/.pnpm/p-queue@8.0.1/node_modules/p-queue/dist/lower-bound.js
367
+ function lowerBound(array, value, comparator) {
368
+ let first = 0;
369
+ let count = array.length;
370
+ while (count > 0) {
371
+ const step = Math.trunc(count / 2);
372
+ let it = first + step;
373
+ if (comparator(array[it], value) <= 0) {
374
+ first = ++it;
375
+ count -= step + 1;
376
+ } else {
377
+ count = step;
378
+ }
379
+ }
380
+ return first;
55
381
  }
382
+
383
+ // ../../node_modules/.pnpm/p-queue@8.0.1/node_modules/p-queue/dist/priority-queue.js
384
+ var _queue;
385
+ var PriorityQueue = class {
386
+ constructor() {
387
+ __privateAdd(this, _queue, []);
388
+ }
389
+ enqueue(run, options) {
390
+ options = {
391
+ priority: 0,
392
+ ...options
393
+ };
394
+ const element = {
395
+ priority: options.priority,
396
+ run
397
+ };
398
+ if (this.size && __privateGet(this, _queue)[this.size - 1].priority >= options.priority) {
399
+ __privateGet(this, _queue).push(element);
400
+ return;
401
+ }
402
+ const index = lowerBound(__privateGet(this, _queue), element, (a, b) => b.priority - a.priority);
403
+ __privateGet(this, _queue).splice(index, 0, element);
404
+ }
405
+ dequeue() {
406
+ const item = __privateGet(this, _queue).shift();
407
+ return item?.run;
408
+ }
409
+ filter(options) {
410
+ return __privateGet(this, _queue).filter((element) => element.priority === options.priority).map((element) => element.run);
411
+ }
412
+ get size() {
413
+ return __privateGet(this, _queue).length;
414
+ }
415
+ };
416
+ _queue = new WeakMap();
417
+
418
+ // ../../node_modules/.pnpm/p-queue@8.0.1/node_modules/p-queue/dist/index.js
419
+ var _carryoverConcurrencyCount, _isIntervalIgnored, _intervalCount, _intervalCap, _interval, _intervalEnd, _intervalId, _timeoutId, _queue2, _queueClass, _pending, _concurrency, _isPaused, _throwOnTimeout, _PQueue_instances, doesIntervalAllowAnother_get, doesConcurrentAllowAnother_get, next_fn, onResumeInterval_fn, isIntervalPaused_get, tryToStartAnother_fn, initializeIntervalIfNeeded_fn, onInterval_fn, processQueue_fn, throwOnAbort_fn, onEvent_fn;
420
+ var PQueue = class extends import_index.default {
421
+ // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`
422
+ constructor(options) {
423
+ super();
424
+ __privateAdd(this, _PQueue_instances);
425
+ __privateAdd(this, _carryoverConcurrencyCount);
426
+ __privateAdd(this, _isIntervalIgnored);
427
+ __privateAdd(this, _intervalCount, 0);
428
+ __privateAdd(this, _intervalCap);
429
+ __privateAdd(this, _interval);
430
+ __privateAdd(this, _intervalEnd, 0);
431
+ __privateAdd(this, _intervalId);
432
+ __privateAdd(this, _timeoutId);
433
+ __privateAdd(this, _queue2);
434
+ __privateAdd(this, _queueClass);
435
+ __privateAdd(this, _pending, 0);
436
+ // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194
437
+ __privateAdd(this, _concurrency);
438
+ __privateAdd(this, _isPaused);
439
+ __privateAdd(this, _throwOnTimeout);
440
+ /**
441
+ Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.
442
+
443
+ Applies to each future operation.
444
+ */
445
+ __publicField(this, "timeout");
446
+ options = {
447
+ carryoverConcurrencyCount: false,
448
+ intervalCap: Number.POSITIVE_INFINITY,
449
+ interval: 0,
450
+ concurrency: Number.POSITIVE_INFINITY,
451
+ autoStart: true,
452
+ queueClass: PriorityQueue,
453
+ ...options
454
+ };
455
+ if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) {
456
+ throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${options.intervalCap?.toString() ?? ""}\` (${typeof options.intervalCap})`);
457
+ }
458
+ if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) {
459
+ throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${options.interval?.toString() ?? ""}\` (${typeof options.interval})`);
460
+ }
461
+ __privateSet(this, _carryoverConcurrencyCount, options.carryoverConcurrencyCount);
462
+ __privateSet(this, _isIntervalIgnored, options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0);
463
+ __privateSet(this, _intervalCap, options.intervalCap);
464
+ __privateSet(this, _interval, options.interval);
465
+ __privateSet(this, _queue2, new options.queueClass());
466
+ __privateSet(this, _queueClass, options.queueClass);
467
+ this.concurrency = options.concurrency;
468
+ this.timeout = options.timeout;
469
+ __privateSet(this, _throwOnTimeout, options.throwOnTimeout === true);
470
+ __privateSet(this, _isPaused, options.autoStart === false);
471
+ }
472
+ get concurrency() {
473
+ return __privateGet(this, _concurrency);
474
+ }
475
+ set concurrency(newConcurrency) {
476
+ if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) {
477
+ throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`);
478
+ }
479
+ __privateSet(this, _concurrency, newConcurrency);
480
+ __privateMethod(this, _PQueue_instances, processQueue_fn).call(this);
481
+ }
482
+ async add(function_, options = {}) {
483
+ options = {
484
+ timeout: this.timeout,
485
+ throwOnTimeout: __privateGet(this, _throwOnTimeout),
486
+ ...options
487
+ };
488
+ return new Promise((resolve, reject) => {
489
+ __privateGet(this, _queue2).enqueue(async () => {
490
+ __privateWrapper(this, _pending)._++;
491
+ __privateWrapper(this, _intervalCount)._++;
492
+ try {
493
+ options.signal?.throwIfAborted();
494
+ let operation = function_({ signal: options.signal });
495
+ if (options.timeout) {
496
+ operation = pTimeout(Promise.resolve(operation), { milliseconds: options.timeout });
497
+ }
498
+ if (options.signal) {
499
+ operation = Promise.race([operation, __privateMethod(this, _PQueue_instances, throwOnAbort_fn).call(this, options.signal)]);
500
+ }
501
+ const result = await operation;
502
+ resolve(result);
503
+ this.emit("completed", result);
504
+ } catch (error) {
505
+ if (error instanceof TimeoutError && !options.throwOnTimeout) {
506
+ resolve();
507
+ return;
508
+ }
509
+ reject(error);
510
+ this.emit("error", error);
511
+ } finally {
512
+ __privateMethod(this, _PQueue_instances, next_fn).call(this);
513
+ }
514
+ }, options);
515
+ this.emit("add");
516
+ __privateMethod(this, _PQueue_instances, tryToStartAnother_fn).call(this);
517
+ });
518
+ }
519
+ async addAll(functions, options) {
520
+ return Promise.all(functions.map(async (function_) => this.add(function_, options)));
521
+ }
522
+ /**
523
+ Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)
524
+ */
525
+ start() {
526
+ if (!__privateGet(this, _isPaused)) {
527
+ return this;
528
+ }
529
+ __privateSet(this, _isPaused, false);
530
+ __privateMethod(this, _PQueue_instances, processQueue_fn).call(this);
531
+ return this;
532
+ }
533
+ /**
534
+ Put queue execution on hold.
535
+ */
536
+ pause() {
537
+ __privateSet(this, _isPaused, true);
538
+ }
539
+ /**
540
+ Clear the queue.
541
+ */
542
+ clear() {
543
+ __privateSet(this, _queue2, new (__privateGet(this, _queueClass))());
544
+ }
545
+ /**
546
+ Can be called multiple times. Useful if you for example add additional items at a later time.
547
+
548
+ @returns A promise that settles when the queue becomes empty.
549
+ */
550
+ async onEmpty() {
551
+ if (__privateGet(this, _queue2).size === 0) {
552
+ return;
553
+ }
554
+ await __privateMethod(this, _PQueue_instances, onEvent_fn).call(this, "empty");
555
+ }
556
+ /**
557
+ @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.
558
+
559
+ If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.
560
+
561
+ Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.
562
+ */
563
+ async onSizeLessThan(limit) {
564
+ if (__privateGet(this, _queue2).size < limit) {
565
+ return;
566
+ }
567
+ await __privateMethod(this, _PQueue_instances, onEvent_fn).call(this, "next", () => __privateGet(this, _queue2).size < limit);
568
+ }
569
+ /**
570
+ The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.
571
+
572
+ @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.
573
+ */
574
+ async onIdle() {
575
+ if (__privateGet(this, _pending) === 0 && __privateGet(this, _queue2).size === 0) {
576
+ return;
577
+ }
578
+ await __privateMethod(this, _PQueue_instances, onEvent_fn).call(this, "idle");
579
+ }
580
+ /**
581
+ Size of the queue, the number of queued items waiting to run.
582
+ */
583
+ get size() {
584
+ return __privateGet(this, _queue2).size;
585
+ }
586
+ /**
587
+ Size of the queue, filtered by the given options.
588
+
589
+ For example, this can be used to find the number of items remaining in the queue with a specific priority level.
590
+ */
591
+ sizeBy(options) {
592
+ return __privateGet(this, _queue2).filter(options).length;
593
+ }
594
+ /**
595
+ Number of running items (no longer in the queue).
596
+ */
597
+ get pending() {
598
+ return __privateGet(this, _pending);
599
+ }
600
+ /**
601
+ Whether the queue is currently paused.
602
+ */
603
+ get isPaused() {
604
+ return __privateGet(this, _isPaused);
605
+ }
606
+ };
607
+ _carryoverConcurrencyCount = new WeakMap();
608
+ _isIntervalIgnored = new WeakMap();
609
+ _intervalCount = new WeakMap();
610
+ _intervalCap = new WeakMap();
611
+ _interval = new WeakMap();
612
+ _intervalEnd = new WeakMap();
613
+ _intervalId = new WeakMap();
614
+ _timeoutId = new WeakMap();
615
+ _queue2 = new WeakMap();
616
+ _queueClass = new WeakMap();
617
+ _pending = new WeakMap();
618
+ _concurrency = new WeakMap();
619
+ _isPaused = new WeakMap();
620
+ _throwOnTimeout = new WeakMap();
621
+ _PQueue_instances = new WeakSet();
622
+ doesIntervalAllowAnother_get = function() {
623
+ return __privateGet(this, _isIntervalIgnored) || __privateGet(this, _intervalCount) < __privateGet(this, _intervalCap);
624
+ };
625
+ doesConcurrentAllowAnother_get = function() {
626
+ return __privateGet(this, _pending) < __privateGet(this, _concurrency);
627
+ };
628
+ next_fn = function() {
629
+ __privateWrapper(this, _pending)._--;
630
+ __privateMethod(this, _PQueue_instances, tryToStartAnother_fn).call(this);
631
+ this.emit("next");
632
+ };
633
+ onResumeInterval_fn = function() {
634
+ __privateMethod(this, _PQueue_instances, onInterval_fn).call(this);
635
+ __privateMethod(this, _PQueue_instances, initializeIntervalIfNeeded_fn).call(this);
636
+ __privateSet(this, _timeoutId, void 0);
637
+ };
638
+ isIntervalPaused_get = function() {
639
+ const now = Date.now();
640
+ if (__privateGet(this, _intervalId) === void 0) {
641
+ const delay = __privateGet(this, _intervalEnd) - now;
642
+ if (delay < 0) {
643
+ __privateSet(this, _intervalCount, __privateGet(this, _carryoverConcurrencyCount) ? __privateGet(this, _pending) : 0);
644
+ } else {
645
+ if (__privateGet(this, _timeoutId) === void 0) {
646
+ __privateSet(this, _timeoutId, setTimeout(() => {
647
+ __privateMethod(this, _PQueue_instances, onResumeInterval_fn).call(this);
648
+ }, delay));
649
+ }
650
+ return true;
651
+ }
652
+ }
653
+ return false;
654
+ };
655
+ tryToStartAnother_fn = function() {
656
+ if (__privateGet(this, _queue2).size === 0) {
657
+ if (__privateGet(this, _intervalId)) {
658
+ clearInterval(__privateGet(this, _intervalId));
659
+ }
660
+ __privateSet(this, _intervalId, void 0);
661
+ this.emit("empty");
662
+ if (__privateGet(this, _pending) === 0) {
663
+ this.emit("idle");
664
+ }
665
+ return false;
666
+ }
667
+ if (!__privateGet(this, _isPaused)) {
668
+ const canInitializeInterval = !__privateGet(this, _PQueue_instances, isIntervalPaused_get);
669
+ if (__privateGet(this, _PQueue_instances, doesIntervalAllowAnother_get) && __privateGet(this, _PQueue_instances, doesConcurrentAllowAnother_get)) {
670
+ const job = __privateGet(this, _queue2).dequeue();
671
+ if (!job) {
672
+ return false;
673
+ }
674
+ this.emit("active");
675
+ job();
676
+ if (canInitializeInterval) {
677
+ __privateMethod(this, _PQueue_instances, initializeIntervalIfNeeded_fn).call(this);
678
+ }
679
+ return true;
680
+ }
681
+ }
682
+ return false;
683
+ };
684
+ initializeIntervalIfNeeded_fn = function() {
685
+ if (__privateGet(this, _isIntervalIgnored) || __privateGet(this, _intervalId) !== void 0) {
686
+ return;
687
+ }
688
+ __privateSet(this, _intervalId, setInterval(() => {
689
+ __privateMethod(this, _PQueue_instances, onInterval_fn).call(this);
690
+ }, __privateGet(this, _interval)));
691
+ __privateSet(this, _intervalEnd, Date.now() + __privateGet(this, _interval));
692
+ };
693
+ onInterval_fn = function() {
694
+ if (__privateGet(this, _intervalCount) === 0 && __privateGet(this, _pending) === 0 && __privateGet(this, _intervalId)) {
695
+ clearInterval(__privateGet(this, _intervalId));
696
+ __privateSet(this, _intervalId, void 0);
697
+ }
698
+ __privateSet(this, _intervalCount, __privateGet(this, _carryoverConcurrencyCount) ? __privateGet(this, _pending) : 0);
699
+ __privateMethod(this, _PQueue_instances, processQueue_fn).call(this);
700
+ };
701
+ /**
702
+ Executes all queued functions until it reaches the limit.
703
+ */
704
+ processQueue_fn = function() {
705
+ while (__privateMethod(this, _PQueue_instances, tryToStartAnother_fn).call(this)) {
706
+ }
707
+ };
708
+ throwOnAbort_fn = async function(signal) {
709
+ return new Promise((_resolve, reject) => {
710
+ signal.addEventListener("abort", () => {
711
+ reject(signal.reason);
712
+ }, { once: true });
713
+ });
714
+ };
715
+ onEvent_fn = async function(event, filter) {
716
+ return new Promise((resolve) => {
717
+ const listener = () => {
718
+ if (filter && !filter()) {
719
+ return;
720
+ }
721
+ this.off(event, listener);
722
+ resolve();
723
+ };
724
+ this.on(event, listener);
725
+ });
726
+ };
56
727
  var getBN = (value, decimals) => {
57
728
  const decimalPart = value - Math.trunc(value);
58
729
  const integerPart = new BN__default.default(Math.trunc(value));
@@ -93,6 +764,423 @@ function multiplyBigIntByNumber(x, y, scaleDigits = 9) {
93
764
  return isNegative ? -product : product;
94
765
  }
95
766
 
767
+ // lib/assertions.ts
768
+ var prefix = "Assertion failed";
769
+ var invariant = (condition, message) => {
770
+ if (condition) {
771
+ return;
772
+ }
773
+ const provided = typeof message === "function" ? message() : message;
774
+ const value = provided ? `${prefix}: ${provided}` : prefix;
775
+ throw new Error(value);
776
+ };
777
+ function assertHasPublicKey(value, message) {
778
+ invariant(value.publicKey, message ?? "publicKey is missing");
779
+ }
780
+
781
+ // solana/utils.ts
782
+ var SIMULATE_TRIES = 3;
783
+ var buildSendThrottler = (sendRate, sendInterval = 1e3) => {
784
+ return new PQueue({ concurrency: sendRate, intervalCap: 1, interval: sendInterval });
785
+ };
786
+ async function getProgramAccounts(connection, wallet, offset, programId) {
787
+ const programAccounts = await connection?.getProgramAccounts(programId, {
788
+ filters: [
789
+ {
790
+ memcmp: {
791
+ offset,
792
+ bytes: wallet.toBase58()
793
+ }
794
+ }
795
+ ]
796
+ });
797
+ return [...programAccounts];
798
+ }
799
+ function isSignerWallet(walletOrKeypair) {
800
+ return walletOrKeypair.signTransaction !== void 0;
801
+ }
802
+ function isSignerKeypair(walletOrKeypair) {
803
+ return walletOrKeypair instanceof web3_js.Keypair || walletOrKeypair.constructor === web3_js.Keypair || walletOrKeypair.constructor.name === web3_js.Keypair.prototype.constructor.name;
804
+ }
805
+ function isTransactionVersioned(tx) {
806
+ return "message" in tx;
807
+ }
808
+ async function prepareTransaction(connection, ixs, payer, commitment, partialSigners, lookupTables) {
809
+ if (!payer) {
810
+ throw new Error("Payer public key is not provided!");
811
+ }
812
+ const { value: hash, context } = await connection.getLatestBlockhashAndContext(commitment);
813
+ return {
814
+ tx: createVersionedTransaction(ixs, payer, hash.blockhash, partialSigners, lookupTables),
815
+ hash,
816
+ context
817
+ };
818
+ }
819
+ function createVersionedTransaction(ixs, payer, recentBlockhash, partialSigners, lookupTables) {
820
+ invariant(payer, "Payer public key is not provided!");
821
+ const messageV0 = new web3_js.TransactionMessage({
822
+ payerKey: payer,
823
+ recentBlockhash,
824
+ instructions: ixs
825
+ }).compileToV0Message(lookupTables);
826
+ const tx = new web3_js.VersionedTransaction(messageV0);
827
+ const signers = partialSigners?.filter((item) => !!item) ?? void 0;
828
+ if (signers) {
829
+ tx.sign(signers);
830
+ }
831
+ return tx;
832
+ }
833
+ async function signTransaction(invoker, tx) {
834
+ let signedTx;
835
+ if (isSignerWallet(invoker)) {
836
+ signedTx = await invoker.signTransaction(tx);
837
+ } else {
838
+ if (isTransactionVersioned(tx)) {
839
+ tx.sign([invoker]);
840
+ } else {
841
+ tx.partialSign(invoker);
842
+ }
843
+ signedTx = tx;
844
+ }
845
+ return signedTx;
846
+ }
847
+ async function signAndExecuteTransaction(connection, invoker, tx, confirmationParams, transactionExecutionParams) {
848
+ const signedTx = await signTransaction(invoker, tx);
849
+ return executeTransaction(connection, signedTx, confirmationParams, transactionExecutionParams);
850
+ }
851
+ async function executeTransaction(connection, tx, confirmationParams, transactionExecutionParams) {
852
+ if (tx.signatures.length === 0) {
853
+ throw Error("Error with transaction parameters.");
854
+ }
855
+ if (!transactionExecutionParams.skipSimulation) {
856
+ await simulateTransaction(connection, tx);
857
+ }
858
+ return sendAndConfirmTransaction(connection, tx, confirmationParams, transactionExecutionParams);
859
+ }
860
+ async function executeMultipleTransactions(connection, txs, confirmationParams, { sendRate = 1, sendThrottler, ...throttlingParams }) {
861
+ if (!sendThrottler) {
862
+ sendThrottler = buildSendThrottler(sendRate);
863
+ }
864
+ return Promise.allSettled(
865
+ txs.map(
866
+ (tx) => executeTransaction(connection, tx, confirmationParams, {
867
+ ...throttlingParams,
868
+ sendRate,
869
+ sendThrottler
870
+ })
871
+ )
872
+ );
873
+ }
874
+ async function sendAndConfirmTransaction(connection, tx, { hash, context, commitment }, { sendRate = 1, sendThrottler, waitBeforeConfirming }) {
875
+ const isVersioned = isTransactionVersioned(tx);
876
+ let signature;
877
+ if (isVersioned) {
878
+ signature = bs58__default.default.encode(tx.signatures[0]);
879
+ } else {
880
+ signature = bs58__default.default.encode(tx.signature);
881
+ }
882
+ if (!sendThrottler) {
883
+ sendThrottler = buildSendThrottler(sendRate);
884
+ }
885
+ let blockheight = await connection.getBlockHeight(commitment);
886
+ let transactionSent = false;
887
+ const rawTransaction = tx.serialize();
888
+ while (blockheight < hash.lastValidBlockHeight + 15) {
889
+ try {
890
+ if (blockheight < hash.lastValidBlockHeight || !transactionSent) {
891
+ await sendThrottler.add(
892
+ async () => connection.sendRawTransaction(rawTransaction, {
893
+ maxRetries: 0,
894
+ minContextSlot: context.slot,
895
+ preflightCommitment: commitment,
896
+ skipPreflight: true
897
+ })
898
+ );
899
+ transactionSent = true;
900
+ }
901
+ } catch (e) {
902
+ if (transactionSent || e instanceof web3_js.SendTransactionError && e.message.includes("Minimum context slot has not been reached")) {
903
+ await sleep(500);
904
+ continue;
905
+ }
906
+ throw e;
907
+ }
908
+ await sleep(waitBeforeConfirming ?? 2e3);
909
+ try {
910
+ const value = await confirmAndEnsureTransaction(connection, signature);
911
+ if (value) {
912
+ return signature;
913
+ }
914
+ } catch (e) {
915
+ if (e instanceof TransactionFailedError) {
916
+ throw e;
917
+ }
918
+ await sleep(500);
919
+ }
920
+ try {
921
+ blockheight = await connection.getBlockHeight(commitment);
922
+ } catch (_e) {
923
+ await sleep(500);
924
+ }
925
+ }
926
+ throw new Error(`Transaction ${signature} expired.`);
927
+ }
928
+ async function simulateTransaction(connection, tx) {
929
+ let res;
930
+ for (let i = 0; i < SIMULATE_TRIES; i++) {
931
+ if (isTransactionVersioned(tx)) {
932
+ res = await connection.simulateTransaction(tx);
933
+ } else {
934
+ res = await connection.simulateTransaction(tx);
935
+ }
936
+ if (res.value.err) {
937
+ const errMessage = JSON.stringify(res.value.err);
938
+ if (!errMessage.includes("BlockhashNotFound") || i === SIMULATE_TRIES - 1) {
939
+ throw new web3_js.SendTransactionError({
940
+ action: "simulate",
941
+ signature: "",
942
+ transactionMessage: `failed to simulate transaction: ${typeof res.value.err === "string" ? res.value.err : errMessage}`,
943
+ logs: res.value.logs ?? void 0
944
+ });
945
+ }
946
+ continue;
947
+ }
948
+ return res;
949
+ }
950
+ throw new web3_js.SendTransactionError({
951
+ action: "simulate",
952
+ signature: "",
953
+ transactionMessage: "failed to simulate transaction"
954
+ });
955
+ }
956
+ async function confirmAndEnsureTransaction(connection, signature, ignoreError) {
957
+ const response = await connection.getSignatureStatuses([signature]);
958
+ if (!response || response.value.length === 0 || response.value[0] === null) {
959
+ return null;
960
+ }
961
+ const value = response.value[0];
962
+ if (!value) {
963
+ return null;
964
+ }
965
+ if (!ignoreError && value.err) {
966
+ throw new TransactionFailedError(`Raw transaction ${signature} failed (${JSON.stringify({ err: value.err })})`);
967
+ }
968
+ switch (connection.commitment) {
969
+ case "confirmed":
970
+ case "single":
971
+ case "singleGossip": {
972
+ if (value.confirmationStatus === "processed") {
973
+ return null;
974
+ }
975
+ break;
976
+ }
977
+ case "finalized":
978
+ case "max":
979
+ case "root": {
980
+ if (value.confirmationStatus === "processed" || value.confirmationStatus === "confirmed") {
981
+ return null;
982
+ }
983
+ break;
984
+ }
985
+ }
986
+ return value;
987
+ }
988
+ function ata(mint, owner, programId) {
989
+ return splToken.getAssociatedTokenAddress(mint, owner, true, programId);
990
+ }
991
+ async function ataBatchExist(connection, paramsBatch) {
992
+ const tokenAccounts = await Promise.all(
993
+ paramsBatch.map(async ({ mint, owner, programId }) => {
994
+ return ata(mint, owner, programId);
995
+ })
996
+ );
997
+ const response = await connection.getMultipleAccountsInfo(tokenAccounts);
998
+ return response.map((accInfo) => !!accInfo);
999
+ }
1000
+ async function enrichAtaParams(connection, paramsBatch) {
1001
+ const programIdByMint = {};
1002
+ return Promise.all(
1003
+ paramsBatch.map(async (params) => {
1004
+ if (params.programId) {
1005
+ return params;
1006
+ }
1007
+ const mintStr = params.mint.toString();
1008
+ if (!(mintStr in programIdByMint)) {
1009
+ const { tokenProgramId } = await getMintAndProgram(connection, params.mint);
1010
+ programIdByMint[mintStr] = tokenProgramId;
1011
+ }
1012
+ params.programId = programIdByMint[mintStr];
1013
+ return params;
1014
+ })
1015
+ );
1016
+ }
1017
+ async function generateCreateAtaBatchTx(connection, payer, paramsBatch, commitment) {
1018
+ paramsBatch = await enrichAtaParams(connection, paramsBatch);
1019
+ const ixs = await Promise.all(
1020
+ paramsBatch.map(async ({ mint, owner, programId }) => {
1021
+ return splToken.createAssociatedTokenAccountInstruction(payer, await ata(mint, owner), owner, mint, programId);
1022
+ })
1023
+ );
1024
+ const { value: hash, context } = await connection.getLatestBlockhashAndContext({ commitment });
1025
+ return { tx: createVersionedTransaction(ixs, payer, hash.blockhash), hash, context };
1026
+ }
1027
+ async function createAtaBatch(connection, invoker, paramsBatch, commitment, rate) {
1028
+ const { tx, hash, context } = await generateCreateAtaBatchTx(
1029
+ connection,
1030
+ invoker.publicKey,
1031
+ await enrichAtaParams(connection, paramsBatch),
1032
+ commitment
1033
+ );
1034
+ return signAndExecuteTransaction(connection, invoker, tx, { hash, context, commitment }, { sendRate: rate });
1035
+ }
1036
+ async function checkOrCreateAtaBatch(connection, owners, mint, invoker, programId, payer) {
1037
+ assertHasPublicKey(invoker, "Invoker's PublicKey is not available, check passed wallet adapter!");
1038
+ const ixs = [];
1039
+ if (!programId) {
1040
+ programId = (await getMintAndProgram(connection, mint)).tokenProgramId;
1041
+ }
1042
+ const atas = [];
1043
+ for (const owner of owners) {
1044
+ atas.push(await ata(mint, owner, programId));
1045
+ }
1046
+ const response = await connection.getMultipleAccountsInfo(atas);
1047
+ for (let i = 0; i < response.length; i++) {
1048
+ if (!response[i]) {
1049
+ ixs.push(
1050
+ splToken.createAssociatedTokenAccountInstruction(payer ?? invoker.publicKey, atas[i], owners[i], mint, programId)
1051
+ );
1052
+ }
1053
+ }
1054
+ return ixs;
1055
+ }
1056
+ function prepareBaseInstructions(connection, { computePrice, computeLimit }) {
1057
+ const ixs = [];
1058
+ if (computePrice && typeof computePrice !== "function") {
1059
+ ixs.push(web3_js.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: computePrice }));
1060
+ }
1061
+ if (computeLimit && typeof computeLimit === "number") {
1062
+ ixs.push(web3_js.ComputeBudgetProgram.setComputeUnitLimit({ units: computeLimit }));
1063
+ }
1064
+ return ixs;
1065
+ }
1066
+ async function getMintAndProgram(connection, address, commitment) {
1067
+ const accountInfo = await connection.getAccountInfo(address, commitment);
1068
+ let programId = accountInfo?.owner;
1069
+ if (!programId?.equals(splToken.TOKEN_PROGRAM_ID) && !programId?.equals(splToken.TOKEN_2022_PROGRAM_ID)) {
1070
+ programId = splToken.TOKEN_PROGRAM_ID;
1071
+ }
1072
+ return {
1073
+ mint: splToken.unpackMint(address, accountInfo, programId),
1074
+ tokenProgramId: programId
1075
+ };
1076
+ }
1077
+ async function getMultipleAccountsInfoBatched(connection, pubKeys, commitment) {
1078
+ const batchSize = 99;
1079
+ const batches = [];
1080
+ for (let i = 0; i < pubKeys.length; i += batchSize) {
1081
+ const batch = pubKeys.slice(i, i + batchSize);
1082
+ batches.push(connection.getMultipleAccountsInfo(batch, commitment));
1083
+ }
1084
+ const results = await Promise.all(batches);
1085
+ return results.flat();
1086
+ }
1087
+ function deserializeRawTransaction(serializedTx) {
1088
+ const txBuffer = buffer.Buffer.from(serializedTx, "base64");
1089
+ try {
1090
+ const tx = web3_js.Transaction.from(txBuffer);
1091
+ return resolveTransactionAccounts(tx);
1092
+ } catch (error) {
1093
+ try {
1094
+ const vtx = web3_js.VersionedTransaction.deserialize(txBuffer);
1095
+ return resolveTransactionAccounts(vtx);
1096
+ } catch (vError) {
1097
+ throw new Error("Failed to deserialize transaction: " + (vError instanceof Error ? vError.message : vError), {
1098
+ cause: vError
1099
+ });
1100
+ }
1101
+ }
1102
+ }
1103
+ var resolveTransactionAccounts = (tx) => {
1104
+ if (tx instanceof web3_js.Transaction) {
1105
+ const message2 = tx.compileMessage();
1106
+ const accounts2 = message2.accountKeys;
1107
+ const writableAccounts2 = accounts2.filter((_, idx) => message2.isAccountWritable(idx));
1108
+ return {
1109
+ type: "legacy",
1110
+ transaction: tx,
1111
+ accounts: accounts2,
1112
+ writableAccounts: writableAccounts2
1113
+ };
1114
+ }
1115
+ const message = tx.message;
1116
+ const accounts = "staticAccountKeys" in message ? message.staticAccountKeys : message.accountKeys;
1117
+ const writableAccounts = accounts.filter((_, idx) => message.isAccountWritable(idx));
1118
+ return {
1119
+ type: "versioned",
1120
+ transaction: tx,
1121
+ accounts,
1122
+ writableAccounts
1123
+ };
1124
+ };
1125
+ var pk = (address) => {
1126
+ return typeof address === "string" ? new web3_js.PublicKey(address) : address;
1127
+ };
1128
+
1129
+ // solana/lib/estimate.ts
1130
+ var createTestTransaction = (ixs, payer, recentBlockhash, partialSigners) => {
1131
+ return createVersionedTransaction(ixs, payer, "11111111111111111111111111111111", partialSigners);
1132
+ };
1133
+ async function estimateComputeUnitPrice(estimate, testTx) {
1134
+ return estimate(resolveTransactionAccounts(testTx).writableAccounts);
1135
+ }
1136
+ async function createAndEstimateTransaction(createFn, extParams, select) {
1137
+ select = select ?? ((value) => value);
1138
+ const createResult = await createFn(extParams);
1139
+ const prepareIxs = select(createResult);
1140
+ const { computePrice, computeLimit } = extParams;
1141
+ const invoker = extParams.invoker.publicKey;
1142
+ invariant(invoker, "Invoker's PublicKey is not available, check passed wallet adapter!");
1143
+ const testTx = createTestTransaction(prepareIxs, pk(invoker), void 0, void 0);
1144
+ const estimatedComputeLimit = typeof computeLimit === "function" ? await computeLimit(testTx) : computeLimit;
1145
+ if (typeof computePrice !== "function") {
1146
+ if (typeof computeLimit !== "function") {
1147
+ return createResult;
1148
+ }
1149
+ return createFn({
1150
+ ...extParams,
1151
+ computeLimit: estimatedComputeLimit
1152
+ });
1153
+ }
1154
+ const estimatedComputeUnitPrice = typeof computePrice === "function" ? await estimateComputeUnitPrice(computePrice, testTx) : (
1155
+ // unachievable because we don't execute estimation for constant or undefined priority fee
1156
+ computePrice
1157
+ );
1158
+ return createFn({
1159
+ ...extParams,
1160
+ computePrice: estimatedComputeUnitPrice,
1161
+ computeLimit: estimatedComputeLimit
1162
+ });
1163
+ }
1164
+
1165
+ // solana/rpc/consume-limit-estimate/estimate.ts
1166
+ var estimateConsumeLimit = async (connection, tx, options = {}) => {
1167
+ const { increaseFactor = 0.05 } = options;
1168
+ const simulationResults = await connection.simulateTransaction(tx, {
1169
+ sigVerify: false,
1170
+ replaceRecentBlockhash: true
1171
+ });
1172
+ return {
1173
+ unitsConsumed: simulationResults.value.unitsConsumed ? Math.ceil(simulationResults.value.unitsConsumed * (1 + increaseFactor)) : simulationResults.value.unitsConsumed,
1174
+ data: simulationResults
1175
+ };
1176
+ };
1177
+
1178
+ // solana/lib/unwrap-auto-simulate-ext.ts
1179
+ var unwrapExecutionParams = ({ computeLimit, ...rest }, connection) => {
1180
+ const consumeLimitFn = computeLimit === "autoSimulate" ? (tx) => estimateConsumeLimit(connection, tx).then((limit) => limit.unitsConsumed ?? 0) : computeLimit;
1181
+ return { ...rest, computeLimit: consumeLimitFn, skipSimulation: computeLimit === "autoSimulate" };
1182
+ };
1183
+
96
1184
  // lib/fetch-token-price.ts
97
1185
  var fetchTokenPrice = async (mintId, cluster = "mainnet" /* Mainnet */, options) => {
98
1186
  const url = `https://token-api.streamflow.finance/price?ids=${encodeURIComponent(mintId)}&cluster=${encodeURIComponent(cluster)}`;
@@ -116,16 +1204,47 @@ var fetchTokenPrice = async (mintId, cluster = "mainnet" /* Mainnet */, options)
116
1204
  };
117
1205
 
118
1206
  exports.ContractError = ContractError;
119
- exports.IChain = IChain;
120
1207
  exports.ICluster = ICluster;
1208
+ exports.TransactionFailedError = TransactionFailedError;
121
1209
  exports.assertHasPublicKey = assertHasPublicKey;
1210
+ exports.ata = ata;
1211
+ exports.ataBatchExist = ataBatchExist;
1212
+ exports.buildSendThrottler = buildSendThrottler;
1213
+ exports.checkOrCreateAtaBatch = checkOrCreateAtaBatch;
1214
+ exports.confirmAndEnsureTransaction = confirmAndEnsureTransaction;
1215
+ exports.createAndEstimateTransaction = createAndEstimateTransaction;
1216
+ exports.createAtaBatch = createAtaBatch;
1217
+ exports.createVersionedTransaction = createVersionedTransaction;
1218
+ exports.deserializeRawTransaction = deserializeRawTransaction;
122
1219
  exports.divCeilN = divCeilN;
1220
+ exports.enrichAtaParams = enrichAtaParams;
1221
+ exports.estimateComputeUnitPrice = estimateComputeUnitPrice;
1222
+ exports.executeMultipleTransactions = executeMultipleTransactions;
1223
+ exports.executeTransaction = executeTransaction;
123
1224
  exports.fetchTokenPrice = fetchTokenPrice;
1225
+ exports.generateCreateAtaBatchTx = generateCreateAtaBatchTx;
124
1226
  exports.getBN = getBN;
1227
+ exports.getFilters = getFilters;
1228
+ exports.getMintAndProgram = getMintAndProgram;
1229
+ exports.getMultipleAccountsInfoBatched = getMultipleAccountsInfoBatched;
125
1230
  exports.getNumberFromBN = getNumberFromBN;
1231
+ exports.getProgramAccounts = getProgramAccounts;
126
1232
  exports.handleContractError = handleContractError;
127
1233
  exports.invariant = invariant;
1234
+ exports.isSignerKeypair = isSignerKeypair;
1235
+ exports.isSignerWallet = isSignerWallet;
1236
+ exports.isTransactionVersioned = isTransactionVersioned;
128
1237
  exports.multiplyBigIntByNumber = multiplyBigIntByNumber;
1238
+ exports.pk = pk;
1239
+ exports.prepareBaseInstructions = prepareBaseInstructions;
1240
+ exports.prepareTransaction = prepareTransaction;
1241
+ exports.prepareWrappedAccount = prepareWrappedAccount;
1242
+ exports.resolveTransactionAccounts = resolveTransactionAccounts;
1243
+ exports.sendAndConfirmTransaction = sendAndConfirmTransaction;
1244
+ exports.signAndExecuteTransaction = signAndExecuteTransaction;
1245
+ exports.signTransaction = signTransaction;
1246
+ exports.simulateTransaction = simulateTransaction;
129
1247
  exports.sleep = sleep;
1248
+ exports.unwrapExecutionParams = unwrapExecutionParams;
130
1249
  //# sourceMappingURL=index.cjs.map
131
1250
  //# sourceMappingURL=index.cjs.map