@atomiqlabs/chain-solana 12.0.14 → 12.0.15

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 (114) hide show
  1. package/LICENSE +201 -201
  2. package/dist/index.d.ts +29 -29
  3. package/dist/index.js +45 -45
  4. package/dist/solana/SolanaChainType.d.ts +11 -11
  5. package/dist/solana/SolanaChainType.js +2 -2
  6. package/dist/solana/SolanaChains.d.ts +20 -20
  7. package/dist/solana/SolanaChains.js +25 -25
  8. package/dist/solana/SolanaInitializer.d.ts +18 -18
  9. package/dist/solana/SolanaInitializer.js +63 -63
  10. package/dist/solana/btcrelay/SolanaBtcRelay.d.ts +228 -228
  11. package/dist/solana/btcrelay/SolanaBtcRelay.js +441 -441
  12. package/dist/solana/btcrelay/headers/SolanaBtcHeader.d.ts +29 -29
  13. package/dist/solana/btcrelay/headers/SolanaBtcHeader.js +34 -34
  14. package/dist/solana/btcrelay/headers/SolanaBtcStoredHeader.d.ts +46 -46
  15. package/dist/solana/btcrelay/headers/SolanaBtcStoredHeader.js +78 -78
  16. package/dist/solana/btcrelay/program/programIdl.json +671 -671
  17. package/dist/solana/chain/SolanaAction.d.ts +26 -26
  18. package/dist/solana/chain/SolanaAction.js +86 -86
  19. package/dist/solana/chain/SolanaChainInterface.d.ts +65 -65
  20. package/dist/solana/chain/SolanaChainInterface.js +125 -125
  21. package/dist/solana/chain/SolanaModule.d.ts +14 -14
  22. package/dist/solana/chain/SolanaModule.js +13 -13
  23. package/dist/solana/chain/modules/SolanaAddresses.d.ts +8 -8
  24. package/dist/solana/chain/modules/SolanaAddresses.js +22 -22
  25. package/dist/solana/chain/modules/SolanaBlocks.d.ts +28 -28
  26. package/dist/solana/chain/modules/SolanaBlocks.js +72 -72
  27. package/dist/solana/chain/modules/SolanaEvents.d.ts +68 -68
  28. package/dist/solana/chain/modules/SolanaEvents.js +238 -238
  29. package/dist/solana/chain/modules/SolanaFees.d.ts +121 -121
  30. package/dist/solana/chain/modules/SolanaFees.js +379 -379
  31. package/dist/solana/chain/modules/SolanaSignatures.d.ts +23 -23
  32. package/dist/solana/chain/modules/SolanaSignatures.js +39 -39
  33. package/dist/solana/chain/modules/SolanaSlots.d.ts +31 -31
  34. package/dist/solana/chain/modules/SolanaSlots.js +68 -68
  35. package/dist/solana/chain/modules/SolanaTokens.d.ts +136 -136
  36. package/dist/solana/chain/modules/SolanaTokens.js +248 -248
  37. package/dist/solana/chain/modules/SolanaTransactions.d.ts +124 -124
  38. package/dist/solana/chain/modules/SolanaTransactions.js +323 -323
  39. package/dist/solana/events/SolanaChainEvents.d.ts +88 -88
  40. package/dist/solana/events/SolanaChainEvents.js +256 -256
  41. package/dist/solana/events/SolanaChainEventsBrowser.d.ts +75 -75
  42. package/dist/solana/events/SolanaChainEventsBrowser.js +172 -172
  43. package/dist/solana/program/SolanaProgramBase.d.ts +40 -40
  44. package/dist/solana/program/SolanaProgramBase.js +43 -43
  45. package/dist/solana/program/SolanaProgramModule.d.ts +8 -8
  46. package/dist/solana/program/SolanaProgramModule.js +11 -11
  47. package/dist/solana/program/modules/SolanaProgramEvents.d.ts +53 -53
  48. package/dist/solana/program/modules/SolanaProgramEvents.js +114 -114
  49. package/dist/solana/swaps/SolanaSwapData.d.ts +71 -71
  50. package/dist/solana/swaps/SolanaSwapData.js +292 -292
  51. package/dist/solana/swaps/SolanaSwapModule.d.ts +10 -10
  52. package/dist/solana/swaps/SolanaSwapModule.js +11 -11
  53. package/dist/solana/swaps/SolanaSwapProgram.d.ts +224 -224
  54. package/dist/solana/swaps/SolanaSwapProgram.js +570 -570
  55. package/dist/solana/swaps/SwapTypeEnum.d.ts +11 -11
  56. package/dist/solana/swaps/SwapTypeEnum.js +42 -42
  57. package/dist/solana/swaps/modules/SolanaDataAccount.d.ts +94 -94
  58. package/dist/solana/swaps/modules/SolanaDataAccount.js +231 -231
  59. package/dist/solana/swaps/modules/SolanaLpVault.d.ts +71 -71
  60. package/dist/solana/swaps/modules/SolanaLpVault.js +173 -173
  61. package/dist/solana/swaps/modules/SwapClaim.d.ts +129 -129
  62. package/dist/solana/swaps/modules/SwapClaim.js +291 -291
  63. package/dist/solana/swaps/modules/SwapInit.d.ts +217 -217
  64. package/dist/solana/swaps/modules/SwapInit.js +519 -519
  65. package/dist/solana/swaps/modules/SwapRefund.d.ts +82 -82
  66. package/dist/solana/swaps/modules/SwapRefund.js +262 -262
  67. package/dist/solana/swaps/programIdl.json +945 -945
  68. package/dist/solana/swaps/programTypes.d.ts +943 -943
  69. package/dist/solana/swaps/programTypes.js +945 -945
  70. package/dist/solana/wallet/SolanaKeypairWallet.d.ts +9 -9
  71. package/dist/solana/wallet/SolanaKeypairWallet.js +33 -33
  72. package/dist/solana/wallet/SolanaSigner.d.ts +11 -11
  73. package/dist/solana/wallet/SolanaSigner.js +17 -17
  74. package/dist/utils/Utils.d.ts +53 -53
  75. package/dist/utils/Utils.js +170 -170
  76. package/package.json +41 -41
  77. package/src/index.ts +36 -36
  78. package/src/solana/SolanaChainType.ts +27 -27
  79. package/src/solana/SolanaChains.ts +23 -23
  80. package/src/solana/SolanaInitializer.ts +102 -102
  81. package/src/solana/btcrelay/SolanaBtcRelay.ts +589 -589
  82. package/src/solana/btcrelay/headers/SolanaBtcHeader.ts +57 -57
  83. package/src/solana/btcrelay/headers/SolanaBtcStoredHeader.ts +102 -102
  84. package/src/solana/btcrelay/program/programIdl.json +670 -670
  85. package/src/solana/chain/SolanaAction.ts +108 -108
  86. package/src/solana/chain/SolanaChainInterface.ts +192 -192
  87. package/src/solana/chain/SolanaModule.ts +20 -20
  88. package/src/solana/chain/modules/SolanaAddresses.ts +20 -20
  89. package/src/solana/chain/modules/SolanaBlocks.ts +78 -78
  90. package/src/solana/chain/modules/SolanaEvents.ts +270 -270
  91. package/src/solana/chain/modules/SolanaFees.ts +450 -450
  92. package/src/solana/chain/modules/SolanaSignatures.ts +39 -39
  93. package/src/solana/chain/modules/SolanaSlots.ts +82 -82
  94. package/src/solana/chain/modules/SolanaTokens.ts +307 -307
  95. package/src/solana/chain/modules/SolanaTransactions.ts +365 -365
  96. package/src/solana/events/SolanaChainEvents.ts +299 -299
  97. package/src/solana/events/SolanaChainEventsBrowser.ts +209 -209
  98. package/src/solana/program/SolanaProgramBase.ts +79 -79
  99. package/src/solana/program/SolanaProgramModule.ts +15 -15
  100. package/src/solana/program/modules/SolanaProgramEvents.ts +155 -155
  101. package/src/solana/swaps/SolanaSwapData.ts +430 -430
  102. package/src/solana/swaps/SolanaSwapModule.ts +16 -16
  103. package/src/solana/swaps/SolanaSwapProgram.ts +854 -854
  104. package/src/solana/swaps/SwapTypeEnum.ts +29 -29
  105. package/src/solana/swaps/modules/SolanaDataAccount.ts +307 -307
  106. package/src/solana/swaps/modules/SolanaLpVault.ts +215 -215
  107. package/src/solana/swaps/modules/SwapClaim.ts +389 -389
  108. package/src/solana/swaps/modules/SwapInit.ts +663 -663
  109. package/src/solana/swaps/modules/SwapRefund.ts +323 -323
  110. package/src/solana/swaps/programIdl.json +944 -944
  111. package/src/solana/swaps/programTypes.ts +1885 -1885
  112. package/src/solana/wallet/SolanaKeypairWallet.ts +36 -36
  113. package/src/solana/wallet/SolanaSigner.ts +24 -24
  114. package/src/utils/Utils.ts +180 -180
@@ -1,323 +1,323 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SolanaTransactions = void 0;
4
- const web3_js_1 = require("@solana/web3.js");
5
- const SolanaModule_1 = require("../SolanaModule");
6
- const bs58 = require("bs58");
7
- const Utils_1 = require("../../../utils/Utils");
8
- const buffer_1 = require("buffer");
9
- const base_1 = require("@atomiqlabs/base");
10
- class SolanaTransactions extends SolanaModule_1.SolanaModule {
11
- /**
12
- * Sends raw solana transaction, first through the cbkSendTransaction callback (for e.g. sending the transaction
13
- * to a different specific RPC), the through the Fees handler (for e.g. Jito transaction) and last through the
14
- * underlying provider's Connection instance (the usual way). Only sends the transaction through one channel.
15
- *
16
- * @param data
17
- * @param options
18
- * @private
19
- */
20
- async sendRawTransaction(data, options) {
21
- let result = null;
22
- options ?? (options = {});
23
- options.maxRetries = 0;
24
- if (this.cbkSendTransaction != null)
25
- result = await this.cbkSendTransaction(data, options);
26
- if (result == null)
27
- result = await this.root.Fees.submitTx(data, options);
28
- if (result == null)
29
- result = await this.connection.sendRawTransaction(data, options);
30
- // this.logger.debug("sendRawTransaction(): tx sent, signature: "+result);
31
- return result;
32
- }
33
- /**
34
- * Waits for the transaction to confirm by periodically checking the transaction status over HTTP, also
35
- * re-sends the transaction at regular intervals
36
- *
37
- * @param solanaTx solana tx to wait for confirmation for
38
- * @param finality wait for this finality
39
- * @param abortSignal signal to abort waiting for tx confirmation
40
- * @private
41
- */
42
- txConfirmationAndResendWatchdog(solanaTx, finality, abortSignal) {
43
- const rawTx = solanaTx.tx.serialize();
44
- const signature = bs58.encode(solanaTx.tx.signature);
45
- return new Promise((resolve, reject) => {
46
- let watchdogInterval;
47
- watchdogInterval = setInterval(async () => {
48
- const result = await this.sendRawTransaction(rawTx, { skipPreflight: true }).catch(e => this.logger.error("txConfirmationAndResendWatchdog(): transaction re-sent error: ", e));
49
- this.logger.debug("txConfirmationAndResendWatchdog(): transaction re-sent: " + result);
50
- const status = await this.getTxIdStatus(signature, finality).catch(e => this.logger.error("txConfirmationAndResendWatchdog(): get tx id status error: ", e));
51
- if (status == null || status === "not_found")
52
- return;
53
- if (status === "success") {
54
- this.logger.info("txConfirmationAndResendWatchdog(): transaction confirmed from HTTP polling, signature: " + signature);
55
- resolve(signature);
56
- }
57
- if (status === "reverted")
58
- reject(new base_1.TransactionRevertedError("Transaction reverted!"));
59
- clearInterval(watchdogInterval);
60
- }, this.retryPolicy?.transactionResendInterval || 3000);
61
- if (abortSignal != null)
62
- abortSignal.addEventListener("abort", () => {
63
- clearInterval(watchdogInterval);
64
- reject(abortSignal.reason);
65
- });
66
- });
67
- }
68
- /**
69
- * Waits for the transaction to confirm from WS, sometimes the WS rejects even though the transaction was confirmed
70
- * this therefore also runs an ultimate check on the transaction in case the WS handler rejects, checking if it
71
- * really was expired
72
- *
73
- * @param solanaTx solana tx to wait for confirmation for
74
- * @param finality wait for this finality
75
- * @param abortSignal signal to abort waiting for tx confirmation
76
- * @private
77
- */
78
- async txConfirmFromWebsocket(solanaTx, finality, abortSignal) {
79
- const signature = bs58.encode(solanaTx.tx.signature);
80
- let result;
81
- try {
82
- result = await this.connection.confirmTransaction({
83
- signature: signature,
84
- blockhash: solanaTx.tx.recentBlockhash,
85
- lastValidBlockHeight: solanaTx.tx.lastValidBlockHeight,
86
- abortSignal
87
- }, finality);
88
- this.logger.info("txConfirmFromWebsocket(): transaction confirmed from WS, signature: " + signature);
89
- }
90
- catch (err) {
91
- if (abortSignal != null && abortSignal.aborted)
92
- throw err;
93
- this.logger.debug("txConfirmFromWebsocket(): transaction rejected from WS, running ultimate check, expiry blockheight: " + solanaTx.tx.lastValidBlockHeight + " signature: " + signature + " error: " + err);
94
- const status = await (0, Utils_1.tryWithRetries)(() => this.getTxIdStatus(signature, finality));
95
- this.logger.info("txConfirmFromWebsocket(): transaction status: " + status + " signature: " + signature);
96
- if (status === "success")
97
- return signature;
98
- if (status === "reverted")
99
- throw new base_1.TransactionRevertedError("Transaction reverted!");
100
- if (err instanceof web3_js_1.TransactionExpiredBlockheightExceededError || err.toString().startsWith("TransactionExpiredBlockheightExceededError")) {
101
- throw new Error("Transaction expired before confirmation, please try again!");
102
- }
103
- else {
104
- throw err;
105
- }
106
- }
107
- if (result.value.err != null)
108
- throw new base_1.TransactionRevertedError("Transaction reverted!");
109
- return signature;
110
- }
111
- /**
112
- * Waits for transaction confirmation using WS subscription and occasional HTTP polling, also re-sends
113
- * the transaction at regular interval
114
- *
115
- * @param solanaTx solana transaction to wait for confirmation for & keep re-sending until it confirms
116
- * @param abortSignal signal to abort waiting for tx confirmation
117
- * @param finality wait for specific finality
118
- * @private
119
- */
120
- async confirmTransaction(solanaTx, abortSignal, finality) {
121
- const abortController = new AbortController();
122
- if (abortSignal != null)
123
- abortSignal.addEventListener("abort", () => {
124
- abortController.abort();
125
- });
126
- let txSignature;
127
- try {
128
- txSignature = await Promise.race([
129
- this.txConfirmationAndResendWatchdog(solanaTx, finality, abortController.signal),
130
- this.txConfirmFromWebsocket(solanaTx, finality, abortController.signal)
131
- ]);
132
- }
133
- catch (e) {
134
- abortController.abort(e);
135
- throw e;
136
- }
137
- // this.logger.info("confirmTransaction(): transaction confirmed, signature: "+txSignature);
138
- abortController.abort();
139
- }
140
- /**
141
- * Prepares solana transactions, assigns recentBlockhash if needed, applies Phantom hotfix,
142
- * sets feePayer to ourselves, calls beforeTxSigned callback & signs transaction with provided signers array
143
- *
144
- * @param signer
145
- * @param txs
146
- * @private
147
- */
148
- async prepareTransactions(signer, txs) {
149
- let latestBlockData = null;
150
- for (let tx of txs) {
151
- if (tx.tx.recentBlockhash == null) {
152
- if (latestBlockData == null) {
153
- latestBlockData = await (0, Utils_1.tryWithRetries)(() => this.connection.getLatestBlockhash("confirmed"), this.retryPolicy);
154
- this.logger.debug("prepareTransactions(): fetched latest block data for transactions," +
155
- " blockhash: " + latestBlockData.blockhash + " expiry blockheight: " + latestBlockData.lastValidBlockHeight);
156
- }
157
- tx.tx.recentBlockhash = latestBlockData.blockhash;
158
- tx.tx.lastValidBlockHeight = latestBlockData.lastValidBlockHeight;
159
- }
160
- //This is a hotfix for Phantom adding compute unit price instruction on the first position & breaking
161
- // required instructions order (e.g. btc relay verify needs to be 0th instruction in a tx)
162
- if (signer.keypair == null && tx.tx.signatures.length === 0) {
163
- const foundIx = tx.tx.instructions.find(ix => ix.programId.equals(web3_js_1.ComputeBudgetProgram.programId) && web3_js_1.ComputeBudgetInstruction.decodeInstructionType(ix) === "SetComputeUnitPrice");
164
- if (foundIx == null)
165
- tx.tx.instructions.splice(tx.tx.instructions.length - 1, 0, web3_js_1.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 }));
166
- }
167
- tx.tx.feePayer = signer.getPublicKey();
168
- if (this.cbkBeforeTxSigned != null)
169
- await this.cbkBeforeTxSigned(tx);
170
- if (tx.signers != null && tx.signers.length > 0)
171
- for (let signer of tx.signers)
172
- tx.tx.sign(signer);
173
- }
174
- }
175
- /**
176
- * Sends out a signed transaction to the RPC
177
- *
178
- * @param solTx solana tx to send
179
- * @param options send options to be passed to the RPC
180
- * @param onBeforePublish a callback called before every transaction is published
181
- * @private
182
- */
183
- async sendSignedTransaction(solTx, options, onBeforePublish) {
184
- if (onBeforePublish != null)
185
- await onBeforePublish(bs58.encode(solTx.tx.signature), await this.serializeTx(solTx));
186
- const serializedTx = solTx.tx.serialize();
187
- this.logger.debug("sendSignedTransaction(): sending transaction: " + serializedTx.toString("hex") +
188
- " signature: " + bs58.encode(solTx.tx.signature));
189
- const txResult = await (0, Utils_1.tryWithRetries)(() => this.sendRawTransaction(serializedTx, options), this.retryPolicy);
190
- this.logger.info("sendSignedTransaction(): tx sent, signature: " + txResult);
191
- return txResult;
192
- }
193
- /**
194
- * Prepares (adds recent blockhash if required, applies Phantom hotfix),
195
- * signs (all together using signAllTransactions() calls), sends (in parallel or sequentially) &
196
- * optionally waits for confirmation of a batch of solana transactions
197
- *
198
- * @param signer
199
- * @param _txs
200
- * @param waitForConfirmation whether to wait for transaction confirmations (this also makes sure the transactions
201
- * are re-sent at regular intervals)
202
- * @param abortSignal abort signal to abort waiting for transaction confirmations
203
- * @param parallel whether the send all the transaction at once in parallel or sequentially (such that transactions
204
- * are executed in order)
205
- * @param onBeforePublish a callback called before every transaction is published
206
- */
207
- async sendAndConfirm(signer, _txs, waitForConfirmation, abortSignal, parallel, onBeforePublish) {
208
- const options = {
209
- skipPreflight: true
210
- };
211
- this.logger.debug("sendAndConfirm(): sending transactions, count: " + _txs.length +
212
- " waitForConfirmation: " + waitForConfirmation + " parallel: " + parallel);
213
- const BATCH_SIZE = 50;
214
- const signatures = [];
215
- for (let e = 0; e < _txs.length; e += BATCH_SIZE) {
216
- const txs = _txs.slice(e, e + BATCH_SIZE);
217
- await this.prepareTransactions(signer, txs);
218
- const signedTxs = await signer.wallet.signAllTransactions(txs.map(e => e.tx));
219
- signedTxs.forEach((tx, index) => {
220
- const solTx = txs[index];
221
- tx.lastValidBlockHeight = solTx.tx.lastValidBlockHeight;
222
- solTx.tx = tx;
223
- });
224
- this.logger.debug("sendAndConfirm(): sending transaction batch (" + e + ".." + (e + 50) + "), count: " + txs.length);
225
- //For solana we are forced to send txs one-by-one even with parallel, as we cannot determine their order upfront,
226
- // however e.g. Jito could possibly handle sending a single package of up to 5 txns in order.
227
- for (let i = 0; i < txs.length; i++) {
228
- const solTx = txs[i];
229
- const signature = await this.sendSignedTransaction(solTx, options, onBeforePublish);
230
- const confirmPromise = this.confirmTransaction(solTx, abortSignal, "confirmed");
231
- //Don't await the last promise when !waitForConfirmation
232
- if (i < txs.length - 1 || e + 50 < _txs.length || waitForConfirmation)
233
- await confirmPromise;
234
- signatures.push(signature);
235
- }
236
- }
237
- this.logger.info("sendAndConfirm(): sent transactions, count: " + _txs.length +
238
- " waitForConfirmation: " + waitForConfirmation + " parallel: " + parallel);
239
- return signatures;
240
- }
241
- /**
242
- * Serializes the solana transaction, saves the transaction, signers & last valid blockheight
243
- *
244
- * @param tx
245
- */
246
- serializeTx(tx) {
247
- return Promise.resolve(JSON.stringify({
248
- tx: tx.tx.serialize().toString("hex"),
249
- signers: tx.signers.map(e => buffer_1.Buffer.from(e.secretKey).toString("hex")),
250
- lastValidBlockheight: tx.tx.lastValidBlockHeight
251
- }));
252
- }
253
- /**
254
- * Deserializes saved solana transaction, extracting the transaction, signers & last valid blockheight
255
- *
256
- * @param txData
257
- */
258
- deserializeTx(txData) {
259
- const jsonParsed = JSON.parse(txData);
260
- const transaction = web3_js_1.Transaction.from(buffer_1.Buffer.from(jsonParsed.tx, "hex"));
261
- transaction.lastValidBlockHeight = jsonParsed.lastValidBlockheight;
262
- return Promise.resolve({
263
- tx: transaction,
264
- signers: jsonParsed.signers.map(e => web3_js_1.Keypair.fromSecretKey(buffer_1.Buffer.from(e, "hex"))),
265
- });
266
- }
267
- /**
268
- * Gets the status of the raw solana transaction, this also checks transaction expiry & can therefore report tx
269
- * in "pending" status, however pending status doesn't necessarily mean that the transaction was sent (again,
270
- * no mempool on Solana, cannot check that), this function is preferred against getTxIdStatus
271
- *
272
- * @param tx
273
- */
274
- async getTxStatus(tx) {
275
- const parsedTx = await this.deserializeTx(tx);
276
- const txReceipt = await this.connection.getTransaction(bs58.encode(parsedTx.tx.signature), {
277
- commitment: "confirmed",
278
- maxSupportedTransactionVersion: 0
279
- });
280
- if (txReceipt == null) {
281
- const currentBlockheight = await this.connection.getBlockHeight("processed");
282
- if (currentBlockheight > parsedTx.tx.lastValidBlockHeight)
283
- return "not_found";
284
- return "pending";
285
- }
286
- if (txReceipt.meta.err)
287
- return "reverted";
288
- return "success";
289
- }
290
- /**
291
- * Gets the status of the solana transaction with a specific txId, this cannot report whether the transaction is
292
- * "pending" because Solana has no concept of mempool & only confirmed transactions are accessible
293
- *
294
- * @param txId
295
- * @param finality
296
- */
297
- async getTxIdStatus(txId, finality) {
298
- const txReceipt = await this.connection.getTransaction(txId, {
299
- commitment: finality || "confirmed",
300
- maxSupportedTransactionVersion: 0
301
- });
302
- if (txReceipt == null)
303
- return "not_found";
304
- if (txReceipt.meta.err)
305
- return "reverted";
306
- return "success";
307
- }
308
- onBeforeTxSigned(callback) {
309
- this.cbkBeforeTxSigned = callback;
310
- }
311
- offBeforeTxSigned(callback) {
312
- this.cbkBeforeTxSigned = null;
313
- return true;
314
- }
315
- onSendTransaction(callback) {
316
- this.cbkSendTransaction = callback;
317
- }
318
- offSendTransaction(callback) {
319
- this.cbkSendTransaction = null;
320
- return true;
321
- }
322
- }
323
- exports.SolanaTransactions = SolanaTransactions;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SolanaTransactions = void 0;
4
+ const web3_js_1 = require("@solana/web3.js");
5
+ const SolanaModule_1 = require("../SolanaModule");
6
+ const bs58 = require("bs58");
7
+ const Utils_1 = require("../../../utils/Utils");
8
+ const buffer_1 = require("buffer");
9
+ const base_1 = require("@atomiqlabs/base");
10
+ class SolanaTransactions extends SolanaModule_1.SolanaModule {
11
+ /**
12
+ * Sends raw solana transaction, first through the cbkSendTransaction callback (for e.g. sending the transaction
13
+ * to a different specific RPC), the through the Fees handler (for e.g. Jito transaction) and last through the
14
+ * underlying provider's Connection instance (the usual way). Only sends the transaction through one channel.
15
+ *
16
+ * @param data
17
+ * @param options
18
+ * @private
19
+ */
20
+ async sendRawTransaction(data, options) {
21
+ let result = null;
22
+ options ?? (options = {});
23
+ options.maxRetries = 0;
24
+ if (this.cbkSendTransaction != null)
25
+ result = await this.cbkSendTransaction(data, options);
26
+ if (result == null)
27
+ result = await this.root.Fees.submitTx(data, options);
28
+ if (result == null)
29
+ result = await this.connection.sendRawTransaction(data, options);
30
+ // this.logger.debug("sendRawTransaction(): tx sent, signature: "+result);
31
+ return result;
32
+ }
33
+ /**
34
+ * Waits for the transaction to confirm by periodically checking the transaction status over HTTP, also
35
+ * re-sends the transaction at regular intervals
36
+ *
37
+ * @param solanaTx solana tx to wait for confirmation for
38
+ * @param finality wait for this finality
39
+ * @param abortSignal signal to abort waiting for tx confirmation
40
+ * @private
41
+ */
42
+ txConfirmationAndResendWatchdog(solanaTx, finality, abortSignal) {
43
+ const rawTx = solanaTx.tx.serialize();
44
+ const signature = bs58.encode(solanaTx.tx.signature);
45
+ return new Promise((resolve, reject) => {
46
+ let watchdogInterval;
47
+ watchdogInterval = setInterval(async () => {
48
+ const result = await this.sendRawTransaction(rawTx, { skipPreflight: true }).catch(e => this.logger.error("txConfirmationAndResendWatchdog(): transaction re-sent error: ", e));
49
+ this.logger.debug("txConfirmationAndResendWatchdog(): transaction re-sent: " + result);
50
+ const status = await this.getTxIdStatus(signature, finality).catch(e => this.logger.error("txConfirmationAndResendWatchdog(): get tx id status error: ", e));
51
+ if (status == null || status === "not_found")
52
+ return;
53
+ if (status === "success") {
54
+ this.logger.info("txConfirmationAndResendWatchdog(): transaction confirmed from HTTP polling, signature: " + signature);
55
+ resolve(signature);
56
+ }
57
+ if (status === "reverted")
58
+ reject(new base_1.TransactionRevertedError("Transaction reverted!"));
59
+ clearInterval(watchdogInterval);
60
+ }, this.retryPolicy?.transactionResendInterval || 3000);
61
+ if (abortSignal != null)
62
+ abortSignal.addEventListener("abort", () => {
63
+ clearInterval(watchdogInterval);
64
+ reject(abortSignal.reason);
65
+ });
66
+ });
67
+ }
68
+ /**
69
+ * Waits for the transaction to confirm from WS, sometimes the WS rejects even though the transaction was confirmed
70
+ * this therefore also runs an ultimate check on the transaction in case the WS handler rejects, checking if it
71
+ * really was expired
72
+ *
73
+ * @param solanaTx solana tx to wait for confirmation for
74
+ * @param finality wait for this finality
75
+ * @param abortSignal signal to abort waiting for tx confirmation
76
+ * @private
77
+ */
78
+ async txConfirmFromWebsocket(solanaTx, finality, abortSignal) {
79
+ const signature = bs58.encode(solanaTx.tx.signature);
80
+ let result;
81
+ try {
82
+ result = await this.connection.confirmTransaction({
83
+ signature: signature,
84
+ blockhash: solanaTx.tx.recentBlockhash,
85
+ lastValidBlockHeight: solanaTx.tx.lastValidBlockHeight,
86
+ abortSignal
87
+ }, finality);
88
+ this.logger.info("txConfirmFromWebsocket(): transaction confirmed from WS, signature: " + signature);
89
+ }
90
+ catch (err) {
91
+ if (abortSignal != null && abortSignal.aborted)
92
+ throw err;
93
+ this.logger.debug("txConfirmFromWebsocket(): transaction rejected from WS, running ultimate check, expiry blockheight: " + solanaTx.tx.lastValidBlockHeight + " signature: " + signature + " error: " + err);
94
+ const status = await (0, Utils_1.tryWithRetries)(() => this.getTxIdStatus(signature, finality));
95
+ this.logger.info("txConfirmFromWebsocket(): transaction status: " + status + " signature: " + signature);
96
+ if (status === "success")
97
+ return signature;
98
+ if (status === "reverted")
99
+ throw new base_1.TransactionRevertedError("Transaction reverted!");
100
+ if (err instanceof web3_js_1.TransactionExpiredBlockheightExceededError || err.toString().startsWith("TransactionExpiredBlockheightExceededError")) {
101
+ throw new Error("Transaction expired before confirmation, please try again!");
102
+ }
103
+ else {
104
+ throw err;
105
+ }
106
+ }
107
+ if (result.value.err != null)
108
+ throw new base_1.TransactionRevertedError("Transaction reverted!");
109
+ return signature;
110
+ }
111
+ /**
112
+ * Waits for transaction confirmation using WS subscription and occasional HTTP polling, also re-sends
113
+ * the transaction at regular interval
114
+ *
115
+ * @param solanaTx solana transaction to wait for confirmation for & keep re-sending until it confirms
116
+ * @param abortSignal signal to abort waiting for tx confirmation
117
+ * @param finality wait for specific finality
118
+ * @private
119
+ */
120
+ async confirmTransaction(solanaTx, abortSignal, finality) {
121
+ const abortController = new AbortController();
122
+ if (abortSignal != null)
123
+ abortSignal.addEventListener("abort", () => {
124
+ abortController.abort();
125
+ });
126
+ let txSignature;
127
+ try {
128
+ txSignature = await Promise.race([
129
+ this.txConfirmationAndResendWatchdog(solanaTx, finality, abortController.signal),
130
+ this.txConfirmFromWebsocket(solanaTx, finality, abortController.signal)
131
+ ]);
132
+ }
133
+ catch (e) {
134
+ abortController.abort(e);
135
+ throw e;
136
+ }
137
+ // this.logger.info("confirmTransaction(): transaction confirmed, signature: "+txSignature);
138
+ abortController.abort();
139
+ }
140
+ /**
141
+ * Prepares solana transactions, assigns recentBlockhash if needed, applies Phantom hotfix,
142
+ * sets feePayer to ourselves, calls beforeTxSigned callback & signs transaction with provided signers array
143
+ *
144
+ * @param signer
145
+ * @param txs
146
+ * @private
147
+ */
148
+ async prepareTransactions(signer, txs) {
149
+ let latestBlockData = null;
150
+ for (let tx of txs) {
151
+ if (tx.tx.recentBlockhash == null) {
152
+ if (latestBlockData == null) {
153
+ latestBlockData = await (0, Utils_1.tryWithRetries)(() => this.connection.getLatestBlockhash("confirmed"), this.retryPolicy);
154
+ this.logger.debug("prepareTransactions(): fetched latest block data for transactions," +
155
+ " blockhash: " + latestBlockData.blockhash + " expiry blockheight: " + latestBlockData.lastValidBlockHeight);
156
+ }
157
+ tx.tx.recentBlockhash = latestBlockData.blockhash;
158
+ tx.tx.lastValidBlockHeight = latestBlockData.lastValidBlockHeight;
159
+ }
160
+ //This is a hotfix for Phantom adding compute unit price instruction on the first position & breaking
161
+ // required instructions order (e.g. btc relay verify needs to be 0th instruction in a tx)
162
+ if (signer.keypair == null && tx.tx.signatures.length === 0) {
163
+ const foundIx = tx.tx.instructions.find(ix => ix.programId.equals(web3_js_1.ComputeBudgetProgram.programId) && web3_js_1.ComputeBudgetInstruction.decodeInstructionType(ix) === "SetComputeUnitPrice");
164
+ if (foundIx == null)
165
+ tx.tx.instructions.splice(tx.tx.instructions.length - 1, 0, web3_js_1.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 }));
166
+ }
167
+ tx.tx.feePayer = signer.getPublicKey();
168
+ if (this.cbkBeforeTxSigned != null)
169
+ await this.cbkBeforeTxSigned(tx);
170
+ if (tx.signers != null && tx.signers.length > 0)
171
+ for (let signer of tx.signers)
172
+ tx.tx.sign(signer);
173
+ }
174
+ }
175
+ /**
176
+ * Sends out a signed transaction to the RPC
177
+ *
178
+ * @param solTx solana tx to send
179
+ * @param options send options to be passed to the RPC
180
+ * @param onBeforePublish a callback called before every transaction is published
181
+ * @private
182
+ */
183
+ async sendSignedTransaction(solTx, options, onBeforePublish) {
184
+ if (onBeforePublish != null)
185
+ await onBeforePublish(bs58.encode(solTx.tx.signature), await this.serializeTx(solTx));
186
+ const serializedTx = solTx.tx.serialize();
187
+ this.logger.debug("sendSignedTransaction(): sending transaction: " + serializedTx.toString("hex") +
188
+ " signature: " + bs58.encode(solTx.tx.signature));
189
+ const txResult = await (0, Utils_1.tryWithRetries)(() => this.sendRawTransaction(serializedTx, options), this.retryPolicy);
190
+ this.logger.info("sendSignedTransaction(): tx sent, signature: " + txResult);
191
+ return txResult;
192
+ }
193
+ /**
194
+ * Prepares (adds recent blockhash if required, applies Phantom hotfix),
195
+ * signs (all together using signAllTransactions() calls), sends (in parallel or sequentially) &
196
+ * optionally waits for confirmation of a batch of solana transactions
197
+ *
198
+ * @param signer
199
+ * @param _txs
200
+ * @param waitForConfirmation whether to wait for transaction confirmations (this also makes sure the transactions
201
+ * are re-sent at regular intervals)
202
+ * @param abortSignal abort signal to abort waiting for transaction confirmations
203
+ * @param parallel whether the send all the transaction at once in parallel or sequentially (such that transactions
204
+ * are executed in order)
205
+ * @param onBeforePublish a callback called before every transaction is published
206
+ */
207
+ async sendAndConfirm(signer, _txs, waitForConfirmation, abortSignal, parallel, onBeforePublish) {
208
+ const options = {
209
+ skipPreflight: true
210
+ };
211
+ this.logger.debug("sendAndConfirm(): sending transactions, count: " + _txs.length +
212
+ " waitForConfirmation: " + waitForConfirmation + " parallel: " + parallel);
213
+ const BATCH_SIZE = 50;
214
+ const signatures = [];
215
+ for (let e = 0; e < _txs.length; e += BATCH_SIZE) {
216
+ const txs = _txs.slice(e, e + BATCH_SIZE);
217
+ await this.prepareTransactions(signer, txs);
218
+ const signedTxs = await signer.wallet.signAllTransactions(txs.map(e => e.tx));
219
+ signedTxs.forEach((tx, index) => {
220
+ const solTx = txs[index];
221
+ tx.lastValidBlockHeight = solTx.tx.lastValidBlockHeight;
222
+ solTx.tx = tx;
223
+ });
224
+ this.logger.debug("sendAndConfirm(): sending transaction batch (" + e + ".." + (e + 50) + "), count: " + txs.length);
225
+ //For solana we are forced to send txs one-by-one even with parallel, as we cannot determine their order upfront,
226
+ // however e.g. Jito could possibly handle sending a single package of up to 5 txns in order.
227
+ for (let i = 0; i < txs.length; i++) {
228
+ const solTx = txs[i];
229
+ const signature = await this.sendSignedTransaction(solTx, options, onBeforePublish);
230
+ const confirmPromise = this.confirmTransaction(solTx, abortSignal, "confirmed");
231
+ //Don't await the last promise when !waitForConfirmation
232
+ if (i < txs.length - 1 || e + 50 < _txs.length || waitForConfirmation)
233
+ await confirmPromise;
234
+ signatures.push(signature);
235
+ }
236
+ }
237
+ this.logger.info("sendAndConfirm(): sent transactions, count: " + _txs.length +
238
+ " waitForConfirmation: " + waitForConfirmation + " parallel: " + parallel);
239
+ return signatures;
240
+ }
241
+ /**
242
+ * Serializes the solana transaction, saves the transaction, signers & last valid blockheight
243
+ *
244
+ * @param tx
245
+ */
246
+ serializeTx(tx) {
247
+ return Promise.resolve(JSON.stringify({
248
+ tx: tx.tx.serialize().toString("hex"),
249
+ signers: tx.signers.map(e => buffer_1.Buffer.from(e.secretKey).toString("hex")),
250
+ lastValidBlockheight: tx.tx.lastValidBlockHeight
251
+ }));
252
+ }
253
+ /**
254
+ * Deserializes saved solana transaction, extracting the transaction, signers & last valid blockheight
255
+ *
256
+ * @param txData
257
+ */
258
+ deserializeTx(txData) {
259
+ const jsonParsed = JSON.parse(txData);
260
+ const transaction = web3_js_1.Transaction.from(buffer_1.Buffer.from(jsonParsed.tx, "hex"));
261
+ transaction.lastValidBlockHeight = jsonParsed.lastValidBlockheight;
262
+ return Promise.resolve({
263
+ tx: transaction,
264
+ signers: jsonParsed.signers.map(e => web3_js_1.Keypair.fromSecretKey(buffer_1.Buffer.from(e, "hex"))),
265
+ });
266
+ }
267
+ /**
268
+ * Gets the status of the raw solana transaction, this also checks transaction expiry & can therefore report tx
269
+ * in "pending" status, however pending status doesn't necessarily mean that the transaction was sent (again,
270
+ * no mempool on Solana, cannot check that), this function is preferred against getTxIdStatus
271
+ *
272
+ * @param tx
273
+ */
274
+ async getTxStatus(tx) {
275
+ const parsedTx = await this.deserializeTx(tx);
276
+ const txReceipt = await this.connection.getTransaction(bs58.encode(parsedTx.tx.signature), {
277
+ commitment: "confirmed",
278
+ maxSupportedTransactionVersion: 0
279
+ });
280
+ if (txReceipt == null) {
281
+ const currentBlockheight = await this.connection.getBlockHeight("processed");
282
+ if (currentBlockheight > parsedTx.tx.lastValidBlockHeight)
283
+ return "not_found";
284
+ return "pending";
285
+ }
286
+ if (txReceipt.meta.err)
287
+ return "reverted";
288
+ return "success";
289
+ }
290
+ /**
291
+ * Gets the status of the solana transaction with a specific txId, this cannot report whether the transaction is
292
+ * "pending" because Solana has no concept of mempool & only confirmed transactions are accessible
293
+ *
294
+ * @param txId
295
+ * @param finality
296
+ */
297
+ async getTxIdStatus(txId, finality) {
298
+ const txReceipt = await this.connection.getTransaction(txId, {
299
+ commitment: finality || "confirmed",
300
+ maxSupportedTransactionVersion: 0
301
+ });
302
+ if (txReceipt == null)
303
+ return "not_found";
304
+ if (txReceipt.meta.err)
305
+ return "reverted";
306
+ return "success";
307
+ }
308
+ onBeforeTxSigned(callback) {
309
+ this.cbkBeforeTxSigned = callback;
310
+ }
311
+ offBeforeTxSigned(callback) {
312
+ this.cbkBeforeTxSigned = null;
313
+ return true;
314
+ }
315
+ onSendTransaction(callback) {
316
+ this.cbkSendTransaction = callback;
317
+ }
318
+ offSendTransaction(callback) {
319
+ this.cbkSendTransaction = null;
320
+ return true;
321
+ }
322
+ }
323
+ exports.SolanaTransactions = SolanaTransactions;