@streamflow/common 7.5.3 → 8.0.0-alpha.p284.726ba98

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/cjs/index.cjs +90 -0
  2. package/dist/cjs/index.cjs.map +1 -0
  3. package/dist/cjs/index.d.cts +66 -0
  4. package/dist/cjs/solana/index.cjs +1039 -0
  5. package/dist/cjs/solana/index.cjs.map +1 -0
  6. package/dist/{esm/solana/utils.d.ts → cjs/solana/index.d.cts} +79 -27
  7. package/dist/esm/index.d.ts +66 -3
  8. package/dist/esm/index.js +76 -3
  9. package/dist/esm/index.js.map +1 -0
  10. package/dist/esm/solana/index.d.ts +239 -5
  11. package/dist/esm/solana/index.js +1008 -5
  12. package/dist/esm/solana/index.js.map +1 -0
  13. package/package.json +25 -15
  14. package/dist/cjs/index.js +0 -19
  15. package/dist/cjs/lib/assertions.js +0 -13
  16. package/dist/cjs/lib/utils.js +0 -62
  17. package/dist/cjs/solana/account-filters.js +0 -19
  18. package/dist/cjs/solana/index.js +0 -21
  19. package/dist/cjs/solana/instructions.js +0 -22
  20. package/dist/cjs/solana/public-key.js +0 -13
  21. package/dist/cjs/solana/types.js +0 -11
  22. package/dist/cjs/solana/utils.js +0 -478
  23. package/dist/cjs/types.js +0 -40
  24. package/dist/esm/lib/assertions.d.ts +0 -1
  25. package/dist/esm/lib/assertions.js +0 -9
  26. package/dist/esm/lib/utils.d.ts +0 -28
  27. package/dist/esm/lib/utils.js +0 -51
  28. package/dist/esm/solana/account-filters.d.ts +0 -2
  29. package/dist/esm/solana/account-filters.js +0 -15
  30. package/dist/esm/solana/instructions.d.ts +0 -3
  31. package/dist/esm/solana/instructions.js +0 -18
  32. package/dist/esm/solana/public-key.d.ts +0 -7
  33. package/dist/esm/solana/public-key.js +0 -9
  34. package/dist/esm/solana/types.d.ts +0 -39
  35. package/dist/esm/solana/types.js +0 -7
  36. package/dist/esm/solana/utils.js +0 -450
  37. package/dist/esm/types.d.ts +0 -32
  38. package/dist/esm/types.js +0 -38
@@ -1,478 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.buildSendThrottler = void 0;
7
- exports.getProgramAccounts = getProgramAccounts;
8
- exports.isSignerWallet = isSignerWallet;
9
- exports.isSignerKeypair = isSignerKeypair;
10
- exports.isTransactionVersioned = isTransactionVersioned;
11
- exports.prepareTransaction = prepareTransaction;
12
- exports.signTransaction = signTransaction;
13
- exports.signAndExecuteTransaction = signAndExecuteTransaction;
14
- exports.executeTransaction = executeTransaction;
15
- exports.executeMultipleTransactions = executeMultipleTransactions;
16
- exports.sendAndConfirmTransaction = sendAndConfirmTransaction;
17
- exports.simulateTransaction = simulateTransaction;
18
- exports.confirmAndEnsureTransaction = confirmAndEnsureTransaction;
19
- exports.ata = ata;
20
- exports.ataBatchExist = ataBatchExist;
21
- exports.enrichAtaParams = enrichAtaParams;
22
- exports.generateCreateAtaBatchTx = generateCreateAtaBatchTx;
23
- exports.createAtaBatch = createAtaBatch;
24
- exports.checkOrCreateAtaBatch = checkOrCreateAtaBatch;
25
- exports.prepareBaseInstructions = prepareBaseInstructions;
26
- exports.getMintAndProgram = getMintAndProgram;
27
- exports.getMultipleAccountsInfoBatched = getMultipleAccountsInfoBatched;
28
- const spl_token_1 = require("@solana/spl-token");
29
- const web3_js_1 = require("@solana/web3.js");
30
- const bs58_1 = __importDefault(require("bs58"));
31
- const p_queue_1 = __importDefault(require("p-queue"));
32
- const types_js_1 = require("./types.js");
33
- const utils_js_1 = require("../lib/utils.js");
34
- const SIMULATE_TRIES = 3;
35
- const buildSendThrottler = (sendRate, sendInterval = 1000) => {
36
- return new p_queue_1.default({ concurrency: sendRate, intervalCap: 1, interval: sendInterval });
37
- };
38
- exports.buildSendThrottler = buildSendThrottler;
39
- /**
40
- * Wrapper function for Solana web3 getProgramAccounts with slightly better call interface
41
- * @param {Connection} connection - Solana web3 connection object.
42
- * @param {PublicKey} wallet - PublicKey to compare against.
43
- * @param {number} offset - Offset of bits of the PublicKey in the account binary.
44
- * @param {PublicKey} programId - Solana program ID.
45
- * @return {Promise<Account[]>} - Array of resulting accounts.
46
- */
47
- async function getProgramAccounts(connection, wallet, offset, programId) {
48
- const programAccounts = await connection?.getProgramAccounts(programId, {
49
- filters: [
50
- {
51
- memcmp: {
52
- offset,
53
- bytes: wallet.toBase58(),
54
- },
55
- },
56
- ],
57
- });
58
- return [...programAccounts];
59
- }
60
- /**
61
- * Utility function to check if the transaction initiator is a Wallet object
62
- * @param {Keypair | SignerWalletAdapter} walletOrKeypair - Wallet or Keypair in question
63
- * @return {boolean} - Returns true if parameter is a Wallet.
64
- */
65
- function isSignerWallet(walletOrKeypair) {
66
- return walletOrKeypair.signTransaction !== undefined;
67
- }
68
- /**
69
- * Utility function to check if the transaction initiator a Keypair object, tries to mitigate version mismatch issues
70
- * @param walletOrKeypair {Keypair | SignerWalletAdapter} walletOrKeypair - Wallet or Keypair in question
71
- * @returns {boolean} - Returns true if parameter is a Keypair.
72
- */
73
- function isSignerKeypair(walletOrKeypair) {
74
- return (walletOrKeypair instanceof web3_js_1.Keypair ||
75
- walletOrKeypair.constructor === web3_js_1.Keypair ||
76
- walletOrKeypair.constructor.name === web3_js_1.Keypair.prototype.constructor.name);
77
- }
78
- /**
79
- * Utility function to check whether given transaction is Versioned
80
- * @param tx {Transaction | VersionedTransaction} - Transaction to check
81
- * @returns {boolean} - Returns true if transaction is Versioned.
82
- */
83
- function isTransactionVersioned(tx) {
84
- return "message" in tx;
85
- }
86
- /**
87
- * Creates a Transaction with given instructions and optionally signs it.
88
- * @param connection - Solana client connection
89
- * @param ixs - Instructions to add to the Transaction
90
- * @param payer - PublicKey of payer
91
- * @param commitment - optional Commitment that will be used to fetch latest blockhash
92
- * @param partialSigners - optional signers that will be used to partially sign a Transaction
93
- * @returns Transaction and Blockhash
94
- */
95
- async function prepareTransaction(connection, ixs, payer, commitment, ...partialSigners) {
96
- if (!payer) {
97
- throw new Error("Payer public key is not provided!");
98
- }
99
- const { value: hash, context } = await connection.getLatestBlockhashAndContext(commitment);
100
- const messageV0 = new web3_js_1.TransactionMessage({
101
- payerKey: payer,
102
- recentBlockhash: hash.blockhash,
103
- instructions: ixs,
104
- }).compileToV0Message();
105
- const tx = new web3_js_1.VersionedTransaction(messageV0);
106
- const signers = partialSigners.filter((item) => !!item);
107
- tx.sign(signers);
108
- return { tx, context, hash };
109
- }
110
- async function signTransaction(invoker, tx) {
111
- let signedTx;
112
- if (isSignerWallet(invoker)) {
113
- signedTx = await invoker.signTransaction(tx);
114
- }
115
- else {
116
- if (isTransactionVersioned(tx)) {
117
- tx.sign([invoker]);
118
- }
119
- else {
120
- tx.partialSign(invoker);
121
- }
122
- signedTx = tx;
123
- }
124
- return signedTx;
125
- }
126
- /**
127
- * Signs, sends and confirms Transaction
128
- * @param connection - Solana client connection
129
- * @param invoker - Keypair used as signer
130
- * @param tx - Transaction instance
131
- * @param confirmationParams - Confirmation Params that will be used for execution
132
- * @param throttleParams - rate or throttler instance to throttle TX sending - to not spam the blockchain too much
133
- * @returns Transaction signature
134
- */
135
- async function signAndExecuteTransaction(connection, invoker, tx, confirmationParams, throttleParams) {
136
- const signedTx = await signTransaction(invoker, tx);
137
- return executeTransaction(connection, signedTx, confirmationParams, throttleParams);
138
- }
139
- /**
140
- * Sends and confirms Transaction
141
- * Uses custom confirmation logic that:
142
- * - simulates tx before sending separately
143
- * - sends transaction without preFlight checks but with some valuable flags https://twitter.com/jordaaash/status/1774892862049800524?s=46&t=bhZ10V0r7IX5Lk5kKzxfGw
144
- * - rebroadcasts a tx every 500 ms
145
- * - after broadcasting check whether tx has executed once
146
- * - catch errors for every actionable item, throw only the ones that signal that tx has failed
147
- * - otherwise there is a chance of marking a landed tx as failed if it was broadcasted at least once
148
- * @param connection - Solana client connection
149
- * @param tx - Transaction instance
150
- * @param confirmationParams - Confirmation Params that will be used for execution
151
- * @param throttleParams - rate or throttler instance to throttle TX sending - to not spam the blockchain too much
152
- * @returns Transaction signature
153
- */
154
- async function executeTransaction(connection, tx, confirmationParams, throttleParams) {
155
- if (tx.signatures.length === 0) {
156
- throw Error("Error with transaction parameters.");
157
- }
158
- await simulateTransaction(connection, tx);
159
- return sendAndConfirmTransaction(connection, tx, confirmationParams, throttleParams);
160
- }
161
- /**
162
- * Launches a PromisePool with all transaction being executed at the same time, allows to throttle all TXs through one Queue
163
- * @param connection - Solana client connection
164
- * @param txs - Transactions
165
- * @param confirmationParams - Confirmation Params that will be used for execution
166
- * @param throttleParams - rate or throttler instance to throttle TX sending - to not spam the blockchain too much
167
- * @param throttleParams.sendRate - rate
168
- * @param throttleParams.sendThrottler - throttler instance
169
- * @returns Raw Promise Results - should be handled by the consumer and unwrapped accordingly
170
- */
171
- async function executeMultipleTransactions(connection, txs, confirmationParams, { sendRate = 1, sendThrottler, ...throttlingParams }) {
172
- if (!sendThrottler) {
173
- sendThrottler = (0, exports.buildSendThrottler)(sendRate);
174
- }
175
- return Promise.allSettled(txs.map((tx) => executeTransaction(connection, tx, confirmationParams, {
176
- ...throttlingParams,
177
- sendRate: sendRate,
178
- sendThrottler: sendThrottler,
179
- })));
180
- }
181
- /**
182
- * Sends and confirm transaction in a loop, constantly re-broadcsting the tx until Blockheight expires.
183
- * - we add additional 30 bocks to account for validators in an PRC pool divergence
184
- * @param connection - Solana client connection
185
- * @param tx - Transaction instance
186
- * @param confirmationParams - Confirmation Params that will be used for execution
187
- * @param confirmationParams.hash - blockhash information, the same hash should be used in the Transaction
188
- * @param confirmationParams.context - context at which blockhash has been retrieve
189
- * @param confirmationParams.commitment - optional commitment that will be used for simulation and confirmation
190
- * @param throttleParams - rate or throttler instance to throttle TX sending - to not spam the blockchain too much
191
- * @param throttleParams.sendRate - rate
192
- * @param throttleParams.sendThrottler - throttler instance
193
- */
194
- async function sendAndConfirmTransaction(connection, tx, { hash, context, commitment }, { sendRate = 1, sendThrottler, waitBeforeConfirming }) {
195
- const isVersioned = isTransactionVersioned(tx);
196
- let signature;
197
- if (isVersioned) {
198
- signature = bs58_1.default.encode(tx.signatures[0]);
199
- }
200
- else {
201
- signature = bs58_1.default.encode(tx.signature);
202
- }
203
- if (!sendThrottler) {
204
- sendThrottler = (0, exports.buildSendThrottler)(sendRate);
205
- }
206
- let blockheight = await connection.getBlockHeight(commitment);
207
- let transactionSent = false;
208
- const rawTransaction = tx.serialize();
209
- while (blockheight < hash.lastValidBlockHeight + 15) {
210
- try {
211
- if (blockheight < hash.lastValidBlockHeight || !transactionSent) {
212
- await sendThrottler.add(async () => connection.sendRawTransaction(rawTransaction, {
213
- maxRetries: 0,
214
- minContextSlot: context.slot,
215
- preflightCommitment: commitment,
216
- skipPreflight: true,
217
- }));
218
- transactionSent = true;
219
- }
220
- }
221
- catch (e) {
222
- if (transactionSent ||
223
- (e instanceof web3_js_1.SendTransactionError && e.message.includes("Minimum context slot has not been reached"))) {
224
- await (0, utils_js_1.sleep)(500);
225
- continue;
226
- }
227
- throw e;
228
- }
229
- // Wait at least 5 slots (~400ms before confirming)
230
- await (0, utils_js_1.sleep)(waitBeforeConfirming ?? 2000);
231
- try {
232
- const value = await confirmAndEnsureTransaction(connection, signature);
233
- if (value) {
234
- return signature;
235
- }
236
- }
237
- catch (e) {
238
- if (e instanceof types_js_1.TransactionFailedError) {
239
- throw e;
240
- }
241
- await (0, utils_js_1.sleep)(500);
242
- }
243
- try {
244
- blockheight = await connection.getBlockHeight(commitment);
245
- }
246
- catch (_e) {
247
- await (0, utils_js_1.sleep)(500);
248
- }
249
- }
250
- throw new Error(`Transaction ${signature} expired.`);
251
- }
252
- async function simulateTransaction(connection, tx) {
253
- let res;
254
- for (let i = 0; i < SIMULATE_TRIES; i++) {
255
- if (isTransactionVersioned(tx)) {
256
- res = await connection.simulateTransaction(tx);
257
- }
258
- else {
259
- res = await connection.simulateTransaction(tx);
260
- }
261
- if (res.value.err) {
262
- const errMessage = JSON.stringify(res.value.err);
263
- if (!errMessage.includes("BlockhashNotFound") || i === SIMULATE_TRIES - 1) {
264
- throw new web3_js_1.SendTransactionError({
265
- action: "simulate",
266
- signature: "",
267
- transactionMessage: `failed to simulate transaction: ${typeof res.value.err === "string" ? res.value.err : errMessage}`,
268
- logs: res.value.logs ?? undefined,
269
- });
270
- }
271
- continue;
272
- }
273
- return res;
274
- }
275
- throw new web3_js_1.SendTransactionError({
276
- action: "simulate",
277
- signature: "",
278
- transactionMessage: "failed to simulate transaction",
279
- });
280
- }
281
- /**
282
- * Confirms and validates transaction success once
283
- * @param connection - Solana client connection
284
- * @param signature - Transaction signature
285
- * @param ignoreError - return status even if tx failed
286
- * @returns Transaction Status
287
- */
288
- async function confirmAndEnsureTransaction(connection, signature, ignoreError) {
289
- const response = await connection.getSignatureStatuses([signature]);
290
- if (!response || response.value.length === 0 || response.value[0] === null) {
291
- return null;
292
- }
293
- const value = response.value[0];
294
- if (!value) {
295
- return null;
296
- }
297
- if (!ignoreError && value.err) {
298
- // That's how solana-web3js does it, `err` here is an object that won't really be handled
299
- throw new types_js_1.TransactionFailedError(`Raw transaction ${signature} failed (${JSON.stringify({ err: value.err })})`);
300
- }
301
- switch (connection.commitment) {
302
- case "confirmed":
303
- case "single":
304
- case "singleGossip": {
305
- if (value.confirmationStatus === "processed") {
306
- return null;
307
- }
308
- break;
309
- }
310
- case "finalized":
311
- case "max":
312
- case "root": {
313
- if (value.confirmationStatus === "processed" || value.confirmationStatus === "confirmed") {
314
- return null;
315
- }
316
- break;
317
- }
318
- // exhaust enums to ensure full coverage
319
- case "processed":
320
- case "recent":
321
- }
322
- return value;
323
- }
324
- /**
325
- * Shorthand call signature for getAssociatedTokenAddress, with allowance for address to be offCurve
326
- * @param {PublicKey} mint - SPL token Mint address.
327
- * @param {PublicKey} owner - Owner of the Associated Token Address
328
- * @param {PublicKey} programId - Program ID of the mint
329
- * @return {Promise<PublicKey>} - Associated Token Address
330
- */
331
- function ata(mint, owner, programId) {
332
- return (0, spl_token_1.getAssociatedTokenAddress)(mint, owner, true, programId);
333
- }
334
- /**
335
- * Function that checks whether ATA exists for each provided owner
336
- * @param connection - Solana client connection
337
- * @param paramsBatch - Array of Params for each ATA account: {mint, owner}
338
- * @returns Array of boolean where each member corresponds to an owner
339
- */
340
- async function ataBatchExist(connection, paramsBatch) {
341
- const tokenAccounts = await Promise.all(paramsBatch.map(async ({ mint, owner, programId }) => {
342
- return ata(mint, owner, programId);
343
- }));
344
- const response = await connection.getMultipleAccountsInfo(tokenAccounts);
345
- return response.map((accInfo) => !!accInfo);
346
- }
347
- async function enrichAtaParams(connection, paramsBatch) {
348
- const programIdByMint = {};
349
- return Promise.all(paramsBatch.map(async (params) => {
350
- if (params.programId) {
351
- return params;
352
- }
353
- const mintStr = params.mint.toString();
354
- if (!(mintStr in programIdByMint)) {
355
- const { tokenProgramId } = await getMintAndProgram(connection, params.mint);
356
- programIdByMint[mintStr] = tokenProgramId;
357
- }
358
- params.programId = programIdByMint[mintStr];
359
- return params;
360
- }));
361
- }
362
- /**
363
- * Generates a Transaction to create ATA for an array of owners
364
- * @param connection - Solana client connection
365
- * @param payer - Transaction invoker, should be a signer
366
- * @param paramsBatch - Array of Params for an each ATA account: {mint, owner}
367
- * @param commitment - optional commitment that will be used to fetch Blockhash
368
- * @returns Unsigned Transaction with create ATA instructions
369
- */
370
- async function generateCreateAtaBatchTx(connection, payer, paramsBatch, commitment) {
371
- paramsBatch = await enrichAtaParams(connection, paramsBatch);
372
- const ixs = await Promise.all(paramsBatch.map(async ({ mint, owner, programId }) => {
373
- return (0, spl_token_1.createAssociatedTokenAccountInstruction)(payer, await ata(mint, owner), owner, mint, programId);
374
- }));
375
- const { value: hash, context } = await connection.getLatestBlockhashAndContext({ commitment });
376
- const messageV0 = new web3_js_1.TransactionMessage({
377
- payerKey: payer,
378
- recentBlockhash: hash.blockhash,
379
- instructions: ixs,
380
- }).compileToV0Message();
381
- const tx = new web3_js_1.VersionedTransaction(messageV0);
382
- return { tx, hash, context };
383
- }
384
- /**
385
- * Creates ATA for an array of owners
386
- * @param connection - Solana client connection
387
- * @param invoker - Transaction invoker and payer
388
- * @param paramsBatch - Array of Params for an each ATA account: {mint, owner}
389
- * @param commitment - optional commitment that will be used to fetch Blockhash
390
- * @param rate - throttle rate for tx sending
391
- * @returns Transaction signature
392
- */
393
- async function createAtaBatch(connection, invoker, paramsBatch, commitment, rate) {
394
- const { tx, hash, context } = await generateCreateAtaBatchTx(connection, invoker.publicKey, await enrichAtaParams(connection, paramsBatch), commitment);
395
- return signAndExecuteTransaction(connection, invoker, tx, { hash, context, commitment }, { sendRate: rate });
396
- }
397
- /**
398
- * Utility function that checks whether associated token accounts exist and return instructions to populate them if not
399
- * @param connection - Solana client connection
400
- * @param owners - Array of ATA owners
401
- * @param mint - Mint for which ATA will be checked
402
- * @param invoker - Transaction invoker and payer
403
- * @param programId - Program ID of the Mint
404
- * @returns Array of Transaction Instructions that should be added to a transaction
405
- */
406
- async function checkOrCreateAtaBatch(connection, owners, mint, invoker, programId) {
407
- const ixs = [];
408
- if (!programId) {
409
- programId = (await getMintAndProgram(connection, mint)).tokenProgramId;
410
- }
411
- // TODO: optimize fetching and maps/arrays
412
- const atas = [];
413
- for (const owner of owners) {
414
- atas.push(await ata(mint, owner, programId));
415
- }
416
- const response = await connection.getMultipleAccountsInfo(atas);
417
- for (let i = 0; i < response.length; i++) {
418
- if (!response[i]) {
419
- ixs.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(invoker.publicKey, atas[i], owners[i], mint, programId));
420
- }
421
- }
422
- return ixs;
423
- }
424
- /**
425
- * Create Base instructions for Solana
426
- * - sets compute price if `computePrice` is provided
427
- * - sets compute limit if `computeLimit` is provided
428
- */
429
- function prepareBaseInstructions(connection, { computePrice, computeLimit }) {
430
- const ixs = [];
431
- if (computePrice) {
432
- ixs.push(web3_js_1.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: computePrice }));
433
- }
434
- if (computeLimit) {
435
- ixs.push(web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: computeLimit }));
436
- }
437
- return ixs;
438
- }
439
- /**
440
- * Retrieve information about a mint and its program ID, support all Token Programs.
441
- *
442
- * @param connection Connection to use
443
- * @param address Mint account
444
- * @param commitment Desired level of commitment for querying the state
445
- *
446
- * @return Mint information
447
- */
448
- async function getMintAndProgram(connection, address, commitment) {
449
- const accountInfo = await connection.getAccountInfo(address, commitment);
450
- let programId = accountInfo?.owner;
451
- if (!programId?.equals(spl_token_1.TOKEN_PROGRAM_ID) && !programId?.equals(spl_token_1.TOKEN_2022_PROGRAM_ID)) {
452
- programId = spl_token_1.TOKEN_PROGRAM_ID;
453
- }
454
- return {
455
- mint: (0, spl_token_1.unpackMint)(address, accountInfo, programId),
456
- tokenProgramId: programId,
457
- };
458
- }
459
- /**
460
- * Split fetching of Multiple Accounts Info into batches of 100
461
- * as the maximum number of accounts that can be fetched in a single call is 100
462
- *
463
- * @param connection Connection to use
464
- * @param pubKeys Array of public keys to fetch account info for
465
- * @param commitment Desired level of commitment for querying the state
466
- *
467
- * @return Array of AccountInfo objects
468
- */
469
- async function getMultipleAccountsInfoBatched(connection, pubKeys, commitment) {
470
- const batchSize = 99;
471
- const batches = [];
472
- for (let i = 0; i < pubKeys.length; i += batchSize) {
473
- const batch = pubKeys.slice(i, i + batchSize);
474
- batches.push(connection.getMultipleAccountsInfo(batch, commitment));
475
- }
476
- const results = await Promise.all(batches);
477
- return results.flat();
478
- }
package/dist/cjs/types.js DELETED
@@ -1,40 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ContractError = exports.IChain = exports.ICluster = void 0;
4
- // Utility types
5
- var ICluster;
6
- (function (ICluster) {
7
- ICluster["Mainnet"] = "mainnet";
8
- ICluster["Devnet"] = "devnet";
9
- ICluster["Testnet"] = "testnet";
10
- ICluster["Local"] = "local";
11
- })(ICluster || (exports.ICluster = ICluster = {}));
12
- var IChain;
13
- (function (IChain) {
14
- IChain["Solana"] = "Solana";
15
- IChain["Aptos"] = "Aptos";
16
- IChain["Ethereum"] = "Ethereum";
17
- IChain["BNB"] = "BNB";
18
- IChain["Polygon"] = "Polygon";
19
- IChain["Sui"] = "Sui";
20
- })(IChain || (exports.IChain = IChain = {}));
21
- /**
22
- * Error wrapper for calls made to the contract on chain
23
- */
24
- class ContractError extends Error {
25
- /**
26
- * Constructs the Error Wrapper
27
- * @param error Original error raised probably by the chain SDK
28
- * @param code extracted code from the error if managed to parse it
29
- */
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;
34
- // Copy properties from the original error
35
- Object.setPrototypeOf(this, ContractError.prototype);
36
- this.name = "ContractError"; // Set the name property
37
- this.stack = error.stack;
38
- }
39
- }
40
- exports.ContractError = ContractError;
@@ -1 +0,0 @@
1
- export declare const invariant: (condition: any, message?: string | (() => string)) => asserts condition;
@@ -1,9 +0,0 @@
1
- const prefix = "Assertion failed";
2
- export const invariant = (condition, message) => {
3
- if (condition) {
4
- return;
5
- }
6
- const provided = typeof message === "function" ? message() : message;
7
- const value = provided ? `${prefix}: ${provided}` : prefix;
8
- throw new Error(value);
9
- };
@@ -1,28 +0,0 @@
1
- import BN from "bn.js";
2
- /**
3
- * Used for conversion of token amounts to their Big Number representation.
4
- * Get Big Number representation in the smallest units from the same value in the highest units.
5
- * @param {number} value - Number of tokens you want to convert to its BN representation.
6
- * @param {number} decimals - Number of decimals the token has.
7
- */
8
- export declare const getBN: (value: number, decimals: number) => BN;
9
- /**
10
- * Used for token amounts conversion from their Big Number representation to number.
11
- * Get value in the highest units from BN representation of the same value in the smallest units.
12
- * @param {BN} value - Big Number representation of value in the smallest units.
13
- * @param {number} decimals - Number of decimals the token has.
14
- */
15
- export declare const getNumberFromBN: (value: BN, decimals: number) => number;
16
- /**
17
- * Used to make on chain calls to the contract and wrap raised errors if any
18
- * @param func function that interacts with the contract
19
- * @param callback callback that may be used to extract error code
20
- * @returns {T}
21
- */
22
- export declare function handleContractError<T>(func: () => Promise<T>, callback?: (err: Error) => string | null): Promise<T>;
23
- /**
24
- * Pause async function execution for given amount of milliseconds
25
- * @param ms millisecond to sleep for
26
- */
27
- export declare function sleep(ms: number): Promise<void>;
28
- export declare const divCeilN: (n: bigint, d: bigint) => bigint;
@@ -1,51 +0,0 @@
1
- import BN from "bn.js";
2
- import { ContractError } from "../types.js";
3
- /**
4
- * Used for conversion of token amounts to their Big Number representation.
5
- * Get Big Number representation in the smallest units from the same value in the highest units.
6
- * @param {number} value - Number of tokens you want to convert to its BN representation.
7
- * @param {number} decimals - Number of decimals the token has.
8
- */
9
- export const getBN = (value, decimals) => {
10
- const decimalPart = value - Math.trunc(value);
11
- const integerPart = new BN(Math.trunc(value));
12
- const decimalE = new BN(decimalPart * 1e9);
13
- const sum = integerPart.mul(new BN(1e9)).add(decimalE);
14
- const resultE = sum.mul(new BN(10).pow(new BN(decimals)));
15
- return resultE.div(new BN(1e9));
16
- };
17
- /**
18
- * Used for token amounts conversion from their Big Number representation to number.
19
- * Get value in the highest units from BN representation of the same value in the smallest units.
20
- * @param {BN} value - Big Number representation of value in the smallest units.
21
- * @param {number} decimals - Number of decimals the token has.
22
- */
23
- export const getNumberFromBN = (value, decimals) => value.gt(new BN(2 ** 53 - 1)) ? value.div(new BN(10 ** decimals)).toNumber() : value.toNumber() / 10 ** decimals;
24
- /**
25
- * Used to make on chain calls to the contract and wrap raised errors if any
26
- * @param func function that interacts with the contract
27
- * @param callback callback that may be used to extract error code
28
- * @returns {T}
29
- */
30
- export async function handleContractError(func, callback) {
31
- try {
32
- return await func();
33
- }
34
- catch (err) {
35
- if (err instanceof Error) {
36
- if (callback) {
37
- throw new ContractError(err, callback(err));
38
- }
39
- throw new ContractError(err);
40
- }
41
- throw err;
42
- }
43
- }
44
- /**
45
- * Pause async function execution for given amount of milliseconds
46
- * @param ms millisecond to sleep for
47
- */
48
- export function sleep(ms) {
49
- return new Promise((resolve) => setTimeout(resolve, ms));
50
- }
51
- export const divCeilN = (n, d) => n / d + (n % d ? BigInt(1) : BigInt(0));
@@ -1,2 +0,0 @@
1
- import { MemcmpFilter, PublicKey } from "@solana/web3.js";
2
- export declare const getFilters: <T extends Record<string, number | PublicKey>>(criteria: T, byteOffsets: Record<keyof T, number>) => MemcmpFilter[];
@@ -1,15 +0,0 @@
1
- export const getFilters = (criteria, byteOffsets) => {
2
- return Object.entries(criteria).reduce((acc, [key, value]) => {
3
- const criteriaKey = key;
4
- const effectiveByteOffset = byteOffsets[criteriaKey];
5
- if (criteria[criteriaKey] && effectiveByteOffset) {
6
- acc.push({
7
- memcmp: {
8
- offset: effectiveByteOffset,
9
- bytes: value.toString(),
10
- },
11
- });
12
- }
13
- return acc;
14
- }, []);
15
- };
@@ -1,3 +0,0 @@
1
- import { Connection, PublicKey, TransactionInstruction } from "@solana/web3.js";
2
- import BN from "bn.js";
3
- export declare const prepareWrappedAccount: (connection: Connection, senderAddress: PublicKey, amount: BN) => Promise<TransactionInstruction[]>;
@@ -1,18 +0,0 @@
1
- import { getAssociatedTokenAddress, NATIVE_MINT, createAssociatedTokenAccountInstruction, createSyncNativeInstruction, } from "@solana/spl-token";
2
- import { SystemProgram } from "@solana/web3.js";
3
- export const prepareWrappedAccount = async (connection, senderAddress, amount) => {
4
- const tokenAccount = await getAssociatedTokenAddress(NATIVE_MINT, senderAddress, true);
5
- const accInfo = await connection.getParsedAccountInfo(tokenAccount);
6
- const instructions = (accInfo.value?.lamports ?? 0) > 0
7
- ? []
8
- : [createAssociatedTokenAccountInstruction(senderAddress, tokenAccount, senderAddress, NATIVE_MINT)];
9
- return [
10
- ...instructions,
11
- SystemProgram.transfer({
12
- fromPubkey: senderAddress,
13
- toPubkey: tokenAccount,
14
- lamports: amount.toNumber(),
15
- }),
16
- createSyncNativeInstruction(tokenAccount),
17
- ];
18
- };
@@ -1,7 +0,0 @@
1
- import { PublicKey } from "@solana/web3.js";
2
- /**
3
- * Converts a string or PublicKey to a PublicKey object.
4
- * @param address - The input address as a string or PublicKey.
5
- * @returns The PublicKey object.
6
- */
7
- export declare const pk: (address: string | PublicKey) => PublicKey;
@@ -1,9 +0,0 @@
1
- import { PublicKey } from "@solana/web3.js";
2
- /**
3
- * Converts a string or PublicKey to a PublicKey object.
4
- * @param address - The input address as a string or PublicKey.
5
- * @returns The PublicKey object.
6
- */
7
- export const pk = (address) => {
8
- return typeof address === "string" ? new PublicKey(address) : address;
9
- };