@hawksightco/hawk-sdk 1.3.265 → 1.3.266

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 (181) hide show
  1. package/dist/addresses.d.ts +37 -0
  2. package/dist/addresses.d.ts.map +1 -0
  3. package/dist/addresses.js +84 -0
  4. package/dist/anchor.d.ts +22 -0
  5. package/dist/anchor.d.ts.map +1 -0
  6. package/dist/anchor.js +121 -0
  7. package/dist/classes/AltStorage.d.ts +29 -0
  8. package/dist/classes/AltStorage.d.ts.map +1 -0
  9. package/dist/classes/AltStorage.js +58 -0
  10. package/dist/classes/Atomicity.d.ts +34 -0
  11. package/dist/classes/Atomicity.d.ts.map +1 -0
  12. package/dist/classes/Atomicity.js +110 -0
  13. package/dist/classes/Client.d.ts +35 -0
  14. package/dist/classes/Client.d.ts.map +1 -0
  15. package/dist/classes/Client.js +66 -0
  16. package/dist/classes/CombineTransactions.d.ts +11 -0
  17. package/dist/classes/CombineTransactions.d.ts.map +1 -0
  18. package/dist/classes/CombineTransactions.js +58 -0
  19. package/dist/classes/CreateTxMetadata.d.ts +100 -0
  20. package/dist/classes/CreateTxMetadata.d.ts.map +1 -0
  21. package/dist/classes/CreateTxMetadata.js +415 -0
  22. package/dist/classes/General.d.ts +87 -0
  23. package/dist/classes/General.d.ts.map +1 -0
  24. package/dist/classes/General.js +176 -0
  25. package/dist/classes/GeneralUtility.d.ts +79 -0
  26. package/dist/classes/GeneralUtility.d.ts.map +1 -0
  27. package/dist/classes/GeneralUtility.js +121 -0
  28. package/dist/classes/HawkAPI.d.ts +122 -0
  29. package/dist/classes/HawkAPI.d.ts.map +1 -0
  30. package/dist/classes/HawkAPI.js +169 -0
  31. package/dist/classes/Health.d.ts +29 -0
  32. package/dist/classes/Health.d.ts.map +1 -0
  33. package/dist/classes/Health.js +48 -0
  34. package/dist/classes/JupiterAlts.d.ts +37 -0
  35. package/dist/classes/JupiterAlts.d.ts.map +1 -0
  36. package/dist/classes/JupiterAlts.js +114 -0
  37. package/dist/classes/JupiterSwap.d.ts +21 -0
  38. package/dist/classes/JupiterSwap.d.ts.map +1 -0
  39. package/dist/classes/JupiterSwap.js +40 -0
  40. package/dist/classes/Logging.d.ts +13 -0
  41. package/dist/classes/Logging.d.ts.map +1 -0
  42. package/dist/classes/Logging.js +50 -0
  43. package/dist/classes/MultiTransaction.d.ts +75 -0
  44. package/dist/classes/MultiTransaction.d.ts.map +1 -0
  45. package/dist/classes/MultiTransaction.js +296 -0
  46. package/dist/classes/RaydiumSDK.d.ts +67 -0
  47. package/dist/classes/RaydiumSDK.d.ts.map +1 -0
  48. package/dist/classes/RaydiumSDK.js +206 -0
  49. package/dist/classes/Search.d.ts +100 -0
  50. package/dist/classes/Search.d.ts.map +1 -0
  51. package/dist/classes/Search.js +216 -0
  52. package/dist/classes/SimpleIxGenerator.d.ts +57 -0
  53. package/dist/classes/SimpleIxGenerator.d.ts.map +1 -0
  54. package/dist/classes/SimpleIxGenerator.js +62 -0
  55. package/dist/classes/SimplePdaGenerator.d.ts +28 -0
  56. package/dist/classes/SimplePdaGenerator.d.ts.map +1 -0
  57. package/dist/classes/SimplePdaGenerator.js +33 -0
  58. package/dist/classes/Transaction.d.ts +229 -0
  59. package/dist/classes/Transaction.d.ts.map +1 -0
  60. package/dist/classes/Transaction.js +643 -0
  61. package/dist/classes/Transaction2.d.ts +107 -0
  62. package/dist/classes/Transaction2.d.ts.map +1 -0
  63. package/dist/classes/Transaction2.js +249 -0
  64. package/dist/classes/Transaction3.d.ts +165 -0
  65. package/dist/classes/Transaction3.d.ts.map +1 -0
  66. package/dist/classes/Transaction3.js +416 -0
  67. package/dist/classes/TransactionBatchExecute.d.ts +163 -0
  68. package/dist/classes/TransactionBatchExecute.d.ts.map +1 -0
  69. package/dist/classes/TransactionBatchExecute.js +466 -0
  70. package/dist/classes/TransactionBatchExecute2.d.ts +99 -0
  71. package/dist/classes/TransactionBatchExecute2.d.ts.map +1 -0
  72. package/dist/classes/TransactionBatchExecute2.js +357 -0
  73. package/dist/classes/Transactions.d.ts +586 -0
  74. package/dist/classes/Transactions.d.ts.map +1 -0
  75. package/dist/classes/Transactions.js +7667 -0
  76. package/dist/classes/TxGenerator.d.ts +350 -0
  77. package/dist/classes/TxGenerator.d.ts.map +1 -0
  78. package/dist/classes/TxGenerator.js +1957 -0
  79. package/dist/classes/TxGeneratorAutomations.d.ts +186 -0
  80. package/dist/classes/TxGeneratorAutomations.d.ts.map +1 -0
  81. package/dist/classes/TxGeneratorAutomations.js +897 -0
  82. package/dist/classes/Util.d.ts +87 -0
  83. package/dist/classes/Util.d.ts.map +1 -0
  84. package/dist/classes/Util.js +148 -0
  85. package/dist/classes/account-cache/AccountCache.d.ts +54 -0
  86. package/dist/classes/account-cache/AccountCache.d.ts.map +1 -0
  87. package/dist/classes/account-cache/AccountCache.js +143 -0
  88. package/dist/classes/account-cache/MintCache.d.ts +33 -0
  89. package/dist/classes/account-cache/MintCache.d.ts.map +1 -0
  90. package/dist/classes/account-cache/MintCache.js +47 -0
  91. package/dist/classes/account-cache/TokenCache.d.ts +33 -0
  92. package/dist/classes/account-cache/TokenCache.d.ts.map +1 -0
  93. package/dist/classes/account-cache/TokenCache.js +47 -0
  94. package/dist/errors.d.ts +13 -0
  95. package/dist/errors.d.ts.map +1 -0
  96. package/dist/errors.js +96 -0
  97. package/dist/functions.d.ts +514 -0
  98. package/dist/functions.d.ts.map +1 -0
  99. package/dist/functions.js +1636 -0
  100. package/dist/hawksight.d.ts +53 -0
  101. package/dist/hawksight.d.ts.map +1 -0
  102. package/dist/hawksight.js +328 -0
  103. package/dist/hsToMeteora.d.ts +31 -0
  104. package/dist/hsToMeteora.d.ts.map +1 -0
  105. package/dist/hsToMeteora.js +3175 -0
  106. package/dist/idl/iyf-extension-idl.d.ts +14583 -0
  107. package/dist/idl/iyf-extension-idl.d.ts.map +1 -0
  108. package/dist/idl/iyf-extension-idl.js +14578 -0
  109. package/dist/idl/iyf-extension-wrapper.d.ts +112 -0
  110. package/dist/idl/iyf-extension-wrapper.d.ts.map +1 -0
  111. package/dist/idl/iyf-extension-wrapper.js +2 -0
  112. package/dist/idl/iyf-main-idl.d.ts +12078 -0
  113. package/dist/idl/iyf-main-idl.d.ts.map +1 -0
  114. package/dist/idl/iyf-main-idl.js +12073 -0
  115. package/dist/idl/iyf-main-wrapper.d.ts +112 -0
  116. package/dist/idl/iyf-main-wrapper.d.ts.map +1 -0
  117. package/dist/idl/iyf-main-wrapper.js +2 -0
  118. package/dist/idl/jupiter-idl.d.ts +3063 -0
  119. package/dist/idl/jupiter-idl.d.ts.map +1 -0
  120. package/dist/idl/jupiter-idl.js +3061 -0
  121. package/dist/idl/meteora-idl.d.ts +7371 -0
  122. package/dist/idl/meteora-idl.d.ts.map +1 -0
  123. package/dist/idl/meteora-idl.js +7372 -0
  124. package/dist/idl/orca-idl.d.ts +3833 -0
  125. package/dist/idl/orca-idl.d.ts.map +1 -0
  126. package/dist/idl/orca-idl.js +3834 -0
  127. package/dist/idl/raydium-idl.d.ts +3054 -0
  128. package/dist/idl/raydium-idl.d.ts.map +1 -0
  129. package/dist/idl/raydium-idl.js +3055 -0
  130. package/dist/index.d.ts +9 -0
  131. package/dist/index.d.ts.map +1 -0
  132. package/dist/index.js +31 -0
  133. package/dist/ixGenerator/IyfExtensionIxGenerator.d.ts +126 -0
  134. package/dist/ixGenerator/IyfExtensionIxGenerator.d.ts.map +1 -0
  135. package/dist/ixGenerator/IyfExtensionIxGenerator.js +467 -0
  136. package/dist/ixGenerator/IyfMainIxGenerator.d.ts +330 -0
  137. package/dist/ixGenerator/IyfMainIxGenerator.d.ts.map +1 -0
  138. package/dist/ixGenerator/IyfMainIxGenerator.js +1239 -0
  139. package/dist/ixGenerator/MeteoraDlmmIxGenerator.d.ts +685 -0
  140. package/dist/ixGenerator/MeteoraDlmmIxGenerator.d.ts.map +1 -0
  141. package/dist/ixGenerator/MeteoraDlmmIxGenerator.js +3005 -0
  142. package/dist/ixGenerator/OrcaIxGenerator.d.ts +119 -0
  143. package/dist/ixGenerator/OrcaIxGenerator.d.ts.map +1 -0
  144. package/dist/ixGenerator/OrcaIxGenerator.js +438 -0
  145. package/dist/ixGenerator/RaydiumIxGenerator.d.ts +99 -0
  146. package/dist/ixGenerator/RaydiumIxGenerator.d.ts.map +1 -0
  147. package/dist/ixGenerator/RaydiumIxGenerator.js +558 -0
  148. package/dist/ixGenerator/UtilIxGenerator.d.ts +20 -0
  149. package/dist/ixGenerator/UtilIxGenerator.d.ts.map +1 -0
  150. package/dist/ixGenerator/UtilIxGenerator.js +25 -0
  151. package/dist/meteora/index.d.ts +2 -0
  152. package/dist/meteora/index.d.ts.map +1 -0
  153. package/dist/meteora/index.js +17 -0
  154. package/dist/meteora/liquidityStrategy.d.ts +408 -0
  155. package/dist/meteora/liquidityStrategy.d.ts.map +1 -0
  156. package/dist/meteora/liquidityStrategy.js +1325 -0
  157. package/dist/meteora.d.ts +669 -0
  158. package/dist/meteora.d.ts.map +1 -0
  159. package/dist/meteora.js +1932 -0
  160. package/dist/orca.d.ts +57 -0
  161. package/dist/orca.d.ts.map +1 -0
  162. package/dist/orca.js +123 -0
  163. package/dist/pdaGenerator/HawksightPdaGenerator.d.ts +29 -0
  164. package/dist/pdaGenerator/HawksightPdaGenerator.d.ts.map +1 -0
  165. package/dist/pdaGenerator/HawksightPdaGenerator.js +75 -0
  166. package/dist/pdaGenerator/MeteoraPdaGenerator.d.ts +76 -0
  167. package/dist/pdaGenerator/MeteoraPdaGenerator.d.ts.map +1 -0
  168. package/dist/pdaGenerator/MeteoraPdaGenerator.js +166 -0
  169. package/dist/pdaGenerator/OrcaPdaGenerator.d.ts +23 -0
  170. package/dist/pdaGenerator/OrcaPdaGenerator.d.ts.map +1 -0
  171. package/dist/pdaGenerator/OrcaPdaGenerator.js +68 -0
  172. package/dist/pdaGenerator/RaydiumPdaGenerator.d.ts +49 -0
  173. package/dist/pdaGenerator/RaydiumPdaGenerator.d.ts.map +1 -0
  174. package/dist/pdaGenerator/RaydiumPdaGenerator.js +114 -0
  175. package/dist/pdaGenerator/UtilPdaGenerator.d.ts +8 -0
  176. package/dist/pdaGenerator/UtilPdaGenerator.d.ts.map +1 -0
  177. package/dist/pdaGenerator/UtilPdaGenerator.js +51 -0
  178. package/dist/types.d.ts +1104 -0
  179. package/dist/types.d.ts.map +1 -0
  180. package/dist/types.js +95 -0
  181. package/package.json +6 -5
@@ -0,0 +1,643 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.Transaction = void 0;
46
+ const client = __importStar(require("@hawksightco/swagger-client"));
47
+ const web3 = __importStar(require("@solana/web3.js"));
48
+ const bn_js_1 = require("bn.js");
49
+ const functions_1 = require("../functions");
50
+ const Logging_1 = require("./Logging");
51
+ /**
52
+ * Represents a transaction object in Solana using the web3.js library.
53
+ * This class encapsulates the logic for creating, signing, and verifying signatures of transactions.
54
+ */
55
+ class Transaction {
56
+ get txMessage() {
57
+ return this._txMessage;
58
+ }
59
+ get versionedTransaction() {
60
+ return this._versionedTransaction;
61
+ }
62
+ get priorityFeeEstimate() {
63
+ return this._priorityFeeEstimate;
64
+ }
65
+ /** The blockhash of a recent ledger entry */
66
+ get recentBlockhash() {
67
+ return this.latestBlockhash.blockhash;
68
+ }
69
+ get instructions() {
70
+ return this._instructions;
71
+ }
72
+ /** last valid block height */
73
+ get lastValidBlockHeight() {
74
+ return this.latestBlockhash.lastValidBlockHeight;
75
+ }
76
+ /**
77
+ * Constructs a new Transaction object.
78
+ *
79
+ * @param payerKey PublicKey of the transaction payer
80
+ * @param instructions Array of TransactionInstruction to be executed in this transaction
81
+ * @param recentBlockhash The blockhash of a recent ledger entry
82
+ * @param alts Address lookup tables that optimize account address storage
83
+ */
84
+ constructor(txMetadataResponse, payerKey, latestBlockhash, alts, generalUtility, _mainIxs = []) {
85
+ this.txMetadataResponse = txMetadataResponse;
86
+ this.payerKey = payerKey;
87
+ this.latestBlockhash = latestBlockhash;
88
+ this.alts = alts;
89
+ this.generalUtility = generalUtility;
90
+ this.MAX_TX_SIZE = 1200;
91
+ /** Estimated fee in SOL for priority fee when addPriorityFee() method is called. */
92
+ this._priorityFeeEstimate = "";
93
+ txMetadataResponse.payer = payerKey.toBase58();
94
+ let mainIxs;
95
+ if (_mainIxs.length > 0) {
96
+ mainIxs = _mainIxs;
97
+ txMetadataResponse.mainInstructions = mainIxs.map(ix => {
98
+ const accounts = ix.keys.map(meta => {
99
+ return {
100
+ pubkey: meta.pubkey.toString(),
101
+ isSigner: meta.isSigner,
102
+ isWritable: meta.isWritable,
103
+ };
104
+ });
105
+ return {
106
+ accounts,
107
+ programId: ix.programId.toString(),
108
+ data: ix.data.toString('base64'),
109
+ };
110
+ });
111
+ }
112
+ else {
113
+ // Construct main instructions
114
+ mainIxs = txMetadataResponse.mainInstructions.map((ix) => {
115
+ return new web3.TransactionInstruction({
116
+ keys: ix.accounts.map((meta) => {
117
+ return {
118
+ pubkey: new web3.PublicKey(meta.pubkey),
119
+ isSigner: meta.isSigner,
120
+ isWritable: meta.isWritable,
121
+ };
122
+ }),
123
+ programId: new web3.PublicKey(ix.programId),
124
+ data: Buffer.from(ix.data, "base64"),
125
+ });
126
+ });
127
+ }
128
+ this._instructions = [...mainIxs];
129
+ const [txMessage, versionedTransaction] = this.buildTransaction(latestBlockhash);
130
+ this._txMessage = txMessage;
131
+ this._versionedTransaction = versionedTransaction;
132
+ this.requiredSigners = this.getRequiredSigners();
133
+ }
134
+ /**
135
+ * Signs the transaction with provided signers.
136
+ *
137
+ * @param signers Array of Signer objects whose private keys will be used to sign the transaction.
138
+ * @param idempotent Boolean indicating whether signing should be idempotent (default is false).
139
+ * @throws Error if a signer is not required or has already signed the transaction when not idempotent.
140
+ */
141
+ sign(signers, idempotent = false) {
142
+ // First validate all signers
143
+ signers.forEach((signer) => {
144
+ const key = signer.publicKey.toString();
145
+ if (typeof this.requiredSigners[key] !== "boolean") {
146
+ throw new Error(`Key ${key} is not a required signer!`);
147
+ }
148
+ if (!idempotent && this.requiredSigners[key]) {
149
+ throw new Error(`Key ${key} has already been signed by required signer!`);
150
+ }
151
+ });
152
+ // If all signers are valid and the process is idempotent or they haven't signed yet, update and sign
153
+ signers.forEach((signer) => {
154
+ const key = signer.publicKey.toString();
155
+ this.requiredSigners[key] = true;
156
+ });
157
+ this.versionedTransaction.sign(signers);
158
+ }
159
+ /**
160
+ * Add a signature on the transaction with provided signature.
161
+ *
162
+ * @param publicKey The public key of the signer
163
+ * @param signature A signature of the signed transaction
164
+ * @throws Error if a signer is not required or has already signed the transaction.
165
+ */
166
+ addSignature(publicKey, signature) {
167
+ const key = publicKey.toBase58();
168
+ if (typeof this.requiredSigners[key] !== "boolean") {
169
+ throw new Error(`Key ${key} is not a required signer!`);
170
+ }
171
+ if (this.requiredSigners[key]) {
172
+ throw new Error(`Key ${key} has already been signed by required signer!`);
173
+ }
174
+ this.requiredSigners[key] = true;
175
+ this.versionedTransaction.addSignature(publicKey, signature);
176
+ }
177
+ /**
178
+ * Checks if all required signers have signed the transaction.
179
+ *
180
+ * @returns Boolean indicating whether all required signers have signed.
181
+ */
182
+ isSignedByRequiredSigners() {
183
+ return Object.values(this.requiredSigners).every((isSigned) => isSigned);
184
+ }
185
+ /**
186
+ * Add priority fee instructions (compute budget)
187
+ *
188
+ * This method adds priority fee instructions to the transaction based on the specified
189
+ * priority level and compute unit limit. It ensures that the total fee does not exceed
190
+ * the specified maximum priority fee (in SOL) if provided.
191
+ *
192
+ * @param connection - The connection to the Solana cluster.
193
+ * @param computeUnitLimit - The limit on the number of compute units.
194
+ * @param fixedPriority - If true, a fixed priority fee is used; if false, the fee is based on priority level.
195
+ * @param priorityLevelOrPriorityFee - The priority level for the fee estimation or the fixed priority fee.
196
+ * @param maxPriorityFee - The maximum priority fee in SOL (optional, only applicable when fixedPriority is false).
197
+ * @returns An array of transaction instructions.
198
+ */
199
+ addPriorityFeeIx(connection_1, computeUnitLimit_1) {
200
+ return __awaiter(this, arguments, void 0, function* (connection, computeUnitLimit, fixedPriority = false, priorityLevelOrPriorityFee, maxPriorityFee) {
201
+ (0, Logging_1.Log)(`addPriorityFeeIx`);
202
+ // First, remove any existing priority fee instructions
203
+ this.removePriorityFeeIxs();
204
+ let totalPriorityFeeLamports;
205
+ if (fixedPriority && typeof priorityLevelOrPriorityFee === 'number') {
206
+ // For fixed priority, directly use the provided fixed priority fee
207
+ totalPriorityFeeLamports = priorityLevelOrPriorityFee - 5000;
208
+ }
209
+ else if (typeof priorityLevelOrPriorityFee === 'string') {
210
+ // Convert maxPriorityFee from SOL to lamports (1 SOL = 1_000_000_000 lamports)
211
+ const maxPriorityFeeLamports = maxPriorityFee !== undefined ? maxPriorityFee * 1000000000 : undefined;
212
+ // Get fee estimate by simulating the transaction
213
+ const startTime = new Date().getTime() / 1000;
214
+ (0, Logging_1.Log)(`addPriorityFeeIx: Starting getFeeEstimate function`);
215
+ let estimate = yield (0, functions_1.getFeeEstimate)(this.generalUtility, priorityLevelOrPriorityFee, this.txMetadataResponse);
216
+ (0, Logging_1.Log)(`addPriorityFeeIx: Starting getFeeEstimate function: Elapsed Time: ${(new Date().getTime() / 1000) - startTime}`);
217
+ // If priority is set to default or medium, we multiply estimate by 2 to increase its chance on blockchain.
218
+ if (priorityLevelOrPriorityFee === client.PriorityLevel.Default || priorityLevelOrPriorityFee === client.PriorityLevel.Medium) {
219
+ estimate = estimate * 2;
220
+ }
221
+ // Calculate the total fee in lamports
222
+ totalPriorityFeeLamports = new bn_js_1.BN(estimate).mul(new bn_js_1.BN(computeUnitLimit)).div(new bn_js_1.BN(1000000)).toNumber();
223
+ // If maxPriorityFee is defined and it is less than the total calculated fee, cap it
224
+ if (maxPriorityFeeLamports !== undefined && totalPriorityFeeLamports > maxPriorityFeeLamports) {
225
+ totalPriorityFeeLamports = maxPriorityFeeLamports - 5000;
226
+ }
227
+ }
228
+ else {
229
+ throw new Error('Invalid parameters');
230
+ }
231
+ // Convert the total priority fee back to microLamports per compute unit
232
+ const priorityFeePerUnitMicroLamports = new bn_js_1.BN(totalPriorityFeeLamports).mul(new bn_js_1.BN(1000000)).div(new bn_js_1.BN(computeUnitLimit)).toNumber();
233
+ // Create priority fee instructions for the transaction
234
+ const priorityFeeIxs = [
235
+ web3.ComputeBudgetProgram.setComputeUnitLimit({
236
+ units: computeUnitLimit,
237
+ }),
238
+ web3.ComputeBudgetProgram.setComputeUnitPrice({
239
+ microLamports: priorityFeePerUnitMicroLamports,
240
+ }),
241
+ ];
242
+ // Store the total priority fee in lamports
243
+ this._priorityFeeEstimate = totalPriorityFeeLamports.toString();
244
+ // Append priority fee instructions at the beginning
245
+ this._instructions.unshift(...priorityFeeIxs);
246
+ // Rebuild versioned transaction with the latest blockhash
247
+ const blockhash = yield connection.getLatestBlockhash();
248
+ this.buildTransaction(blockhash);
249
+ return priorityFeeIxs;
250
+ });
251
+ }
252
+ /**
253
+ * Gets the compute unit limit from a transaction simulation.
254
+ *
255
+ * This function simulates a transaction and calculates the compute unit limit
256
+ * based on the simulation results. If an additional compute limit is provided,
257
+ * it is added to the units consumed in the simulation. Otherwise, the units
258
+ * consumed are increased by 10%.
259
+ *
260
+ * @param {web3.Connection} connection - The connection object to the Solana cluster.
261
+ * @param {number} [additionalComputeLimit] - Optional additional compute limit to add to the units consumed.
262
+ * @returns {Promise<number>} - A promise that resolves to the total compute unit limit.
263
+ * @throws {Error} - Throws an error if the transaction simulation fails.
264
+ */
265
+ getComputeUnitLimit(connection, additionalComputeLimit) {
266
+ return __awaiter(this, void 0, void 0, function* () {
267
+ const simulation = yield this.simulateTransaction(connection);
268
+ if (simulation.err !== null) {
269
+ if (simulation.logs === null) {
270
+ (0, Logging_1.Log)(simulation.err);
271
+ }
272
+ else {
273
+ for (const log of simulation.logs) {
274
+ (0, Logging_1.Log)(log);
275
+ }
276
+ }
277
+ throw new Error(`Transaction simulation error. See logs above.`);
278
+ }
279
+ const totalUnitLimit = additionalComputeLimit ? simulation.unitsConsumed + additionalComputeLimit : Math.round(simulation.unitsConsumed * 1.1);
280
+ return totalUnitLimit;
281
+ });
282
+ }
283
+ /**
284
+ * Simulate transaction
285
+ *
286
+ * @param connection
287
+ * @returns
288
+ */
289
+ simulateTransaction(connection_1) {
290
+ return __awaiter(this, arguments, void 0, function* (connection, signers = []) {
291
+ const testInstructions = [
292
+ ...this.instructions,
293
+ ];
294
+ if (this.findSetComputeUnitLimitIndex(testInstructions) === -1) {
295
+ testInstructions.unshift(web3.ComputeBudgetProgram.setComputeUnitLimit({ units: 1400000 }));
296
+ }
297
+ if (this.findSetComputeUnitPriceIndex(testInstructions) === -1) {
298
+ testInstructions.unshift(web3.ComputeBudgetProgram.setComputeUnitPrice({
299
+ // CU * CU PRICE -> 1400000 * feeEstimate.priorityFeeEstimate
300
+ microLamports: 100000,
301
+ }));
302
+ }
303
+ const testVersionedTxn = new web3.VersionedTransaction(new web3.TransactionMessage({
304
+ instructions: testInstructions,
305
+ payerKey: this.payerKey,
306
+ recentBlockhash: web3.PublicKey.default.toString(),
307
+ }).compileToV0Message(this.alts));
308
+ if (signers.length > 0) {
309
+ testVersionedTxn.sign(signers);
310
+ }
311
+ const simulation = yield connection.simulateTransaction(testVersionedTxn, {
312
+ replaceRecentBlockhash: true,
313
+ sigVerify: false,
314
+ });
315
+ if (simulation.value.unitsConsumed === undefined) {
316
+ throw new Error("Unable to calculate compute budget.");
317
+ }
318
+ return {
319
+ err: simulation.value.err,
320
+ logs: simulation.value.logs,
321
+ accounts: simulation.value.accounts,
322
+ unitsConsumed: simulation.value.unitsConsumed,
323
+ returnData: simulation.value.returnData,
324
+ };
325
+ });
326
+ }
327
+ /**
328
+ * Builds transaction object
329
+ */
330
+ buildTransaction(latestBlockhash) {
331
+ this.latestBlockhash = latestBlockhash;
332
+ this._txMessage = new web3.TransactionMessage({
333
+ payerKey: this.payerKey,
334
+ instructions: this.instructions,
335
+ recentBlockhash: this.recentBlockhash,
336
+ });
337
+ this._versionedTransaction = new web3.VersionedTransaction(this.txMessage.compileToV0Message(this.alts));
338
+ return [this._txMessage, this._versionedTransaction];
339
+ }
340
+ /**
341
+ * Gathers the public keys of all parties required to sign the transaction.
342
+ *
343
+ * @returns A record of signer public keys mapped to a boolean indicating whether they have signed.
344
+ */
345
+ getRequiredSigners() {
346
+ const signerKeys = this.instructions.flatMap((ix) => ix.keys
347
+ .filter((meta) => meta.isSigner)
348
+ .map((meta) => meta.pubkey.toString()));
349
+ const result = {};
350
+ signerKeys.forEach((key) => (result[key] = false));
351
+ return result;
352
+ }
353
+ /**
354
+ * Find setComputeUnitLimit index within the instructions
355
+ */
356
+ findSetComputeUnitLimitIndex(instructions) {
357
+ let _instructions = [];
358
+ if (instructions !== undefined) {
359
+ _instructions = instructions;
360
+ }
361
+ else {
362
+ _instructions = this.instructions;
363
+ }
364
+ return _instructions.findIndex((ix) => {
365
+ const isComputeBudgetProgram = ix.programId.toString() ===
366
+ "ComputeBudget111111111111111111111111111111";
367
+ const isSetComputeLimitIx = ix.data[0] === 2;
368
+ return isComputeBudgetProgram && isSetComputeLimitIx;
369
+ });
370
+ }
371
+ /**
372
+ * Find setComputeUnitPrice index within the instructions
373
+ */
374
+ findSetComputeUnitPriceIndex(instructions) {
375
+ let _instructions = [];
376
+ if (instructions !== undefined) {
377
+ _instructions = instructions;
378
+ }
379
+ else {
380
+ _instructions = this.instructions;
381
+ }
382
+ return _instructions.findIndex((ix) => {
383
+ const isComputeBudgetProgram = ix.programId.toString() ===
384
+ "ComputeBudget111111111111111111111111111111";
385
+ const isSetComputeUnitPriceIx = ix.data[0] === 3;
386
+ return isComputeBudgetProgram && isSetComputeUnitPriceIx;
387
+ });
388
+ }
389
+ /**
390
+ * Remove priority fee instructions
391
+ */
392
+ removePriorityFeeIxs() {
393
+ while (true) {
394
+ const setComputeUnitLimitIxIndex = this.findSetComputeUnitLimitIndex();
395
+ const setComputeUnitPriceIxIndex = this.findSetComputeUnitPriceIndex();
396
+ if (setComputeUnitLimitIxIndex !== -1)
397
+ this._instructions.splice(setComputeUnitLimitIxIndex, 1);
398
+ if (setComputeUnitPriceIxIndex !== -1)
399
+ this._instructions.splice(setComputeUnitPriceIxIndex, 1);
400
+ if (setComputeUnitLimitIxIndex && setComputeUnitPriceIxIndex)
401
+ break;
402
+ }
403
+ }
404
+ /**
405
+ * Injects a candidate user alt into the transaction metadata.
406
+ *
407
+ * @param connection - The connection to the Solana cluster.
408
+ * @returns A new transaction metadata with the candidate user alt injected.
409
+ */
410
+ injectCandidateUserAlt(connection) {
411
+ return __awaiter(this, void 0, void 0, function* () {
412
+ const userAlts = yield (0, functions_1.findUserAlts)(this.payerKey, connection);
413
+ const pubkeys = this.listPubkeys();
414
+ const rank = [];
415
+ for (const alt of userAlts) {
416
+ const p = (0, functions_1.pubkeysInAlt)(pubkeys, alt);
417
+ rank.push(p.length);
418
+ }
419
+ if (rank.length === 0) {
420
+ // If no user alts are found, return the original transaction metadata
421
+ console.log(`No user alts found, returning original transaction metadata`);
422
+ return {
423
+ metadata: yield (0, functions_1.createTxMetadata)(this.generalUtility, connection, this.payerKey.toString(), this.txMetadataResponse),
424
+ withUserAlt: false,
425
+ };
426
+ }
427
+ const highetsRank = Math.max(...rank);
428
+ const highestRankIndex = rank.indexOf(highetsRank);
429
+ const highestRankAlt = userAlts[highestRankIndex];
430
+ // Generate tx metadata with user alt injected
431
+ const metadata = yield this.injectUserAlt(connection, highestRankAlt.key);
432
+ // Serialize the transaction
433
+ const serializedTxn = metadata.transaction.versionedTransaction.serialize();
434
+ // And check if it is within the max tx size
435
+ const withinSizeLimit = serializedTxn.length < this.MAX_TX_SIZE;
436
+ // Log result
437
+ console.log(`Size limit: ${this.MAX_TX_SIZE}, Transaction size: ${serializedTxn.length}, Within size limit: ${withinSizeLimit}`);
438
+ // Return result
439
+ return {
440
+ metadata,
441
+ withUserAlt: withinSizeLimit,
442
+ };
443
+ });
444
+ }
445
+ /**
446
+ * Generate a new transaction metadata with a user alt injected.
447
+ *
448
+ * @param connection - The connection to the Solana cluster.
449
+ * @param lookupTable - The lookup table to inject into the transaction metadata.
450
+ * @returns A new transaction metadata with the user alt injected.
451
+ */
452
+ injectUserAlt(connection, lookupTable) {
453
+ return __awaiter(this, void 0, void 0, function* () {
454
+ // Inject user alt into transaction metadata
455
+ this.txMetadataResponse.addressLookupTableAddresses.push(lookupTable.toString());
456
+ // Create transaction metadata
457
+ return yield (0, functions_1.createTxMetadata)(this.generalUtility, connection, this.payerKey.toString(), this.txMetadataResponse);
458
+ });
459
+ }
460
+ /**
461
+ * Close all address lookup tables.
462
+ * Dev Note: This is a temporary function to close all address lookup tables.
463
+ * This is not meant to be used in production. It is only meant to be used for testing.
464
+ *
465
+ * @param connection - The connection to the Solana cluster.
466
+ */
467
+ deactivateAllAddressLookupTable(connection) {
468
+ return __awaiter(this, void 0, void 0, function* () {
469
+ const userAlts = yield (0, functions_1.findUserAlts)(this.payerKey, connection);
470
+ const mainInstructions = [];
471
+ for (const alt of userAlts) {
472
+ const deactivateIx = web3.AddressLookupTableProgram.deactivateLookupTable({
473
+ lookupTable: alt.key,
474
+ authority: this.payerKey,
475
+ });
476
+ mainInstructions.push(deactivateIx);
477
+ }
478
+ const meta = yield (0, functions_1.createTransactionMeta)({
479
+ payer: this.payerKey,
480
+ description: "Deactivate all address lookup table",
481
+ addressLookupTableAddresses: [],
482
+ mainInstructions,
483
+ });
484
+ return yield (0, functions_1.createTxMetadata)(this.generalUtility, connection, this.payerKey.toString(), meta);
485
+ });
486
+ }
487
+ /**
488
+ * Close all address lookup tables.
489
+ * Dev Note: This is a temporary function to close all address lookup tables.
490
+ * This is not meant to be used in production. It is only meant to be used for testing.
491
+ *
492
+ * @param connection - The connection to the Solana cluster.
493
+ */
494
+ closeAllAddressLookupTable(connection) {
495
+ return __awaiter(this, void 0, void 0, function* () {
496
+ const userAlts = yield (0, functions_1.findUserAlts)(this.payerKey, connection, false);
497
+ const mainInstructions = [];
498
+ for (const alt of userAlts) {
499
+ const closeAltIx = web3.AddressLookupTableProgram.closeLookupTable({
500
+ lookupTable: alt.key,
501
+ authority: this.payerKey,
502
+ recipient: this.payerKey,
503
+ });
504
+ mainInstructions.push(closeAltIx);
505
+ }
506
+ const meta = yield (0, functions_1.createTransactionMeta)({
507
+ payer: this.payerKey,
508
+ description: "Close all address lookup table",
509
+ addressLookupTableAddresses: [],
510
+ mainInstructions,
511
+ });
512
+ return yield (0, functions_1.createTxMetadata)(this.generalUtility, connection, this.payerKey.toString(), meta);
513
+ });
514
+ }
515
+ /**
516
+ * Create a new address lookup table.
517
+ *
518
+ * @param connection - The connection to the Solana cluster.
519
+ * @param payer - The payer of the transaction.
520
+ * @returns A new address lookup table.
521
+ */
522
+ createAddressLookupTable(connection, payer) {
523
+ return __awaiter(this, void 0, void 0, function* () {
524
+ console.log(`createAddressLookupTable`);
525
+ const serializedTxn = this.versionedTransaction.serialize();
526
+ console.log(`serializedTxn:`, serializedTxn.length);
527
+ console.log(`this.MAX_TX_SIZE:`, this.MAX_TX_SIZE);
528
+ // if (serializedTxn.length <= this.MAX_TX_SIZE) {
529
+ // return [null, null];
530
+ // }
531
+ const pubkeys = this.listPubkeys();
532
+ const pubkeysNotInAlt = this.pubkeysNotInAlt(pubkeys);
533
+ const userAlts = yield (0, functions_1.findUserAlts)(this.payerKey, connection);
534
+ let table, lookupTable, createAltIx, extendAltIx;
535
+ console.log(`userAlts:`, userAlts.map(alt => alt.key.toString()));
536
+ // Find candidate alt to extend
537
+ for (const alt of userAlts) {
538
+ if (alt.state.addresses.length < (256 - pubkeysNotInAlt.length)) {
539
+ lookupTable = alt.key;
540
+ table = alt;
541
+ break;
542
+ }
543
+ }
544
+ // If candidate alt is found, extend it
545
+ if (lookupTable) {
546
+ const addresses = this._pubkeysNotInAlt(pubkeysNotInAlt, table).map(pubkey => new web3.PublicKey(pubkey));
547
+ console.log(`addresses:`, addresses.map(address => address.toString()));
548
+ if (addresses.length > 0) {
549
+ extendAltIx = web3.AddressLookupTableProgram.extendLookupTable({
550
+ lookupTable,
551
+ authority: payer,
552
+ payer,
553
+ addresses,
554
+ });
555
+ }
556
+ }
557
+ else {
558
+ // If no candidate alt is found, create a new alt
559
+ [createAltIx, lookupTable] = web3.AddressLookupTableProgram.createLookupTable({
560
+ authority: payer,
561
+ payer,
562
+ recentSlot: yield connection.getSlot(),
563
+ });
564
+ extendAltIx = web3.AddressLookupTableProgram.extendLookupTable({
565
+ lookupTable,
566
+ authority: payer,
567
+ payer,
568
+ addresses: pubkeysNotInAlt.map(pubkey => new web3.PublicKey(pubkey)),
569
+ });
570
+ }
571
+ const mainInstructions = [];
572
+ if (createAltIx) {
573
+ mainInstructions.push(createAltIx);
574
+ }
575
+ if (extendAltIx) {
576
+ mainInstructions.push(extendAltIx);
577
+ }
578
+ // Create transaction metadata
579
+ const meta = yield (0, functions_1.createTransactionMeta)({
580
+ payer: this.payerKey,
581
+ description: "Create / Extend address lookup table",
582
+ addressLookupTableAddresses: [],
583
+ mainInstructions,
584
+ });
585
+ // Return transaction metadata and lookup table
586
+ return [
587
+ yield (0, functions_1.createTxMetadata)(this.generalUtility, connection, this.payerKey.toString(), meta),
588
+ lookupTable
589
+ ];
590
+ });
591
+ }
592
+ pubkeysNotInAlt(pubkeys) {
593
+ const pubkeysNotInAlt = pubkeys.filter(pubkey => !this.pubkeyInAlt(pubkey));
594
+ return pubkeysNotInAlt;
595
+ }
596
+ /**
597
+ * List all unique pubkeys in the instructions
598
+ * @param instructions - Transaction instructions
599
+ * @returns Unique pubkeys
600
+ */
601
+ listPubkeys() {
602
+ const accounts = this.instructions.flatMap((ix) => ix.keys.map((key) => key.pubkey.toString()));
603
+ const uniquePubkeys = [...new Set(accounts)];
604
+ return uniquePubkeys;
605
+ }
606
+ /**
607
+ * Check if a pubkey is in an alt
608
+ * @param pubkey - Pubkey to check
609
+ * @returns True if the pubkey is in an alt, false otherwise
610
+ */
611
+ pubkeyInAlt(pubkey) {
612
+ const alt = this.alts.find(alt => this._pubkeyInAlt(pubkey, alt));
613
+ if (alt) {
614
+ return true;
615
+ }
616
+ else {
617
+ return false;
618
+ }
619
+ }
620
+ _pubkeysNotInAlt(pubkeys, alt) {
621
+ const pubkeysNotInAlt = pubkeys.filter(pubkey => !this._pubkeyInAlt(pubkey, alt));
622
+ return pubkeysNotInAlt;
623
+ }
624
+ /**
625
+ * Check if a pubkey is in an alt
626
+ * @param pubkey - Pubkey to check
627
+ * @returns True if the pubkey is in an alt, false otherwise
628
+ */
629
+ _pubkeyInAlt(pubkey, alt) {
630
+ const address = alt.state.addresses.find(address => {
631
+ if (address.toString() === pubkey) {
632
+ return address;
633
+ }
634
+ });
635
+ if (address) {
636
+ return true;
637
+ }
638
+ else {
639
+ return false;
640
+ }
641
+ }
642
+ }
643
+ exports.Transaction = Transaction;