@streamflow/common 6.5.0 → 7.0.0-alpha.10

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,754 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- var __read = (this && this.__read) || function (o, n) {
39
- var m = typeof Symbol === "function" && o[Symbol.iterator];
40
- if (!m) return o;
41
- var i = m.call(o), r, ar = [], e;
42
- try {
43
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
44
- }
45
- catch (error) { e = { error: error }; }
46
- finally {
47
- try {
48
- if (r && !r.done && (m = i["return"])) m.call(i);
49
- }
50
- finally { if (e) throw e.error; }
51
- }
52
- return ar;
53
- };
54
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
55
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
56
- if (ar || !(i in from)) {
57
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
58
- ar[i] = from[i];
59
- }
60
- }
61
- return to.concat(ar || Array.prototype.slice.call(from));
62
- };
63
- var __values = (this && this.__values) || function(o) {
64
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
65
- if (m) return m.call(o);
66
- if (o && typeof o.length === "number") return {
67
- next: function () {
68
- if (o && i >= o.length) o = void 0;
69
- return { value: o && o[i++], done: !o };
70
- }
71
- };
72
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
73
- };
74
- var __importDefault = (this && this.__importDefault) || function (mod) {
75
- return (mod && mod.__esModule) ? mod : { "default": mod };
76
- };
77
- Object.defineProperty(exports, "__esModule", { value: true });
78
- exports.getMintAndProgram = exports.prepareBaseInstructions = exports.checkOrCreateAtaBatch = exports.createAtaBatch = exports.generateCreateAtaBatchTx = exports.enrichAtaParams = exports.ataBatchExist = exports.ata = exports.confirmAndEnsureTransaction = exports.simulateTransaction = exports.sendAndConfirmTransaction = exports.executeMultipleTransactions = exports.executeTransaction = exports.signAndExecuteTransaction = exports.signTransaction = exports.prepareTransaction = exports.isTransactionVersioned = exports.isSignerKeypair = exports.isSignerWallet = exports.getProgramAccounts = exports.buildSendThrottler = void 0;
79
- var spl_token_1 = require("@solana/spl-token");
80
- var web3_js_1 = require("@solana/web3.js");
81
- var bs58_1 = __importDefault(require("bs58"));
82
- var p_queue_1 = __importDefault(require("p-queue"));
83
- var types_1 = require("./types");
84
- var utils_1 = require("../utils");
85
- var SIMULATE_TRIES = 3;
86
- var buildSendThrottler = function (sendRate) {
87
- return new p_queue_1.default({ concurrency: sendRate, intervalCap: 1, interval: 1000 });
88
- };
89
- exports.buildSendThrottler = buildSendThrottler;
90
- /**
91
- * Wrapper function for Solana web3 getProgramAccounts with slightly better call interface
92
- * @param {Connection} connection - Solana web3 connection object.
93
- * @param {PublicKey} wallet - PublicKey to compare against.
94
- * @param {number} offset - Offset of bits of the PublicKey in the account binary.
95
- * @param {PublicKey} programId - Solana program ID.
96
- * @return {Promise<Account[]>} - Array of resulting accounts.
97
- */
98
- function getProgramAccounts(connection, wallet, offset, programId) {
99
- return __awaiter(this, void 0, void 0, function () {
100
- var programAccounts;
101
- return __generator(this, function (_a) {
102
- switch (_a.label) {
103
- case 0: return [4 /*yield*/, (connection === null || connection === void 0 ? void 0 : connection.getProgramAccounts(programId, {
104
- filters: [
105
- {
106
- memcmp: {
107
- offset: offset,
108
- bytes: wallet.toBase58(),
109
- },
110
- },
111
- ],
112
- }))];
113
- case 1:
114
- programAccounts = _a.sent();
115
- return [2 /*return*/, __spreadArray([], __read(programAccounts), false)];
116
- }
117
- });
118
- });
119
- }
120
- exports.getProgramAccounts = getProgramAccounts;
121
- /**
122
- * Utility function to check if the transaction initiator is a Wallet object
123
- * @param {Keypair | SignerWalletAdapter} walletOrKeypair - Wallet or Keypair in question
124
- * @return {boolean} - Returns true if parameter is a Wallet.
125
- */
126
- function isSignerWallet(walletOrKeypair) {
127
- return walletOrKeypair.signTransaction !== undefined;
128
- }
129
- exports.isSignerWallet = isSignerWallet;
130
- /**
131
- * Utility function to check if the transaction initiator a Keypair object, tries to mitigate version mismatch issues
132
- * @param walletOrKeypair {Keypair | SignerWalletAdapter} walletOrKeypair - Wallet or Keypair in question
133
- * @returns {boolean} - Returns true if parameter is a Keypair.
134
- */
135
- function isSignerKeypair(walletOrKeypair) {
136
- return (walletOrKeypair instanceof web3_js_1.Keypair ||
137
- walletOrKeypair.constructor === web3_js_1.Keypair ||
138
- walletOrKeypair.constructor.name === web3_js_1.Keypair.prototype.constructor.name);
139
- }
140
- exports.isSignerKeypair = isSignerKeypair;
141
- /**
142
- * Utility function to check whether given transaction is Versioned
143
- * @param tx {Transaction | VersionedTransaction} - Transaction to check
144
- * @returns {boolean} - Returns true if transaction is Versioned.
145
- */
146
- function isTransactionVersioned(tx) {
147
- return "message" in tx;
148
- }
149
- exports.isTransactionVersioned = isTransactionVersioned;
150
- /**
151
- * Creates a Transaction with given instructions and optionally signs it.
152
- * @param connection - Solana client connection
153
- * @param ixs - Instructions to add to the Transaction
154
- * @param payer - PublicKey of payer
155
- * @param commitment - optional Commitment that will be used to fetch latest blockhash
156
- * @param partialSigners - optional signers that will be used to partially sign a Transaction
157
- * @returns Transaction and Blockhash
158
- */
159
- function prepareTransaction(connection, ixs, payer, commitment) {
160
- var partialSigners = [];
161
- for (var _i = 4; _i < arguments.length; _i++) {
162
- partialSigners[_i - 4] = arguments[_i];
163
- }
164
- return __awaiter(this, void 0, void 0, function () {
165
- var _a, hash, context, messageV0, tx, signers;
166
- return __generator(this, function (_b) {
167
- switch (_b.label) {
168
- case 0:
169
- if (!payer) {
170
- throw new Error("Payer public key is not provided!");
171
- }
172
- return [4 /*yield*/, connection.getLatestBlockhashAndContext(commitment)];
173
- case 1:
174
- _a = _b.sent(), hash = _a.value, context = _a.context;
175
- messageV0 = new web3_js_1.TransactionMessage({
176
- payerKey: payer,
177
- recentBlockhash: hash.blockhash,
178
- instructions: ixs,
179
- }).compileToV0Message();
180
- tx = new web3_js_1.VersionedTransaction(messageV0);
181
- signers = partialSigners.filter(function (item) { return !!item; });
182
- tx.sign(signers);
183
- return [2 /*return*/, { tx: tx, context: context, hash: hash }];
184
- }
185
- });
186
- });
187
- }
188
- exports.prepareTransaction = prepareTransaction;
189
- function signTransaction(invoker, tx) {
190
- return __awaiter(this, void 0, void 0, function () {
191
- var signedTx;
192
- return __generator(this, function (_a) {
193
- switch (_a.label) {
194
- case 0:
195
- if (!isSignerWallet(invoker)) return [3 /*break*/, 2];
196
- return [4 /*yield*/, invoker.signTransaction(tx)];
197
- case 1:
198
- signedTx = _a.sent();
199
- return [3 /*break*/, 3];
200
- case 2:
201
- if (isTransactionVersioned(tx)) {
202
- tx.sign([invoker]);
203
- }
204
- else {
205
- tx.partialSign(invoker);
206
- }
207
- signedTx = tx;
208
- _a.label = 3;
209
- case 3: return [2 /*return*/, signedTx];
210
- }
211
- });
212
- });
213
- }
214
- exports.signTransaction = signTransaction;
215
- /**
216
- * Signs, sends and confirms Transaction
217
- * @param connection - Solana client connection
218
- * @param invoker - Keypair used as signer
219
- * @param tx - Transaction instance
220
- * @param confirmationParams - Confirmation Params that will be used for execution
221
- * @param throttleParams - rate or throttler instance to throttle TX sending - to not spam the blockchain too much
222
- * @returns Transaction signature
223
- */
224
- function signAndExecuteTransaction(connection, invoker, tx, confirmationParams, throttleParams) {
225
- return __awaiter(this, void 0, void 0, function () {
226
- var signedTx;
227
- return __generator(this, function (_a) {
228
- switch (_a.label) {
229
- case 0: return [4 /*yield*/, signTransaction(invoker, tx)];
230
- case 1:
231
- signedTx = _a.sent();
232
- return [2 /*return*/, executeTransaction(connection, signedTx, confirmationParams, throttleParams)];
233
- }
234
- });
235
- });
236
- }
237
- exports.signAndExecuteTransaction = signAndExecuteTransaction;
238
- /**
239
- * Sends and confirms Transaction
240
- * Uses custom confirmation logic that:
241
- * - simulates tx before sending separately
242
- * - sends transaction without preFlight checks but with some valuable flags https://twitter.com/jordaaash/status/1774892862049800524?s=46&t=bhZ10V0r7IX5Lk5kKzxfGw
243
- * - rebroadcasts a tx every 500 ms
244
- * - after broadcasting check whether tx has executed once
245
- * - catch errors for every actionable item, throw only the ones that signal that tx has failed
246
- * - otherwise there is a chance of marking a landed tx as failed if it was broadcasted at least once
247
- * @param connection - Solana client connection
248
- * @param tx - Transaction instance
249
- * @param confirmationParams - Confirmation Params that will be used for execution
250
- * @param throttleParams - rate or throttler instance to throttle TX sending - to not spam the blockchain too much
251
- * @returns Transaction signature
252
- */
253
- function executeTransaction(connection, tx, confirmationParams, throttleParams) {
254
- return __awaiter(this, void 0, void 0, function () {
255
- return __generator(this, function (_a) {
256
- switch (_a.label) {
257
- case 0:
258
- if (tx.signatures.length === 0) {
259
- throw Error("Error with transaction parameters.");
260
- }
261
- return [4 /*yield*/, simulateTransaction(connection, tx)];
262
- case 1:
263
- _a.sent();
264
- return [2 /*return*/, sendAndConfirmTransaction(connection, tx, confirmationParams, throttleParams)];
265
- }
266
- });
267
- });
268
- }
269
- exports.executeTransaction = executeTransaction;
270
- /**
271
- * Launches a PromisePool with all transaction being executed at the same time, allows to throttle all TXs through one Queue
272
- * @param connection - Solana client connection
273
- * @param txs - Transactions
274
- * @param confirmationParams - Confirmation Params that will be used for execution
275
- * @param throttleParams - rate or throttler instance to throttle TX sending - to not spam the blockchain too much
276
- * @param throttleParams.sendRate - rate
277
- * @param throttleParams.sendThrottler - throttler instance
278
- * @returns Raw Promise Results - should be handled by the consumer and unwrapped accordingly
279
- */
280
- function executeMultipleTransactions(connection, txs, confirmationParams, _a) {
281
- var _b = _a.sendRate, sendRate = _b === void 0 ? 1 : _b, sendThrottler = _a.sendThrottler;
282
- return __awaiter(this, void 0, void 0, function () {
283
- return __generator(this, function (_c) {
284
- if (!sendThrottler) {
285
- sendThrottler = (0, exports.buildSendThrottler)(sendRate);
286
- }
287
- return [2 /*return*/, Promise.allSettled(txs.map(function (tx) {
288
- return executeTransaction(connection, tx, confirmationParams, { sendRate: sendRate, sendThrottler: sendThrottler });
289
- }))];
290
- });
291
- });
292
- }
293
- exports.executeMultipleTransactions = executeMultipleTransactions;
294
- /**
295
- * Sends and confirm transaction in a loop, constantly re-broadcsting the tx until Blockheight expires.
296
- * - we add additional 30 bocks to account for validators in an PRC pool divergence
297
- * @param connection - Solana client connection
298
- * @param tx - Transaction instance
299
- * @param confirmationParams - Confirmation Params that will be used for execution
300
- * @param confirmationParams.hash - blockhash information, the same hash should be used in the Transaction
301
- * @param confirmationParams.context - context at which blockhash has been retrieve
302
- * @param confirmationParams.commitment - optional commitment that will be used for simulation and confirmation
303
- * @param throttleParams - rate or throttler instance to throttle TX sending - to not spam the blockchain too much
304
- * @param throttleParams.sendRate - rate
305
- * @param throttleParams.sendThrottler - throttler instance
306
- */
307
- function sendAndConfirmTransaction(connection, tx, _a, _b) {
308
- var hash = _a.hash, context = _a.context, commitment = _a.commitment;
309
- var _c = _b.sendRate, sendRate = _c === void 0 ? 1 : _c, sendThrottler = _b.sendThrottler;
310
- return __awaiter(this, void 0, void 0, function () {
311
- var isVersioned, signature, blockheight, transactionSent, rawTransaction, e_1, value, e_2, _e_1;
312
- var _this = this;
313
- return __generator(this, function (_d) {
314
- switch (_d.label) {
315
- case 0:
316
- isVersioned = isTransactionVersioned(tx);
317
- if (isVersioned) {
318
- signature = bs58_1.default.encode(tx.signatures[0]);
319
- }
320
- else {
321
- signature = bs58_1.default.encode(tx.signature);
322
- }
323
- if (!sendThrottler) {
324
- sendThrottler = (0, exports.buildSendThrottler)(sendRate);
325
- }
326
- return [4 /*yield*/, connection.getBlockHeight(commitment)];
327
- case 1:
328
- blockheight = _d.sent();
329
- transactionSent = false;
330
- rawTransaction = tx.serialize();
331
- _d.label = 2;
332
- case 2:
333
- if (!(blockheight < hash.lastValidBlockHeight + 15)) return [3 /*break*/, 20];
334
- _d.label = 3;
335
- case 3:
336
- _d.trys.push([3, 6, , 9]);
337
- if (!(blockheight < hash.lastValidBlockHeight || !transactionSent)) return [3 /*break*/, 5];
338
- return [4 /*yield*/, sendThrottler.add(function () { return __awaiter(_this, void 0, void 0, function () {
339
- return __generator(this, function (_a) {
340
- return [2 /*return*/, connection.sendRawTransaction(rawTransaction, {
341
- maxRetries: 0,
342
- minContextSlot: context.slot,
343
- preflightCommitment: commitment,
344
- skipPreflight: true,
345
- })];
346
- });
347
- }); })];
348
- case 4:
349
- _d.sent();
350
- transactionSent = true;
351
- _d.label = 5;
352
- case 5: return [3 /*break*/, 9];
353
- case 6:
354
- e_1 = _d.sent();
355
- if (!(transactionSent ||
356
- (e_1 instanceof web3_js_1.SendTransactionError && e_1.message.includes("Minimum context slot has not been reached")))) return [3 /*break*/, 8];
357
- return [4 /*yield*/, (0, utils_1.sleep)(500)];
358
- case 7:
359
- _d.sent();
360
- return [3 /*break*/, 2];
361
- case 8: throw e_1;
362
- case 9: return [4 /*yield*/, (0, utils_1.sleep)(500)];
363
- case 10:
364
- _d.sent();
365
- _d.label = 11;
366
- case 11:
367
- _d.trys.push([11, 13, , 15]);
368
- return [4 /*yield*/, confirmAndEnsureTransaction(connection, signature)];
369
- case 12:
370
- value = _d.sent();
371
- if (value) {
372
- return [2 /*return*/, signature];
373
- }
374
- return [3 /*break*/, 15];
375
- case 13:
376
- e_2 = _d.sent();
377
- if (e_2 instanceof types_1.TransactionFailedError) {
378
- throw e_2;
379
- }
380
- return [4 /*yield*/, (0, utils_1.sleep)(500)];
381
- case 14:
382
- _d.sent();
383
- return [3 /*break*/, 15];
384
- case 15:
385
- _d.trys.push([15, 17, , 19]);
386
- return [4 /*yield*/, connection.getBlockHeight(commitment)];
387
- case 16:
388
- blockheight = _d.sent();
389
- return [3 /*break*/, 19];
390
- case 17:
391
- _e_1 = _d.sent();
392
- return [4 /*yield*/, (0, utils_1.sleep)(500)];
393
- case 18:
394
- _d.sent();
395
- return [3 /*break*/, 19];
396
- case 19: return [3 /*break*/, 2];
397
- case 20: throw new Error("Transaction ".concat(signature, " expired."));
398
- }
399
- });
400
- });
401
- }
402
- exports.sendAndConfirmTransaction = sendAndConfirmTransaction;
403
- function simulateTransaction(connection, tx) {
404
- return __awaiter(this, void 0, void 0, function () {
405
- var res, i, errMessage;
406
- return __generator(this, function (_a) {
407
- switch (_a.label) {
408
- case 0:
409
- i = 0;
410
- _a.label = 1;
411
- case 1:
412
- if (!(i < SIMULATE_TRIES)) return [3 /*break*/, 7];
413
- if (!isTransactionVersioned(tx)) return [3 /*break*/, 3];
414
- return [4 /*yield*/, connection.simulateTransaction(tx)];
415
- case 2:
416
- res = _a.sent();
417
- return [3 /*break*/, 5];
418
- case 3: return [4 /*yield*/, connection.simulateTransaction(tx)];
419
- case 4:
420
- res = _a.sent();
421
- _a.label = 5;
422
- case 5:
423
- if (res.value.err) {
424
- errMessage = JSON.stringify(res.value.err);
425
- if (!errMessage.includes("BlockhashNotFound") || i === SIMULATE_TRIES - 1) {
426
- throw new web3_js_1.SendTransactionError("failed to simulate transaction: " + errMessage, res.value.logs || undefined);
427
- }
428
- return [3 /*break*/, 6];
429
- }
430
- return [2 /*return*/, res];
431
- case 6:
432
- i++;
433
- return [3 /*break*/, 1];
434
- case 7: throw new web3_js_1.SendTransactionError("failed to simulate transaction");
435
- }
436
- });
437
- });
438
- }
439
- exports.simulateTransaction = simulateTransaction;
440
- /**
441
- * Confirms and validates transaction success once
442
- * @param connection - Solana client connection
443
- * @param signature - Transaction signature
444
- * @param ignoreError - return status even if tx failed
445
- * @returns Transaction Status
446
- */
447
- function confirmAndEnsureTransaction(connection, signature, ignoreError) {
448
- return __awaiter(this, void 0, void 0, function () {
449
- var response, value;
450
- return __generator(this, function (_a) {
451
- switch (_a.label) {
452
- case 0: return [4 /*yield*/, connection.getSignatureStatuses([signature])];
453
- case 1:
454
- response = _a.sent();
455
- if (!response || response.value.length === 0 || response.value[0] === null) {
456
- return [2 /*return*/, null];
457
- }
458
- value = response.value[0];
459
- if (!value) {
460
- return [2 /*return*/, null];
461
- }
462
- if (!ignoreError && value.err) {
463
- // That's how solana-web3js does it, `err` here is an object that won't really be handled
464
- throw new types_1.TransactionFailedError("Raw transaction ".concat(signature, " failed (").concat(JSON.stringify({ err: value.err }), ")"));
465
- }
466
- switch (connection.commitment) {
467
- case "confirmed":
468
- case "single":
469
- case "singleGossip": {
470
- if (value.confirmationStatus === "processed") {
471
- return [2 /*return*/, null];
472
- }
473
- break;
474
- }
475
- case "finalized":
476
- case "max":
477
- case "root": {
478
- if (value.confirmationStatus === "processed" || value.confirmationStatus === "confirmed") {
479
- return [2 /*return*/, null];
480
- }
481
- break;
482
- }
483
- // exhaust enums to ensure full coverage
484
- case "processed":
485
- case "recent":
486
- }
487
- return [2 /*return*/, value];
488
- }
489
- });
490
- });
491
- }
492
- exports.confirmAndEnsureTransaction = confirmAndEnsureTransaction;
493
- /**
494
- * Shorthand call signature for getAssociatedTokenAddress, with allowance for address to be offCurve
495
- * @param {PublicKey} mint - SPL token Mint address.
496
- * @param {PublicKey} owner - Owner of the Associated Token Address
497
- * @param {PublicKey} programId - Program ID of the mint
498
- * @return {Promise<PublicKey>} - Associated Token Address
499
- */
500
- function ata(mint, owner, programId) {
501
- return (0, spl_token_1.getAssociatedTokenAddress)(mint, owner, true, programId);
502
- }
503
- exports.ata = ata;
504
- /**
505
- * Function that checks whether ATA exists for each provided owner
506
- * @param connection - Solana client connection
507
- * @param paramsBatch - Array of Params for each ATA account: {mint, owner}
508
- * @returns Array of boolean where each member corresponds to an owner
509
- */
510
- function ataBatchExist(connection, paramsBatch) {
511
- return __awaiter(this, void 0, void 0, function () {
512
- var tokenAccounts, response;
513
- var _this = this;
514
- return __generator(this, function (_a) {
515
- switch (_a.label) {
516
- case 0: return [4 /*yield*/, Promise.all(paramsBatch.map(function (_a) {
517
- var mint = _a.mint, owner = _a.owner, programId = _a.programId;
518
- return __awaiter(_this, void 0, void 0, function () {
519
- return __generator(this, function (_b) {
520
- return [2 /*return*/, ata(mint, owner, programId)];
521
- });
522
- });
523
- }))];
524
- case 1:
525
- tokenAccounts = _a.sent();
526
- return [4 /*yield*/, connection.getMultipleAccountsInfo(tokenAccounts)];
527
- case 2:
528
- response = _a.sent();
529
- return [2 /*return*/, response.map(function (accInfo) { return !!accInfo; })];
530
- }
531
- });
532
- });
533
- }
534
- exports.ataBatchExist = ataBatchExist;
535
- function enrichAtaParams(connection, paramsBatch) {
536
- return __awaiter(this, void 0, void 0, function () {
537
- var programIdByMint;
538
- var _this = this;
539
- return __generator(this, function (_a) {
540
- programIdByMint = {};
541
- return [2 /*return*/, Promise.all(paramsBatch.map(function (params) { return __awaiter(_this, void 0, void 0, function () {
542
- var mintStr, tokenProgramId;
543
- return __generator(this, function (_a) {
544
- switch (_a.label) {
545
- case 0:
546
- if (params.programId) {
547
- return [2 /*return*/, params];
548
- }
549
- mintStr = params.mint.toString();
550
- if (!!(mintStr in programIdByMint)) return [3 /*break*/, 2];
551
- return [4 /*yield*/, getMintAndProgram(connection, params.mint)];
552
- case 1:
553
- tokenProgramId = (_a.sent()).tokenProgramId;
554
- programIdByMint[mintStr] = tokenProgramId;
555
- _a.label = 2;
556
- case 2:
557
- params.programId = programIdByMint[mintStr];
558
- return [2 /*return*/, params];
559
- }
560
- });
561
- }); }))];
562
- });
563
- });
564
- }
565
- exports.enrichAtaParams = enrichAtaParams;
566
- /**
567
- * Generates a Transaction to create ATA for an array of owners
568
- * @param connection - Solana client connection
569
- * @param payer - Transaction invoker, should be a signer
570
- * @param paramsBatch - Array of Params for an each ATA account: {mint, owner}
571
- * @param commitment - optional commitment that will be used to fetch Blockhash
572
- * @returns Unsigned Transaction with create ATA instructions
573
- */
574
- function generateCreateAtaBatchTx(connection, payer, paramsBatch, commitment) {
575
- return __awaiter(this, void 0, void 0, function () {
576
- var ixs, _a, hash, context, messageV0, tx;
577
- var _this = this;
578
- return __generator(this, function (_b) {
579
- switch (_b.label) {
580
- case 0: return [4 /*yield*/, enrichAtaParams(connection, paramsBatch)];
581
- case 1:
582
- paramsBatch = _b.sent();
583
- return [4 /*yield*/, Promise.all(paramsBatch.map(function (_a) {
584
- var mint = _a.mint, owner = _a.owner, programId = _a.programId;
585
- return __awaiter(_this, void 0, void 0, function () {
586
- var _b, _c;
587
- return __generator(this, function (_d) {
588
- switch (_d.label) {
589
- case 0:
590
- _b = spl_token_1.createAssociatedTokenAccountInstruction;
591
- _c = [payer];
592
- return [4 /*yield*/, ata(mint, owner)];
593
- case 1: return [2 /*return*/, _b.apply(void 0, _c.concat([_d.sent(), owner, mint, programId]))];
594
- }
595
- });
596
- });
597
- }))];
598
- case 2:
599
- ixs = _b.sent();
600
- return [4 /*yield*/, connection.getLatestBlockhashAndContext({ commitment: commitment })];
601
- case 3:
602
- _a = _b.sent(), hash = _a.value, context = _a.context;
603
- messageV0 = new web3_js_1.TransactionMessage({
604
- payerKey: payer,
605
- recentBlockhash: hash.blockhash,
606
- instructions: ixs,
607
- }).compileToV0Message();
608
- tx = new web3_js_1.VersionedTransaction(messageV0);
609
- return [2 /*return*/, { tx: tx, hash: hash, context: context }];
610
- }
611
- });
612
- });
613
- }
614
- exports.generateCreateAtaBatchTx = generateCreateAtaBatchTx;
615
- /**
616
- * Creates ATA for an array of owners
617
- * @param connection - Solana client connection
618
- * @param invoker - Transaction invoker and payer
619
- * @param paramsBatch - Array of Params for an each ATA account: {mint, owner}
620
- * @param commitment - optional commitment that will be used to fetch Blockhash
621
- * @param rate - throttle rate for tx sending
622
- * @returns Transaction signature
623
- */
624
- function createAtaBatch(connection, invoker, paramsBatch, commitment, rate) {
625
- return __awaiter(this, void 0, void 0, function () {
626
- var _a, tx, hash, context, _b, _c;
627
- return __generator(this, function (_d) {
628
- switch (_d.label) {
629
- case 0:
630
- _b = generateCreateAtaBatchTx;
631
- _c = [connection,
632
- invoker.publicKey];
633
- return [4 /*yield*/, enrichAtaParams(connection, paramsBatch)];
634
- case 1: return [4 /*yield*/, _b.apply(void 0, _c.concat([_d.sent(), commitment]))];
635
- case 2:
636
- _a = _d.sent(), tx = _a.tx, hash = _a.hash, context = _a.context;
637
- return [2 /*return*/, signAndExecuteTransaction(connection, invoker, tx, { hash: hash, context: context, commitment: commitment }, { sendRate: rate })];
638
- }
639
- });
640
- });
641
- }
642
- exports.createAtaBatch = createAtaBatch;
643
- /**
644
- * Utility function that checks whether associated token accounts exist and return instructions to populate them if not
645
- * @param connection - Solana client connection
646
- * @param owners - Array of ATA owners
647
- * @param mint - Mint for which ATA will be checked
648
- * @param invoker - Transaction invoker and payer
649
- * @param programId - Program ID of the Mint
650
- * @returns Array of Transaction Instructions that should be added to a transaction
651
- */
652
- function checkOrCreateAtaBatch(connection, owners, mint, invoker, programId) {
653
- return __awaiter(this, void 0, void 0, function () {
654
- var ixs, atas, owners_1, owners_1_1, owner, _a, _b, e_3_1, response, i;
655
- var e_3, _c;
656
- return __generator(this, function (_d) {
657
- switch (_d.label) {
658
- case 0:
659
- ixs = [];
660
- if (!!programId) return [3 /*break*/, 2];
661
- return [4 /*yield*/, getMintAndProgram(connection, mint)];
662
- case 1:
663
- programId = (_d.sent()).tokenProgramId;
664
- _d.label = 2;
665
- case 2:
666
- atas = [];
667
- _d.label = 3;
668
- case 3:
669
- _d.trys.push([3, 8, 9, 10]);
670
- owners_1 = __values(owners), owners_1_1 = owners_1.next();
671
- _d.label = 4;
672
- case 4:
673
- if (!!owners_1_1.done) return [3 /*break*/, 7];
674
- owner = owners_1_1.value;
675
- _b = (_a = atas).push;
676
- return [4 /*yield*/, ata(mint, owner, programId)];
677
- case 5:
678
- _b.apply(_a, [_d.sent()]);
679
- _d.label = 6;
680
- case 6:
681
- owners_1_1 = owners_1.next();
682
- return [3 /*break*/, 4];
683
- case 7: return [3 /*break*/, 10];
684
- case 8:
685
- e_3_1 = _d.sent();
686
- e_3 = { error: e_3_1 };
687
- return [3 /*break*/, 10];
688
- case 9:
689
- try {
690
- if (owners_1_1 && !owners_1_1.done && (_c = owners_1.return)) _c.call(owners_1);
691
- }
692
- finally { if (e_3) throw e_3.error; }
693
- return [7 /*endfinally*/];
694
- case 10: return [4 /*yield*/, connection.getMultipleAccountsInfo(atas)];
695
- case 11:
696
- response = _d.sent();
697
- for (i = 0; i < response.length; i++) {
698
- if (!response[i]) {
699
- ixs.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(invoker.publicKey, atas[i], owners[i], mint, programId));
700
- }
701
- }
702
- return [2 /*return*/, ixs];
703
- }
704
- });
705
- });
706
- }
707
- exports.checkOrCreateAtaBatch = checkOrCreateAtaBatch;
708
- /**
709
- * Create Base instructions for Solana
710
- * - sets compute price if `computePrice` is provided
711
- * - sets compute limit if `computeLimit` is provided
712
- */
713
- function prepareBaseInstructions(connection, _a) {
714
- var computePrice = _a.computePrice, computeLimit = _a.computeLimit;
715
- var ixs = [];
716
- if (computePrice) {
717
- ixs.push(web3_js_1.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: computePrice }));
718
- }
719
- if (computeLimit) {
720
- ixs.push(web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: computeLimit }));
721
- }
722
- return ixs;
723
- }
724
- exports.prepareBaseInstructions = prepareBaseInstructions;
725
- /**
726
- * Retrieve information about a mint and its program ID, support all Token Programs.
727
- *
728
- * @param connection Connection to use
729
- * @param address Mint account
730
- * @param commitment Desired level of commitment for querying the state
731
- *
732
- * @return Mint information
733
- */
734
- function getMintAndProgram(connection, address, commitment) {
735
- return __awaiter(this, void 0, void 0, function () {
736
- var accountInfo, programId;
737
- return __generator(this, function (_a) {
738
- switch (_a.label) {
739
- case 0: return [4 /*yield*/, connection.getAccountInfo(address, commitment)];
740
- case 1:
741
- accountInfo = _a.sent();
742
- programId = accountInfo === null || accountInfo === void 0 ? void 0 : accountInfo.owner;
743
- if (!(programId === null || programId === void 0 ? void 0 : programId.equals(spl_token_1.TOKEN_PROGRAM_ID)) && !(programId === null || programId === void 0 ? void 0 : programId.equals(spl_token_1.TOKEN_2022_PROGRAM_ID))) {
744
- programId = spl_token_1.TOKEN_PROGRAM_ID;
745
- }
746
- return [2 /*return*/, {
747
- mint: (0, spl_token_1.unpackMint)(address, accountInfo, programId),
748
- tokenProgramId: programId,
749
- }];
750
- }
751
- });
752
- });
753
- }
754
- exports.getMintAndProgram = getMintAndProgram;