@streamflow/common 7.0.0-alpha.3 → 7.0.0-alpha.6

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,92 +1,22 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
64
3
  exports.prepareWrappedAccount = void 0;
65
- var spl_token_1 = require("@solana/spl-token");
66
- var web3_js_1 = require("@solana/web3.js");
67
- var prepareWrappedAccount = function (connection, senderAddress, amount) { return __awaiter(void 0, void 0, void 0, function () {
68
- var tokenAccount, accInfo, instructions;
69
- var _a, _b;
70
- return __generator(this, function (_c) {
71
- switch (_c.label) {
72
- case 0: return [4 /*yield*/, (0, spl_token_1.getAssociatedTokenAddress)(spl_token_1.NATIVE_MINT, senderAddress, true)];
73
- case 1:
74
- tokenAccount = _c.sent();
75
- return [4 /*yield*/, connection.getParsedAccountInfo(tokenAccount)];
76
- case 2:
77
- accInfo = _c.sent();
78
- instructions = ((_b = (_a = accInfo.value) === null || _a === void 0 ? void 0 : _a.lamports) !== null && _b !== void 0 ? _b : 0) > 0
79
- ? []
80
- : [(0, spl_token_1.createAssociatedTokenAccountInstruction)(senderAddress, tokenAccount, senderAddress, spl_token_1.NATIVE_MINT)];
81
- return [2 /*return*/, __spreadArray(__spreadArray([], __read(instructions), false), [
82
- web3_js_1.SystemProgram.transfer({
83
- fromPubkey: senderAddress,
84
- toPubkey: tokenAccount,
85
- lamports: amount.toNumber(),
86
- }),
87
- (0, spl_token_1.createSyncNativeInstruction)(tokenAccount),
88
- ], false)];
89
- }
90
- });
91
- }); };
4
+ const spl_token_1 = require("@solana/spl-token");
5
+ const web3_js_1 = require("@solana/web3.js");
6
+ const prepareWrappedAccount = async (connection, senderAddress, amount) => {
7
+ const tokenAccount = await (0, spl_token_1.getAssociatedTokenAddress)(spl_token_1.NATIVE_MINT, senderAddress, true);
8
+ const accInfo = await connection.getParsedAccountInfo(tokenAccount);
9
+ const instructions = (accInfo.value?.lamports ?? 0) > 0
10
+ ? []
11
+ : [(0, spl_token_1.createAssociatedTokenAccountInstruction)(senderAddress, tokenAccount, senderAddress, spl_token_1.NATIVE_MINT)];
12
+ return [
13
+ ...instructions,
14
+ web3_js_1.SystemProgram.transfer({
15
+ fromPubkey: senderAddress,
16
+ toPubkey: tokenAccount,
17
+ lamports: amount.toNumber(),
18
+ }),
19
+ (0, spl_token_1.createSyncNativeInstruction)(tokenAccount),
20
+ ];
21
+ };
92
22
  exports.prepareWrappedAccount = prepareWrappedAccount;
@@ -1,29 +1,11 @@
1
1
  "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
2
  Object.defineProperty(exports, "__esModule", { value: true });
18
3
  exports.TransactionFailedError = void 0;
19
- var TransactionFailedError = /** @class */ (function (_super) {
20
- __extends(TransactionFailedError, _super);
21
- function TransactionFailedError(m) {
22
- var _this = _super.call(this, m) || this;
23
- Object.setPrototypeOf(_this, TransactionFailedError.prototype);
24
- _this.name = "TransactionFailedError";
25
- return _this;
4
+ class TransactionFailedError extends Error {
5
+ constructor(m) {
6
+ super(m);
7
+ Object.setPrototypeOf(this, TransactionFailedError.prototype);
8
+ this.name = "TransactionFailedError";
26
9
  }
27
- return TransactionFailedError;
28
- }(Error));
10
+ }
29
11
  exports.TransactionFailedError = TransactionFailedError;
@@ -1,64 +1,17 @@
1
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 __values = (this && this.__values) || function(o) {
39
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
40
- if (m) return m.call(o);
41
- if (o && typeof o.length === "number") return {
42
- next: function () {
43
- if (o && i >= o.length) o = void 0;
44
- return { value: o && o[i++], done: !o };
45
- }
46
- };
47
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
48
- };
49
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
50
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
51
4
  };
52
5
  Object.defineProperty(exports, "__esModule", { value: true });
53
6
  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;
54
- var spl_token_1 = require("@solana/spl-token");
55
- var web3_js_1 = require("@solana/web3.js");
56
- var bs58_1 = __importDefault(require("bs58"));
57
- var p_queue_1 = __importDefault(require("p-queue"));
58
- var types_js_1 = require("./types.js");
59
- var utils_js_1 = require("../utils.js");
60
- var SIMULATE_TRIES = 3;
61
- var buildSendThrottler = function (sendRate) {
7
+ const spl_token_1 = require("@solana/spl-token");
8
+ const web3_js_1 = require("@solana/web3.js");
9
+ const bs58_1 = __importDefault(require("bs58"));
10
+ const p_queue_1 = __importDefault(require("p-queue"));
11
+ const types_js_1 = require("./types.js");
12
+ const utils_js_1 = require("../utils.js");
13
+ const SIMULATE_TRIES = 3;
14
+ const buildSendThrottler = (sendRate) => {
62
15
  return new p_queue_1.default({ concurrency: sendRate, intervalCap: 1, interval: 1000 });
63
16
  };
64
17
  exports.buildSendThrottler = buildSendThrottler;
@@ -70,20 +23,16 @@ exports.buildSendThrottler = buildSendThrottler;
70
23
  * @param {PublicKey} programId - Solana program ID.
71
24
  * @return {Promise<Account[]>} - Array of resulting accounts.
72
25
  */
73
- function getProgramAccounts(connection, wallet, offset, programId) {
74
- return __awaiter(this, void 0, void 0, function () {
75
- return __generator(this, function (_a) {
76
- return [2 /*return*/, connection === null || connection === void 0 ? void 0 : connection.getProgramAccounts(programId, {
77
- filters: [
78
- {
79
- memcmp: {
80
- offset: offset,
81
- bytes: wallet.toBase58(),
82
- },
83
- },
84
- ],
85
- })];
86
- });
26
+ async function getProgramAccounts(connection, wallet, offset, programId) {
27
+ return connection?.getProgramAccounts(programId, {
28
+ filters: [
29
+ {
30
+ memcmp: {
31
+ offset,
32
+ bytes: wallet.toBase58(),
33
+ },
34
+ },
35
+ ],
87
36
  });
88
37
  }
89
38
  exports.getProgramAccounts = getProgramAccounts;
@@ -125,60 +74,37 @@ exports.isTransactionVersioned = isTransactionVersioned;
125
74
  * @param partialSigners - optional signers that will be used to partially sign a Transaction
126
75
  * @returns Transaction and Blockhash
127
76
  */
128
- function prepareTransaction(connection, ixs, payer, commitment) {
129
- var partialSigners = [];
130
- for (var _i = 4; _i < arguments.length; _i++) {
131
- partialSigners[_i - 4] = arguments[_i];
77
+ async function prepareTransaction(connection, ixs, payer, commitment, ...partialSigners) {
78
+ if (!payer) {
79
+ throw new Error("Payer public key is not provided!");
132
80
  }
133
- return __awaiter(this, void 0, void 0, function () {
134
- var _a, hash, context, messageV0, tx, signers;
135
- return __generator(this, function (_b) {
136
- switch (_b.label) {
137
- case 0:
138
- if (!payer) {
139
- throw new Error("Payer public key is not provided!");
140
- }
141
- return [4 /*yield*/, connection.getLatestBlockhashAndContext(commitment)];
142
- case 1:
143
- _a = _b.sent(), hash = _a.value, context = _a.context;
144
- messageV0 = new web3_js_1.TransactionMessage({
145
- payerKey: payer,
146
- recentBlockhash: hash.blockhash,
147
- instructions: ixs,
148
- }).compileToV0Message();
149
- tx = new web3_js_1.VersionedTransaction(messageV0);
150
- signers = partialSigners.filter(function (item) { return !!item; });
151
- tx.sign(signers);
152
- return [2 /*return*/, { tx: tx, context: context, hash: hash }];
153
- }
154
- });
155
- });
81
+ const { value: hash, context } = await connection.getLatestBlockhashAndContext(commitment);
82
+ const messageV0 = new web3_js_1.TransactionMessage({
83
+ payerKey: payer,
84
+ recentBlockhash: hash.blockhash,
85
+ instructions: ixs,
86
+ }).compileToV0Message();
87
+ const tx = new web3_js_1.VersionedTransaction(messageV0);
88
+ const signers = partialSigners.filter((item) => !!item);
89
+ tx.sign(signers);
90
+ return { tx, context, hash };
156
91
  }
157
92
  exports.prepareTransaction = prepareTransaction;
158
- function signTransaction(invoker, tx) {
159
- return __awaiter(this, void 0, void 0, function () {
160
- var signedTx;
161
- return __generator(this, function (_a) {
162
- switch (_a.label) {
163
- case 0:
164
- if (!isSignerWallet(invoker)) return [3 /*break*/, 2];
165
- return [4 /*yield*/, invoker.signTransaction(tx)];
166
- case 1:
167
- signedTx = _a.sent();
168
- return [3 /*break*/, 3];
169
- case 2:
170
- if (isTransactionVersioned(tx)) {
171
- tx.sign([invoker]);
172
- }
173
- else {
174
- tx.partialSign(invoker);
175
- }
176
- signedTx = tx;
177
- _a.label = 3;
178
- case 3: return [2 /*return*/, signedTx];
179
- }
180
- });
181
- });
93
+ async function signTransaction(invoker, tx) {
94
+ let signedTx;
95
+ if (isSignerWallet(invoker)) {
96
+ signedTx = await invoker.signTransaction(tx);
97
+ }
98
+ else {
99
+ if (isTransactionVersioned(tx)) {
100
+ tx.sign([invoker]);
101
+ }
102
+ else {
103
+ tx.partialSign(invoker);
104
+ }
105
+ signedTx = tx;
106
+ }
107
+ return signedTx;
182
108
  }
183
109
  exports.signTransaction = signTransaction;
184
110
  /**
@@ -190,18 +116,9 @@ exports.signTransaction = signTransaction;
190
116
  * @param throttleParams - rate or throttler instance to throttle TX sending - to not spam the blockchain too much
191
117
  * @returns Transaction signature
192
118
  */
193
- function signAndExecuteTransaction(connection, invoker, tx, confirmationParams, throttleParams) {
194
- return __awaiter(this, void 0, void 0, function () {
195
- var signedTx;
196
- return __generator(this, function (_a) {
197
- switch (_a.label) {
198
- case 0: return [4 /*yield*/, signTransaction(invoker, tx)];
199
- case 1:
200
- signedTx = _a.sent();
201
- return [2 /*return*/, executeTransaction(connection, signedTx, confirmationParams, throttleParams)];
202
- }
203
- });
204
- });
119
+ async function signAndExecuteTransaction(connection, invoker, tx, confirmationParams, throttleParams) {
120
+ const signedTx = await signTransaction(invoker, tx);
121
+ return executeTransaction(connection, signedTx, confirmationParams, throttleParams);
205
122
  }
206
123
  exports.signAndExecuteTransaction = signAndExecuteTransaction;
207
124
  /**
@@ -219,21 +136,12 @@ exports.signAndExecuteTransaction = signAndExecuteTransaction;
219
136
  * @param throttleParams - rate or throttler instance to throttle TX sending - to not spam the blockchain too much
220
137
  * @returns Transaction signature
221
138
  */
222
- function executeTransaction(connection, tx, confirmationParams, throttleParams) {
223
- return __awaiter(this, void 0, void 0, function () {
224
- return __generator(this, function (_a) {
225
- switch (_a.label) {
226
- case 0:
227
- if (tx.signatures.length === 0) {
228
- throw Error("Error with transaction parameters.");
229
- }
230
- return [4 /*yield*/, simulateTransaction(connection, tx)];
231
- case 1:
232
- _a.sent();
233
- return [2 /*return*/, sendAndConfirmTransaction(connection, tx, confirmationParams, throttleParams)];
234
- }
235
- });
236
- });
139
+ async function executeTransaction(connection, tx, confirmationParams, throttleParams) {
140
+ if (tx.signatures.length === 0) {
141
+ throw Error("Error with transaction parameters.");
142
+ }
143
+ await simulateTransaction(connection, tx);
144
+ return sendAndConfirmTransaction(connection, tx, confirmationParams, throttleParams);
237
145
  }
238
146
  exports.executeTransaction = executeTransaction;
239
147
  /**
@@ -246,18 +154,11 @@ exports.executeTransaction = executeTransaction;
246
154
  * @param throttleParams.sendThrottler - throttler instance
247
155
  * @returns Raw Promise Results - should be handled by the consumer and unwrapped accordingly
248
156
  */
249
- function executeMultipleTransactions(connection, txs, confirmationParams, _a) {
250
- var _b = _a.sendRate, sendRate = _b === void 0 ? 1 : _b, sendThrottler = _a.sendThrottler;
251
- return __awaiter(this, void 0, void 0, function () {
252
- return __generator(this, function (_c) {
253
- if (!sendThrottler) {
254
- sendThrottler = (0, exports.buildSendThrottler)(sendRate);
255
- }
256
- return [2 /*return*/, Promise.allSettled(txs.map(function (tx) {
257
- return executeTransaction(connection, tx, confirmationParams, { sendRate: sendRate, sendThrottler: sendThrottler });
258
- }))];
259
- });
260
- });
157
+ async function executeMultipleTransactions(connection, txs, confirmationParams, { sendRate = 1, sendThrottler }) {
158
+ if (!sendThrottler) {
159
+ sendThrottler = (0, exports.buildSendThrottler)(sendRate);
160
+ }
161
+ return Promise.allSettled(txs.map((tx) => executeTransaction(connection, tx, confirmationParams, { sendRate: sendRate, sendThrottler: sendThrottler })));
261
162
  }
262
163
  exports.executeMultipleTransactions = executeMultipleTransactions;
263
164
  /**
@@ -273,137 +174,83 @@ exports.executeMultipleTransactions = executeMultipleTransactions;
273
174
  * @param throttleParams.sendRate - rate
274
175
  * @param throttleParams.sendThrottler - throttler instance
275
176
  */
276
- function sendAndConfirmTransaction(connection, tx, _a, _b) {
277
- var hash = _a.hash, context = _a.context, commitment = _a.commitment;
278
- var _c = _b.sendRate, sendRate = _c === void 0 ? 1 : _c, sendThrottler = _b.sendThrottler;
279
- return __awaiter(this, void 0, void 0, function () {
280
- var isVersioned, signature, blockheight, transactionSent, rawTransaction, e_1, value, e_2, _e_1;
281
- var _this = this;
282
- return __generator(this, function (_d) {
283
- switch (_d.label) {
284
- case 0:
285
- isVersioned = isTransactionVersioned(tx);
286
- if (isVersioned) {
287
- signature = bs58_1.default.encode(tx.signatures[0]);
288
- }
289
- else {
290
- signature = bs58_1.default.encode(tx.signature);
291
- }
292
- if (!sendThrottler) {
293
- sendThrottler = (0, exports.buildSendThrottler)(sendRate);
294
- }
295
- return [4 /*yield*/, connection.getBlockHeight(commitment)];
296
- case 1:
297
- blockheight = _d.sent();
298
- transactionSent = false;
299
- rawTransaction = tx.serialize();
300
- _d.label = 2;
301
- case 2:
302
- if (!(blockheight < hash.lastValidBlockHeight + 15)) return [3 /*break*/, 20];
303
- _d.label = 3;
304
- case 3:
305
- _d.trys.push([3, 6, , 9]);
306
- if (!(blockheight < hash.lastValidBlockHeight || !transactionSent)) return [3 /*break*/, 5];
307
- return [4 /*yield*/, sendThrottler.add(function () { return __awaiter(_this, void 0, void 0, function () {
308
- return __generator(this, function (_a) {
309
- return [2 /*return*/, connection.sendRawTransaction(rawTransaction, {
310
- maxRetries: 0,
311
- minContextSlot: context.slot,
312
- preflightCommitment: commitment,
313
- skipPreflight: true,
314
- })];
315
- });
316
- }); })];
317
- case 4:
318
- _d.sent();
319
- transactionSent = true;
320
- _d.label = 5;
321
- case 5: return [3 /*break*/, 9];
322
- case 6:
323
- e_1 = _d.sent();
324
- if (!(transactionSent ||
325
- (e_1 instanceof web3_js_1.SendTransactionError && e_1.message.includes("Minimum context slot has not been reached")))) return [3 /*break*/, 8];
326
- return [4 /*yield*/, (0, utils_js_1.sleep)(500)];
327
- case 7:
328
- _d.sent();
329
- return [3 /*break*/, 2];
330
- case 8: throw e_1;
331
- case 9: return [4 /*yield*/, (0, utils_js_1.sleep)(500)];
332
- case 10:
333
- _d.sent();
334
- _d.label = 11;
335
- case 11:
336
- _d.trys.push([11, 13, , 15]);
337
- return [4 /*yield*/, confirmAndEnsureTransaction(connection, signature)];
338
- case 12:
339
- value = _d.sent();
340
- if (value) {
341
- return [2 /*return*/, signature];
342
- }
343
- return [3 /*break*/, 15];
344
- case 13:
345
- e_2 = _d.sent();
346
- if (e_2 instanceof types_js_1.TransactionFailedError) {
347
- throw e_2;
348
- }
349
- return [4 /*yield*/, (0, utils_js_1.sleep)(500)];
350
- case 14:
351
- _d.sent();
352
- return [3 /*break*/, 15];
353
- case 15:
354
- _d.trys.push([15, 17, , 19]);
355
- return [4 /*yield*/, connection.getBlockHeight(commitment)];
356
- case 16:
357
- blockheight = _d.sent();
358
- return [3 /*break*/, 19];
359
- case 17:
360
- _e_1 = _d.sent();
361
- return [4 /*yield*/, (0, utils_js_1.sleep)(500)];
362
- case 18:
363
- _d.sent();
364
- return [3 /*break*/, 19];
365
- case 19: return [3 /*break*/, 2];
366
- case 20: throw new Error("Transaction ".concat(signature, " expired."));
177
+ async function sendAndConfirmTransaction(connection, tx, { hash, context, commitment }, { sendRate = 1, sendThrottler }) {
178
+ const isVersioned = isTransactionVersioned(tx);
179
+ let signature;
180
+ if (isVersioned) {
181
+ signature = bs58_1.default.encode(tx.signatures[0]);
182
+ }
183
+ else {
184
+ signature = bs58_1.default.encode(tx.signature);
185
+ }
186
+ if (!sendThrottler) {
187
+ sendThrottler = (0, exports.buildSendThrottler)(sendRate);
188
+ }
189
+ let blockheight = await connection.getBlockHeight(commitment);
190
+ let transactionSent = false;
191
+ const rawTransaction = tx.serialize();
192
+ while (blockheight < hash.lastValidBlockHeight + 15) {
193
+ try {
194
+ if (blockheight < hash.lastValidBlockHeight || !transactionSent) {
195
+ await sendThrottler.add(async () => connection.sendRawTransaction(rawTransaction, {
196
+ maxRetries: 0,
197
+ minContextSlot: context.slot,
198
+ preflightCommitment: commitment,
199
+ skipPreflight: true,
200
+ }));
201
+ transactionSent = true;
367
202
  }
368
- });
369
- });
203
+ }
204
+ catch (e) {
205
+ if (transactionSent ||
206
+ (e instanceof web3_js_1.SendTransactionError && e.message.includes("Minimum context slot has not been reached"))) {
207
+ await (0, utils_js_1.sleep)(500);
208
+ continue;
209
+ }
210
+ throw e;
211
+ }
212
+ await (0, utils_js_1.sleep)(500);
213
+ try {
214
+ const value = await confirmAndEnsureTransaction(connection, signature);
215
+ if (value) {
216
+ return signature;
217
+ }
218
+ }
219
+ catch (e) {
220
+ if (e instanceof types_js_1.TransactionFailedError) {
221
+ throw e;
222
+ }
223
+ await (0, utils_js_1.sleep)(500);
224
+ }
225
+ try {
226
+ blockheight = await connection.getBlockHeight(commitment);
227
+ }
228
+ catch (_e) {
229
+ await (0, utils_js_1.sleep)(500);
230
+ }
231
+ }
232
+ throw new Error(`Transaction ${signature} expired.`);
370
233
  }
371
234
  exports.sendAndConfirmTransaction = sendAndConfirmTransaction;
372
- function simulateTransaction(connection, tx) {
373
- return __awaiter(this, void 0, void 0, function () {
374
- var res, i, errMessage;
375
- return __generator(this, function (_a) {
376
- switch (_a.label) {
377
- case 0:
378
- i = 0;
379
- _a.label = 1;
380
- case 1:
381
- if (!(i < SIMULATE_TRIES)) return [3 /*break*/, 7];
382
- if (!isTransactionVersioned(tx)) return [3 /*break*/, 3];
383
- return [4 /*yield*/, connection.simulateTransaction(tx)];
384
- case 2:
385
- res = _a.sent();
386
- return [3 /*break*/, 5];
387
- case 3: return [4 /*yield*/, connection.simulateTransaction(tx)];
388
- case 4:
389
- res = _a.sent();
390
- _a.label = 5;
391
- case 5:
392
- if (res.value.err) {
393
- errMessage = JSON.stringify(res.value.err);
394
- if (!errMessage.includes("BlockhashNotFound") || i === SIMULATE_TRIES - 1) {
395
- throw new web3_js_1.SendTransactionError("failed to simulate transaction: " + errMessage, res.value.logs || undefined);
396
- }
397
- return [3 /*break*/, 6];
398
- }
399
- return [2 /*return*/, res];
400
- case 6:
401
- i++;
402
- return [3 /*break*/, 1];
403
- case 7: throw new web3_js_1.SendTransactionError("failed to simulate transaction");
235
+ async function simulateTransaction(connection, tx) {
236
+ let res;
237
+ for (let i = 0; i < SIMULATE_TRIES; i++) {
238
+ if (isTransactionVersioned(tx)) {
239
+ res = await connection.simulateTransaction(tx);
240
+ }
241
+ else {
242
+ res = await connection.simulateTransaction(tx);
243
+ }
244
+ if (res.value.err) {
245
+ const errMessage = JSON.stringify(res.value.err);
246
+ if (!errMessage.includes("BlockhashNotFound") || i === SIMULATE_TRIES - 1) {
247
+ throw new web3_js_1.SendTransactionError("failed to simulate transaction: " + errMessage, res.value.logs || undefined);
404
248
  }
405
- });
406
- });
249
+ continue;
250
+ }
251
+ return res;
252
+ }
253
+ throw new web3_js_1.SendTransactionError("failed to simulate transaction");
407
254
  }
408
255
  exports.simulateTransaction = simulateTransaction;
409
256
  /**
@@ -413,50 +260,41 @@ exports.simulateTransaction = simulateTransaction;
413
260
  * @param ignoreError - return status even if tx failed
414
261
  * @returns Transaction Status
415
262
  */
416
- function confirmAndEnsureTransaction(connection, signature, ignoreError) {
417
- return __awaiter(this, void 0, void 0, function () {
418
- var response, value;
419
- return __generator(this, function (_a) {
420
- switch (_a.label) {
421
- case 0: return [4 /*yield*/, connection.getSignatureStatus(signature)];
422
- case 1:
423
- response = _a.sent();
424
- if (!response) {
425
- return [2 /*return*/, null];
426
- }
427
- value = response.value;
428
- if (!value) {
429
- return [2 /*return*/, null];
430
- }
431
- if (!ignoreError && value.err) {
432
- // That's how solana-web3js does it, `err` here is an object that won't really be handled
433
- throw new types_js_1.TransactionFailedError("Raw transaction ".concat(signature, " failed (").concat(JSON.stringify({ err: value.err }), ")"));
434
- }
435
- switch (connection.commitment) {
436
- case "confirmed":
437
- case "single":
438
- case "singleGossip": {
439
- if (value.confirmationStatus === "processed") {
440
- return [2 /*return*/, null];
441
- }
442
- break;
443
- }
444
- case "finalized":
445
- case "max":
446
- case "root": {
447
- if (value.confirmationStatus === "processed" || value.confirmationStatus === "confirmed") {
448
- return [2 /*return*/, null];
449
- }
450
- break;
451
- }
452
- // exhaust enums to ensure full coverage
453
- case "processed":
454
- case "recent":
455
- }
456
- return [2 /*return*/, value];
263
+ async function confirmAndEnsureTransaction(connection, signature, ignoreError) {
264
+ const response = await connection.getSignatureStatus(signature);
265
+ if (!response) {
266
+ return null;
267
+ }
268
+ const { value } = response;
269
+ if (!value) {
270
+ return null;
271
+ }
272
+ if (!ignoreError && value.err) {
273
+ // That's how solana-web3js does it, `err` here is an object that won't really be handled
274
+ throw new types_js_1.TransactionFailedError(`Raw transaction ${signature} failed (${JSON.stringify({ err: value.err })})`);
275
+ }
276
+ switch (connection.commitment) {
277
+ case "confirmed":
278
+ case "single":
279
+ case "singleGossip": {
280
+ if (value.confirmationStatus === "processed") {
281
+ return null;
457
282
  }
458
- });
459
- });
283
+ break;
284
+ }
285
+ case "finalized":
286
+ case "max":
287
+ case "root": {
288
+ if (value.confirmationStatus === "processed" || value.confirmationStatus === "confirmed") {
289
+ return null;
290
+ }
291
+ break;
292
+ }
293
+ // exhaust enums to ensure full coverage
294
+ case "processed":
295
+ case "recent":
296
+ }
297
+ return value;
460
298
  }
461
299
  exports.confirmAndEnsureTransaction = confirmAndEnsureTransaction;
462
300
  /**
@@ -476,60 +314,28 @@ exports.ata = ata;
476
314
  * @param paramsBatch - Array of Params for each ATA account: {mint, owner}
477
315
  * @returns Array of boolean where each member corresponds to an owner
478
316
  */
479
- function ataBatchExist(connection, paramsBatch) {
480
- return __awaiter(this, void 0, void 0, function () {
481
- var tokenAccounts, response;
482
- var _this = this;
483
- return __generator(this, function (_a) {
484
- switch (_a.label) {
485
- case 0: return [4 /*yield*/, Promise.all(paramsBatch.map(function (_a) {
486
- var mint = _a.mint, owner = _a.owner, programId = _a.programId;
487
- return __awaiter(_this, void 0, void 0, function () {
488
- return __generator(this, function (_b) {
489
- return [2 /*return*/, ata(mint, owner, programId)];
490
- });
491
- });
492
- }))];
493
- case 1:
494
- tokenAccounts = _a.sent();
495
- return [4 /*yield*/, connection.getMultipleAccountsInfo(tokenAccounts)];
496
- case 2:
497
- response = _a.sent();
498
- return [2 /*return*/, response.map(function (accInfo) { return !!accInfo; })];
499
- }
500
- });
501
- });
317
+ async function ataBatchExist(connection, paramsBatch) {
318
+ const tokenAccounts = await Promise.all(paramsBatch.map(async ({ mint, owner, programId }) => {
319
+ return ata(mint, owner, programId);
320
+ }));
321
+ const response = await connection.getMultipleAccountsInfo(tokenAccounts);
322
+ return response.map((accInfo) => !!accInfo);
502
323
  }
503
324
  exports.ataBatchExist = ataBatchExist;
504
- function enrichAtaParams(connection, paramsBatch) {
505
- return __awaiter(this, void 0, void 0, function () {
506
- var programIdByMint;
507
- var _this = this;
508
- return __generator(this, function (_a) {
509
- programIdByMint = {};
510
- return [2 /*return*/, Promise.all(paramsBatch.map(function (params) { return __awaiter(_this, void 0, void 0, function () {
511
- var mintStr, tokenProgramId;
512
- return __generator(this, function (_a) {
513
- switch (_a.label) {
514
- case 0:
515
- if (params.programId) {
516
- return [2 /*return*/, params];
517
- }
518
- mintStr = params.mint.toString();
519
- if (!!(mintStr in programIdByMint)) return [3 /*break*/, 2];
520
- return [4 /*yield*/, getMintAndProgram(connection, params.mint)];
521
- case 1:
522
- tokenProgramId = (_a.sent()).tokenProgramId;
523
- programIdByMint[mintStr] = tokenProgramId;
524
- _a.label = 2;
525
- case 2:
526
- params.programId = programIdByMint[mintStr];
527
- return [2 /*return*/, params];
528
- }
529
- });
530
- }); }))];
531
- });
532
- });
325
+ async function enrichAtaParams(connection, paramsBatch) {
326
+ const programIdByMint = {};
327
+ return Promise.all(paramsBatch.map(async (params) => {
328
+ if (params.programId) {
329
+ return params;
330
+ }
331
+ const mintStr = params.mint.toString();
332
+ if (!(mintStr in programIdByMint)) {
333
+ const { tokenProgramId } = await getMintAndProgram(connection, params.mint);
334
+ programIdByMint[mintStr] = tokenProgramId;
335
+ }
336
+ params.programId = programIdByMint[mintStr];
337
+ return params;
338
+ }));
533
339
  }
534
340
  exports.enrichAtaParams = enrichAtaParams;
535
341
  /**
@@ -540,45 +346,19 @@ exports.enrichAtaParams = enrichAtaParams;
540
346
  * @param commitment - optional commitment that will be used to fetch Blockhash
541
347
  * @returns Unsigned Transaction with create ATA instructions
542
348
  */
543
- function generateCreateAtaBatchTx(connection, payer, paramsBatch, commitment) {
544
- return __awaiter(this, void 0, void 0, function () {
545
- var ixs, _a, hash, context, messageV0, tx;
546
- var _this = this;
547
- return __generator(this, function (_b) {
548
- switch (_b.label) {
549
- case 0: return [4 /*yield*/, enrichAtaParams(connection, paramsBatch)];
550
- case 1:
551
- paramsBatch = _b.sent();
552
- return [4 /*yield*/, Promise.all(paramsBatch.map(function (_a) {
553
- var mint = _a.mint, owner = _a.owner, programId = _a.programId;
554
- return __awaiter(_this, void 0, void 0, function () {
555
- var _b, _c;
556
- return __generator(this, function (_d) {
557
- switch (_d.label) {
558
- case 0:
559
- _b = spl_token_1.createAssociatedTokenAccountInstruction;
560
- _c = [payer];
561
- return [4 /*yield*/, ata(mint, owner)];
562
- case 1: return [2 /*return*/, _b.apply(void 0, _c.concat([_d.sent(), owner, mint, programId]))];
563
- }
564
- });
565
- });
566
- }))];
567
- case 2:
568
- ixs = _b.sent();
569
- return [4 /*yield*/, connection.getLatestBlockhashAndContext({ commitment: commitment })];
570
- case 3:
571
- _a = _b.sent(), hash = _a.value, context = _a.context;
572
- messageV0 = new web3_js_1.TransactionMessage({
573
- payerKey: payer,
574
- recentBlockhash: hash.blockhash,
575
- instructions: ixs,
576
- }).compileToV0Message();
577
- tx = new web3_js_1.VersionedTransaction(messageV0);
578
- return [2 /*return*/, { tx: tx, hash: hash, context: context }];
579
- }
580
- });
581
- });
349
+ async function generateCreateAtaBatchTx(connection, payer, paramsBatch, commitment) {
350
+ paramsBatch = await enrichAtaParams(connection, paramsBatch);
351
+ const ixs = await Promise.all(paramsBatch.map(async ({ mint, owner, programId }) => {
352
+ return (0, spl_token_1.createAssociatedTokenAccountInstruction)(payer, await ata(mint, owner), owner, mint, programId);
353
+ }));
354
+ const { value: hash, context } = await connection.getLatestBlockhashAndContext({ commitment });
355
+ const messageV0 = new web3_js_1.TransactionMessage({
356
+ payerKey: payer,
357
+ recentBlockhash: hash.blockhash,
358
+ instructions: ixs,
359
+ }).compileToV0Message();
360
+ const tx = new web3_js_1.VersionedTransaction(messageV0);
361
+ return { tx, hash, context };
582
362
  }
583
363
  exports.generateCreateAtaBatchTx = generateCreateAtaBatchTx;
584
364
  /**
@@ -590,23 +370,9 @@ exports.generateCreateAtaBatchTx = generateCreateAtaBatchTx;
590
370
  * @param rate - throttle rate for tx sending
591
371
  * @returns Transaction signature
592
372
  */
593
- function createAtaBatch(connection, invoker, paramsBatch, commitment, rate) {
594
- return __awaiter(this, void 0, void 0, function () {
595
- var _a, tx, hash, context, _b, _c;
596
- return __generator(this, function (_d) {
597
- switch (_d.label) {
598
- case 0:
599
- _b = generateCreateAtaBatchTx;
600
- _c = [connection,
601
- invoker.publicKey];
602
- return [4 /*yield*/, enrichAtaParams(connection, paramsBatch)];
603
- case 1: return [4 /*yield*/, _b.apply(void 0, _c.concat([_d.sent(), commitment]))];
604
- case 2:
605
- _a = _d.sent(), tx = _a.tx, hash = _a.hash, context = _a.context;
606
- return [2 /*return*/, signAndExecuteTransaction(connection, invoker, tx, { hash: hash, context: context, commitment: commitment }, { sendRate: rate })];
607
- }
608
- });
609
- });
373
+ async function createAtaBatch(connection, invoker, paramsBatch, commitment, rate) {
374
+ const { tx, hash, context } = await generateCreateAtaBatchTx(connection, invoker.publicKey, await enrichAtaParams(connection, paramsBatch), commitment);
375
+ return signAndExecuteTransaction(connection, invoker, tx, { hash, context, commitment }, { sendRate: rate });
610
376
  }
611
377
  exports.createAtaBatch = createAtaBatch;
612
378
  /**
@@ -618,60 +384,23 @@ exports.createAtaBatch = createAtaBatch;
618
384
  * @param programId - Program ID of the Mint
619
385
  * @returns Array of Transaction Instructions that should be added to a transaction
620
386
  */
621
- function checkOrCreateAtaBatch(connection, owners, mint, invoker, programId) {
622
- return __awaiter(this, void 0, void 0, function () {
623
- var ixs, atas, owners_1, owners_1_1, owner, _a, _b, e_3_1, response, i;
624
- var e_3, _c;
625
- return __generator(this, function (_d) {
626
- switch (_d.label) {
627
- case 0:
628
- ixs = [];
629
- if (!!programId) return [3 /*break*/, 2];
630
- return [4 /*yield*/, getMintAndProgram(connection, mint)];
631
- case 1:
632
- programId = (_d.sent()).tokenProgramId;
633
- _d.label = 2;
634
- case 2:
635
- atas = [];
636
- _d.label = 3;
637
- case 3:
638
- _d.trys.push([3, 8, 9, 10]);
639
- owners_1 = __values(owners), owners_1_1 = owners_1.next();
640
- _d.label = 4;
641
- case 4:
642
- if (!!owners_1_1.done) return [3 /*break*/, 7];
643
- owner = owners_1_1.value;
644
- _b = (_a = atas).push;
645
- return [4 /*yield*/, ata(mint, owner, programId)];
646
- case 5:
647
- _b.apply(_a, [_d.sent()]);
648
- _d.label = 6;
649
- case 6:
650
- owners_1_1 = owners_1.next();
651
- return [3 /*break*/, 4];
652
- case 7: return [3 /*break*/, 10];
653
- case 8:
654
- e_3_1 = _d.sent();
655
- e_3 = { error: e_3_1 };
656
- return [3 /*break*/, 10];
657
- case 9:
658
- try {
659
- if (owners_1_1 && !owners_1_1.done && (_c = owners_1.return)) _c.call(owners_1);
660
- }
661
- finally { if (e_3) throw e_3.error; }
662
- return [7 /*endfinally*/];
663
- case 10: return [4 /*yield*/, connection.getMultipleAccountsInfo(atas)];
664
- case 11:
665
- response = _d.sent();
666
- for (i = 0; i < response.length; i++) {
667
- if (!response[i]) {
668
- ixs.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(invoker.publicKey, atas[i], owners[i], mint, programId));
669
- }
670
- }
671
- return [2 /*return*/, ixs];
672
- }
673
- });
674
- });
387
+ async function checkOrCreateAtaBatch(connection, owners, mint, invoker, programId) {
388
+ const ixs = [];
389
+ if (!programId) {
390
+ programId = (await getMintAndProgram(connection, mint)).tokenProgramId;
391
+ }
392
+ // TODO: optimize fetching and maps/arrays
393
+ const atas = [];
394
+ for (const owner of owners) {
395
+ atas.push(await ata(mint, owner, programId));
396
+ }
397
+ const response = await connection.getMultipleAccountsInfo(atas);
398
+ for (let i = 0; i < response.length; i++) {
399
+ if (!response[i]) {
400
+ ixs.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(invoker.publicKey, atas[i], owners[i], mint, programId));
401
+ }
402
+ }
403
+ return ixs;
675
404
  }
676
405
  exports.checkOrCreateAtaBatch = checkOrCreateAtaBatch;
677
406
  /**
@@ -679,9 +408,8 @@ exports.checkOrCreateAtaBatch = checkOrCreateAtaBatch;
679
408
  * - sets compute price if `computePrice` is provided
680
409
  * - sets compute limit if `computeLimit` is provided
681
410
  */
682
- function prepareBaseInstructions(connection, _a) {
683
- var computePrice = _a.computePrice, computeLimit = _a.computeLimit;
684
- var ixs = [];
411
+ function prepareBaseInstructions(connection, { computePrice, computeLimit }) {
412
+ const ixs = [];
685
413
  if (computePrice) {
686
414
  ixs.push(web3_js_1.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: computePrice }));
687
415
  }
@@ -700,24 +428,15 @@ exports.prepareBaseInstructions = prepareBaseInstructions;
700
428
  *
701
429
  * @return Mint information
702
430
  */
703
- function getMintAndProgram(connection, address, commitment) {
704
- return __awaiter(this, void 0, void 0, function () {
705
- var accountInfo, programId;
706
- return __generator(this, function (_a) {
707
- switch (_a.label) {
708
- case 0: return [4 /*yield*/, connection.getAccountInfo(address, commitment)];
709
- case 1:
710
- accountInfo = _a.sent();
711
- programId = accountInfo === null || accountInfo === void 0 ? void 0 : accountInfo.owner;
712
- 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))) {
713
- programId = spl_token_1.TOKEN_PROGRAM_ID;
714
- }
715
- return [2 /*return*/, {
716
- mint: (0, spl_token_1.unpackMint)(address, accountInfo, programId),
717
- tokenProgramId: programId,
718
- }];
719
- }
720
- });
721
- });
431
+ async function getMintAndProgram(connection, address, commitment) {
432
+ const accountInfo = await connection.getAccountInfo(address, commitment);
433
+ let programId = accountInfo?.owner;
434
+ if (!programId?.equals(spl_token_1.TOKEN_PROGRAM_ID) && !programId?.equals(spl_token_1.TOKEN_2022_PROGRAM_ID)) {
435
+ programId = spl_token_1.TOKEN_PROGRAM_ID;
436
+ }
437
+ return {
438
+ mint: (0, spl_token_1.unpackMint)(address, accountInfo, programId),
439
+ tokenProgramId: programId,
440
+ };
722
441
  }
723
442
  exports.getMintAndProgram = getMintAndProgram;
package/dist/cjs/types.js CHANGED
@@ -1,19 +1,4 @@
1
1
  "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
2
  Object.defineProperty(exports, "__esModule", { value: true });
18
3
  exports.ContractError = exports.IChain = exports.ICluster = void 0;
19
4
  // Utility types
@@ -36,23 +21,20 @@ var IChain;
36
21
  /**
37
22
  * Error wrapper for calls made to the contract on chain
38
23
  */
39
- var ContractError = /** @class */ (function (_super) {
40
- __extends(ContractError, _super);
24
+ class ContractError extends Error {
41
25
  /**
42
26
  * Constructs the Error Wrapper
43
27
  * @param error Original error raised probably by the chain SDK
44
28
  * @param code extracted code from the error if managed to parse it
45
29
  */
46
- function ContractError(error, code, description) {
47
- var _this = _super.call(this, error.message) || this;
48
- _this.contractErrorCode = code !== null && code !== void 0 ? code : null;
49
- _this.description = description !== null && description !== void 0 ? description : null;
30
+ constructor(error, code, description) {
31
+ super(error.message); // Call the base class constructor with the error message
32
+ this.contractErrorCode = code ?? null;
33
+ this.description = description ?? null;
50
34
  // Copy properties from the original error
51
- Object.setPrototypeOf(_this, ContractError.prototype);
52
- _this.name = "ContractError"; // Set the name property
53
- _this.stack = error.stack;
54
- return _this;
35
+ Object.setPrototypeOf(this, ContractError.prototype);
36
+ this.name = "ContractError"; // Set the name property
37
+ this.stack = error.stack;
55
38
  }
56
- return ContractError;
57
- }(Error));
39
+ }
58
40
  exports.ContractError = ContractError;
package/dist/cjs/utils.js CHANGED
@@ -1,54 +1,18 @@
1
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
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
39
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
40
4
  };
41
5
  Object.defineProperty(exports, "__esModule", { value: true });
42
6
  exports.sleep = exports.handleContractError = exports.getScaledBigNumber = exports.getNumberFromBigNumber = void 0;
43
- var bignumber_js_1 = __importDefault(require("bignumber.js"));
44
- var types_js_1 = require("./types.js");
7
+ const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
+ const types_js_1 = require("./types.js");
45
9
  /**
46
10
  * Used for token amounts conversion from their Big Number representation to number.
47
11
  * Get value in the highest units from BigNumber representation of the same value in the smallest units.
48
12
  * @param {BigNumber} value - Big Number representation of value in the smallest units.
49
13
  * @param {number} decimals - Number of decimals the token has.
50
14
  */
51
- var getNumberFromBigNumber = function (bigNum, decimals) {
15
+ const getNumberFromBigNumber = (bigNum, decimals) => {
52
16
  return bigNum.div((0, bignumber_js_1.default)(10).pow(decimals)).toNumber();
53
17
  };
54
18
  exports.getNumberFromBigNumber = getNumberFromBigNumber;
@@ -58,7 +22,7 @@ exports.getNumberFromBigNumber = getNumberFromBigNumber;
58
22
  * @param {number} value - Number of tokens you want to convert to its BigNumber representation.
59
23
  * @param {number} decimals - Number of decimals the token has.
60
24
  */
61
- var getScaledBigNumber = function (value, decimals) {
25
+ const getScaledBigNumber = (value, decimals) => {
62
26
  return new bignumber_js_1.default(value).times(new bignumber_js_1.default(10).pow(decimals));
63
27
  };
64
28
  exports.getScaledBigNumber = getScaledBigNumber;
@@ -68,28 +32,19 @@ exports.getScaledBigNumber = getScaledBigNumber;
68
32
  * @param callback callback that may be used to extract error code
69
33
  * @returns {T}
70
34
  */
71
- function handleContractError(func, callback) {
72
- return __awaiter(this, void 0, void 0, function () {
73
- var err_1;
74
- return __generator(this, function (_a) {
75
- switch (_a.label) {
76
- case 0:
77
- _a.trys.push([0, 2, , 3]);
78
- return [4 /*yield*/, func()];
79
- case 1: return [2 /*return*/, _a.sent()];
80
- case 2:
81
- err_1 = _a.sent();
82
- if (err_1 instanceof Error) {
83
- if (callback) {
84
- throw new types_js_1.ContractError(err_1, callback(err_1));
85
- }
86
- throw new types_js_1.ContractError(err_1);
87
- }
88
- throw err_1;
89
- case 3: return [2 /*return*/];
35
+ async function handleContractError(func, callback) {
36
+ try {
37
+ return await func();
38
+ }
39
+ catch (err) {
40
+ if (err instanceof Error) {
41
+ if (callback) {
42
+ throw new types_js_1.ContractError(err, callback(err));
90
43
  }
91
- });
92
- });
44
+ throw new types_js_1.ContractError(err);
45
+ }
46
+ throw err;
47
+ }
93
48
  }
94
49
  exports.handleContractError = handleContractError;
95
50
  /**
@@ -97,6 +52,6 @@ exports.handleContractError = handleContractError;
97
52
  * @param ms millisecond to sleep for
98
53
  */
99
54
  function sleep(ms) {
100
- return new Promise(function (resolve) { return setTimeout(resolve, ms); });
55
+ return new Promise((resolve) => setTimeout(resolve, ms));
101
56
  }
102
57
  exports.sleep = sleep;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@streamflow/common",
3
- "version": "7.0.0-alpha.3",
3
+ "version": "7.0.0-alpha.6",
4
4
  "description": "Common utilities and types used by streamflow packages.",
5
5
  "homepage": "https://github.com/streamflow-finance/js-sdk/",
6
6
  "main": "./dist/esm/index.js",
@@ -27,9 +27,9 @@
27
27
  "lint-config": "eslint --print-config",
28
28
  "prepublishOnly": "npm run lint && npm run build"
29
29
  },
30
- "gitHead": "1f0ce4ebcbbf9ac79f744a7ef232543b9e6d2a5b",
30
+ "gitHead": "f789b5ddcc3d6fb9b84beb0b16f63c6348bd37ab",
31
31
  "devDependencies": {
32
- "@streamflow/eslint-config": "7.0.0-alpha.3",
32
+ "@streamflow/eslint-config": "7.0.0-alpha.6",
33
33
  "date-fns": "2.28.0",
34
34
  "typescript": "^4.9.5"
35
35
  },