@atomiqlabs/chain-solana 10.0.0-dev.3 → 11.0.0

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