@atomiqlabs/chain-solana 13.5.13 → 13.5.14

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 (131) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +73 -73
  3. package/dist/index.d.ts +81 -81
  4. package/dist/index.js +102 -102
  5. package/dist/node/index.d.ts +9 -9
  6. package/dist/node/index.js +13 -13
  7. package/dist/solana/SolanaChainType.d.ts +15 -15
  8. package/dist/solana/SolanaChainType.js +2 -2
  9. package/dist/solana/SolanaChains.d.ts +12 -12
  10. package/dist/solana/SolanaChains.js +45 -45
  11. package/dist/solana/SolanaInitializer.d.ts +94 -94
  12. package/dist/solana/SolanaInitializer.js +174 -174
  13. package/dist/solana/btcrelay/SolanaBtcRelay.d.ts +222 -222
  14. package/dist/solana/btcrelay/SolanaBtcRelay.js +455 -455
  15. package/dist/solana/btcrelay/headers/SolanaBtcHeader.d.ts +84 -84
  16. package/dist/solana/btcrelay/headers/SolanaBtcHeader.js +70 -70
  17. package/dist/solana/btcrelay/headers/SolanaBtcStoredHeader.d.ts +92 -92
  18. package/dist/solana/btcrelay/headers/SolanaBtcStoredHeader.js +109 -109
  19. package/dist/solana/btcrelay/program/programIdl.json +671 -671
  20. package/dist/solana/chain/SolanaAction.d.ts +26 -26
  21. package/dist/solana/chain/SolanaAction.js +87 -87
  22. package/dist/solana/chain/SolanaChainInterface.d.ts +224 -224
  23. package/dist/solana/chain/SolanaChainInterface.js +275 -275
  24. package/dist/solana/chain/SolanaModule.d.ts +14 -14
  25. package/dist/solana/chain/SolanaModule.js +13 -13
  26. package/dist/solana/chain/modules/SolanaAddresses.d.ts +8 -8
  27. package/dist/solana/chain/modules/SolanaAddresses.js +22 -22
  28. package/dist/solana/chain/modules/SolanaBlocks.d.ts +32 -32
  29. package/dist/solana/chain/modules/SolanaBlocks.js +78 -78
  30. package/dist/solana/chain/modules/SolanaEvents.d.ts +68 -68
  31. package/dist/solana/chain/modules/SolanaEvents.js +238 -238
  32. package/dist/solana/chain/modules/SolanaFees.d.ts +189 -189
  33. package/dist/solana/chain/modules/SolanaFees.js +434 -434
  34. package/dist/solana/chain/modules/SolanaSignatures.d.ts +24 -24
  35. package/dist/solana/chain/modules/SolanaSignatures.js +39 -39
  36. package/dist/solana/chain/modules/SolanaSlots.d.ts +33 -33
  37. package/dist/solana/chain/modules/SolanaSlots.js +72 -72
  38. package/dist/solana/chain/modules/SolanaTokens.d.ts +123 -123
  39. package/dist/solana/chain/modules/SolanaTokens.js +242 -242
  40. package/dist/solana/chain/modules/SolanaTransactions.d.ts +149 -149
  41. package/dist/solana/chain/modules/SolanaTransactions.js +445 -445
  42. package/dist/solana/connection/ConnectionWithRetries.d.ts +35 -35
  43. package/dist/solana/connection/ConnectionWithRetries.js +86 -71
  44. package/dist/solana/events/SolanaChainEvents.d.ts +45 -45
  45. package/dist/solana/events/SolanaChainEvents.js +108 -108
  46. package/dist/solana/events/SolanaChainEventsBrowser.d.ts +205 -205
  47. package/dist/solana/events/SolanaChainEventsBrowser.js +404 -404
  48. package/dist/solana/program/SolanaProgramBase.d.ts +73 -73
  49. package/dist/solana/program/SolanaProgramBase.js +54 -54
  50. package/dist/solana/program/SolanaProgramModule.d.ts +8 -8
  51. package/dist/solana/program/SolanaProgramModule.js +11 -11
  52. package/dist/solana/program/modules/SolanaProgramEvents.d.ts +53 -53
  53. package/dist/solana/program/modules/SolanaProgramEvents.js +117 -117
  54. package/dist/solana/swaps/SolanaSwapData.d.ts +333 -333
  55. package/dist/solana/swaps/SolanaSwapData.js +535 -535
  56. package/dist/solana/swaps/SolanaSwapModule.d.ts +11 -11
  57. package/dist/solana/swaps/SolanaSwapModule.js +12 -12
  58. package/dist/solana/swaps/SolanaSwapProgram.d.ts +376 -376
  59. package/dist/solana/swaps/SolanaSwapProgram.js +769 -769
  60. package/dist/solana/swaps/SwapTypeEnum.d.ts +11 -11
  61. package/dist/solana/swaps/SwapTypeEnum.js +43 -43
  62. package/dist/solana/swaps/modules/SolanaDataAccount.d.ts +95 -95
  63. package/dist/solana/swaps/modules/SolanaDataAccount.js +232 -232
  64. package/dist/solana/swaps/modules/SolanaLpVault.d.ts +69 -69
  65. package/dist/solana/swaps/modules/SolanaLpVault.js +171 -171
  66. package/dist/solana/swaps/modules/SwapClaim.d.ts +126 -126
  67. package/dist/solana/swaps/modules/SwapClaim.js +294 -294
  68. package/dist/solana/swaps/modules/SwapInit.d.ts +213 -213
  69. package/dist/solana/swaps/modules/SwapInit.js +658 -658
  70. package/dist/solana/swaps/modules/SwapRefund.d.ts +87 -87
  71. package/dist/solana/swaps/modules/SwapRefund.js +293 -293
  72. package/dist/solana/swaps/programIdl.json +945 -945
  73. package/dist/solana/swaps/programTypes.d.ts +943 -943
  74. package/dist/solana/swaps/programTypes.js +945 -945
  75. package/dist/solana/swaps/v1/programIdl.json +945 -945
  76. package/dist/solana/swaps/v1/programTypes.d.ts +943 -943
  77. package/dist/solana/swaps/v1/programTypes.js +945 -945
  78. package/dist/solana/swaps/v2/programIdl.json +952 -952
  79. package/dist/solana/swaps/v2/programTypes.d.ts +950 -950
  80. package/dist/solana/swaps/v2/programTypes.js +952 -952
  81. package/dist/solana/wallet/SolanaKeypairWallet.d.ts +29 -29
  82. package/dist/solana/wallet/SolanaKeypairWallet.js +50 -50
  83. package/dist/solana/wallet/SolanaSigner.d.ts +30 -30
  84. package/dist/solana/wallet/SolanaSigner.js +30 -30
  85. package/dist/utils/Utils.d.ts +58 -58
  86. package/dist/utils/Utils.js +170 -170
  87. package/node/index.d.ts +1 -1
  88. package/node/index.js +3 -3
  89. package/package.json +46 -46
  90. package/src/index.ts +87 -87
  91. package/src/node/index.ts +9 -9
  92. package/src/solana/SolanaChainType.ts +32 -32
  93. package/src/solana/SolanaChains.ts +46 -46
  94. package/src/solana/SolanaInitializer.ts +278 -278
  95. package/src/solana/btcrelay/SolanaBtcRelay.ts +615 -615
  96. package/src/solana/btcrelay/headers/SolanaBtcHeader.ts +116 -116
  97. package/src/solana/btcrelay/headers/SolanaBtcStoredHeader.ts +148 -148
  98. package/src/solana/btcrelay/program/programIdl.json +670 -670
  99. package/src/solana/chain/SolanaAction.ts +109 -109
  100. package/src/solana/chain/SolanaChainInterface.ts +404 -404
  101. package/src/solana/chain/SolanaModule.ts +20 -20
  102. package/src/solana/chain/modules/SolanaAddresses.ts +20 -20
  103. package/src/solana/chain/modules/SolanaBlocks.ts +89 -89
  104. package/src/solana/chain/modules/SolanaEvents.ts +271 -271
  105. package/src/solana/chain/modules/SolanaFees.ts +522 -522
  106. package/src/solana/chain/modules/SolanaSignatures.ts +39 -39
  107. package/src/solana/chain/modules/SolanaSlots.ts +85 -85
  108. package/src/solana/chain/modules/SolanaTokens.ts +300 -300
  109. package/src/solana/chain/modules/SolanaTransactions.ts +503 -503
  110. package/src/solana/connection/ConnectionWithRetries.ts +113 -96
  111. package/src/solana/events/SolanaChainEvents.ts +127 -127
  112. package/src/solana/events/SolanaChainEventsBrowser.ts +495 -495
  113. package/src/solana/program/SolanaProgramBase.ts +119 -119
  114. package/src/solana/program/SolanaProgramModule.ts +15 -15
  115. package/src/solana/program/modules/SolanaProgramEvents.ts +157 -157
  116. package/src/solana/swaps/SolanaSwapData.ts +735 -735
  117. package/src/solana/swaps/SolanaSwapModule.ts +19 -19
  118. package/src/solana/swaps/SolanaSwapProgram.ts +1074 -1074
  119. package/src/solana/swaps/SwapTypeEnum.ts +30 -30
  120. package/src/solana/swaps/modules/SolanaDataAccount.ts +302 -302
  121. package/src/solana/swaps/modules/SolanaLpVault.ts +208 -208
  122. package/src/solana/swaps/modules/SwapClaim.ts +387 -387
  123. package/src/solana/swaps/modules/SwapInit.ts +785 -785
  124. package/src/solana/swaps/modules/SwapRefund.ts +353 -353
  125. package/src/solana/swaps/v1/programIdl.json +944 -944
  126. package/src/solana/swaps/v1/programTypes.ts +1885 -1885
  127. package/src/solana/swaps/v2/programIdl.json +951 -951
  128. package/src/solana/swaps/v2/programTypes.ts +1899 -1899
  129. package/src/solana/wallet/SolanaKeypairWallet.ts +56 -56
  130. package/src/solana/wallet/SolanaSigner.ts +43 -43
  131. package/src/utils/Utils.ts +194 -194
@@ -1,658 +1,658 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SwapInit = void 0;
4
- const web3_js_1 = require("@solana/web3.js");
5
- const base_1 = require("@atomiqlabs/base");
6
- const SolanaAction_1 = require("../../chain/SolanaAction");
7
- const spl_token_1 = require("@solana/spl-token");
8
- const SolanaSwapModule_1 = require("../SolanaSwapModule");
9
- const Utils_1 = require("../../../utils/Utils");
10
- const buffer_1 = require("buffer");
11
- const SolanaTokens_1 = require("../../chain/modules/SolanaTokens");
12
- const SolanaSwapProgram_1 = require("../SolanaSwapProgram");
13
- const BN = require("bn.js");
14
- class SwapInit extends SolanaSwapModule_1.SolanaSwapModule {
15
- constructor() {
16
- super(...arguments);
17
- this.SIGNATURE_SLOT_BUFFER = 20;
18
- this.SIGNATURE_PREFETCH_DATA_VALIDITY = 5000;
19
- }
20
- /**
21
- * bare Init action based on the data passed in swapData
22
- *
23
- * @param sender
24
- * @param swapData
25
- * @param timeout
26
- * @private
27
- */
28
- async Init(sender, swapData, timeout) {
29
- const claimerAta = (0, spl_token_1.getAssociatedTokenAddressSync)(swapData.token, swapData.claimer);
30
- const paymentHash = buffer_1.Buffer.from(swapData.paymentHash, "hex");
31
- const accounts = {
32
- initializer: sender,
33
- claimer: swapData.claimer,
34
- offerer: swapData.offerer,
35
- escrowState: this.program._SwapEscrowState(paymentHash),
36
- mint: swapData.token,
37
- systemProgram: web3_js_1.SystemProgram.programId,
38
- claimerAta: swapData.payOut ? claimerAta : null,
39
- claimerUserData: !swapData.payOut ? this.program._SwapUserVault(swapData.claimer, swapData.token) : null
40
- };
41
- if (swapData.payIn) {
42
- const ata = (0, spl_token_1.getAssociatedTokenAddressSync)(swapData.token, swapData.offerer);
43
- let instruction;
44
- const program = this.swapProgram;
45
- if ((0, SolanaSwapProgram_1.isSwapProgramV1)(program)) {
46
- if (!swapData.securityDeposit.eq(new BN(0)))
47
- throw new Error("Swap data for V1 payIn=true swaps cannot have any security deposit!");
48
- if (!swapData.claimerBounty.eq(new BN(0)))
49
- throw new Error("Swap data for V1 payIn=true swaps cannot have any claimer bounty!");
50
- instruction = await program.methods
51
- .offererInitializePayIn(swapData.toSwapDataStruct(), [...buffer_1.Buffer.alloc(32, 0)], (0, Utils_1.toBN)(timeout))
52
- .accounts({
53
- ...accounts,
54
- offererAta: ata,
55
- vault: this.program._SwapVault(swapData.token),
56
- vaultAuthority: this.program._SwapVaultAuthority,
57
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
58
- })
59
- .instruction();
60
- }
61
- else if ((0, SolanaSwapProgram_1.isSwapProgramV2)(program)) {
62
- instruction = await program.methods
63
- .offererInitializePayIn(swapData.toSwapDataStruct(), swapData.securityDeposit, swapData.claimerBounty, [...(swapData.txoHash != null ? buffer_1.Buffer.from(swapData.txoHash, "hex") : buffer_1.Buffer.alloc(32, 0))], (0, Utils_1.toBN)(timeout))
64
- .accounts({
65
- ...accounts,
66
- offererAta: ata,
67
- vault: this.program._SwapVault(swapData.token),
68
- vaultAuthority: this.program._SwapVaultAuthority,
69
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
70
- })
71
- .instruction();
72
- // Mark the claimer as signer for non payOut swaps
73
- if (!swapData.isPayOut()) {
74
- instruction.keys.forEach(key => {
75
- if (key.pubkey.equals(swapData.claimer))
76
- key.isSigner = true;
77
- });
78
- }
79
- }
80
- else
81
- throw new Error("Invalid swap program version!");
82
- return new SolanaAction_1.SolanaAction(sender, this.root, instruction, SwapInit.CUCosts.INIT_PAY_IN);
83
- }
84
- else {
85
- const instruction = await this.swapProgram.methods
86
- .offererInitialize(swapData.toSwapDataStruct(), swapData.securityDeposit, swapData.claimerBounty, [...(swapData.txoHash != null ? buffer_1.Buffer.from(swapData.txoHash, "hex") : buffer_1.Buffer.alloc(32, 0))], (0, Utils_1.toBN)(timeout))
87
- .accounts({
88
- ...accounts,
89
- offererUserData: this.program._SwapUserVault(swapData.offerer, swapData.token),
90
- })
91
- .instruction();
92
- // Mark the claimer as signer for non payOut swaps
93
- if ((0, SolanaSwapProgram_1.isSwapProgramV2)(this.swapProgram) && !swapData.isPayOut()) {
94
- instruction.keys.forEach(key => {
95
- if (key.pubkey.equals(swapData.claimer))
96
- key.isSigner = true;
97
- });
98
- }
99
- return new SolanaAction_1.SolanaAction(sender, this.root, instruction, SwapInit.CUCosts.INIT);
100
- }
101
- }
102
- /**
103
- * InitPayIn action which includes SOL to WSOL wrapping if indicated by the fee rate
104
- *
105
- * @param signer
106
- * @param swapData
107
- * @param timeout
108
- * @param feeRate
109
- * @private
110
- */
111
- async InitPayIn(sender, swapData, timeout, feeRate) {
112
- if (!swapData.isPayIn())
113
- throw new Error("Must be payIn==true");
114
- if ((0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram)) {
115
- if (!sender.equals(swapData.offerer))
116
- throw new Error("Transaction signer must be offerer for payIn=true escrows!");
117
- }
118
- else {
119
- if (!sender.equals(swapData.offerer) && !sender.equals(swapData.claimer))
120
- throw new Error("Transaction signer must be either offerer or claimer claimer!");
121
- }
122
- const action = new SolanaAction_1.SolanaAction(sender, this.root);
123
- if (this.shouldWrapOnInit(swapData, feeRate))
124
- action.addAction(this.Wrap(swapData, feeRate), undefined, true);
125
- action.addAction(await this.Init(sender, swapData, timeout));
126
- return action;
127
- }
128
- /**
129
- * InitNotPayIn action with additional createAssociatedTokenAccountIdempotentInstruction instruction, such that
130
- * a recipient ATA is created if it doesn't exist
131
- *
132
- * @param sender
133
- * @param swapData
134
- * @param timeout
135
- * @private
136
- */
137
- async InitNotPayIn(sender, swapData, timeout) {
138
- if (swapData.isPayIn())
139
- throw new Error("Must be payIn==false");
140
- if ((0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram)) {
141
- if (!sender.equals(swapData.claimer))
142
- throw new Error("Transaction signer must be claimer for payIn=false escrows!");
143
- }
144
- else {
145
- if (!sender.equals(swapData.offerer) && !sender.equals(swapData.claimer))
146
- throw new Error("Transaction signer must be either offerer or claimer claimer!");
147
- }
148
- const action = new SolanaAction_1.SolanaAction(sender, this.root);
149
- if ((0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram)) {
150
- action.addIx((0, spl_token_1.createAssociatedTokenAccountIdempotentInstruction)(sender, swapData.claimerAta ?? await (0, spl_token_1.getAssociatedTokenAddress)(swapData.token, swapData.claimer), swapData.claimer, swapData.token));
151
- } // V2 doesn't explicitly check the token account on initialization, no need to open it
152
- action.addAction(await this.Init(sender, swapData, timeout));
153
- return action;
154
- }
155
- Wrap(swapData, feeRate) {
156
- const data = this.extractAtaDataFromFeeRate(feeRate);
157
- if (feeRate == null || data == null)
158
- throw new Error("Tried to add wrap instruction, but feeRate malformed: " + feeRate);
159
- return this.root.Tokens.Wrap(swapData.offerer, swapData.getAmount() - data.balance, data.initAta);
160
- }
161
- /**
162
- * Extracts data about SOL to WSOL wrapping from the fee rate, fee rate is used to convey this information from
163
- * the user to the intermediary, such that the intermediary creates valid signature for transaction including
164
- * the SOL to WSOL wrapping instructions
165
- *
166
- * @param feeRate
167
- * @private
168
- */
169
- extractAtaDataFromFeeRate(feeRate) {
170
- const hashArr = feeRate == null ? [] : feeRate.split("#");
171
- if (hashArr.length <= 1)
172
- return null;
173
- const arr = hashArr[1].split(";");
174
- if (arr.length <= 1)
175
- return null;
176
- return {
177
- balance: BigInt(arr[1]),
178
- initAta: arr[0] === "1"
179
- };
180
- }
181
- /**
182
- * Checks whether a wrap instruction (SOL -> WSOL) should be a part of the signed init message
183
- *
184
- * @param swapData
185
- * @param feeRate
186
- * @private
187
- * @returns {boolean} returns true if wrap instruction should be added
188
- */
189
- shouldWrapOnInit(swapData, feeRate) {
190
- const data = this.extractAtaDataFromFeeRate(feeRate);
191
- if (data == null)
192
- return false;
193
- return data.balance < swapData.getAmount();
194
- }
195
- /**
196
- * Returns the transaction to be signed as an initialization signature from the intermediary, also adds
197
- * SOL to WSOL wrapping if indicated by the fee rate
198
- *
199
- * @param swapData
200
- * @param timeout
201
- * @param feeRate
202
- * @private
203
- */
204
- async getTxToSign(signer, swapData, timeout, feeRate) {
205
- let txSender;
206
- if (signer.equals(swapData.offerer)) {
207
- txSender = swapData.claimer;
208
- }
209
- else if (signer.equals(swapData.claimer)) {
210
- txSender = swapData.offerer;
211
- }
212
- else
213
- throw new Error("Signer needs to be either claimer or offerer of the swap!");
214
- const action = swapData.isPayIn() ?
215
- await this.InitPayIn(txSender, swapData, BigInt(timeout), feeRate) :
216
- await this.InitNotPayIn(txSender, swapData, BigInt(timeout));
217
- const tx = (await action.tx(feeRate)).tx;
218
- return tx;
219
- }
220
- /**
221
- * Returns auth prefix to be used with a specific swap, payIn=true & payIn=false use different prefixes (these
222
- * actually have no meaning for the smart contract/solana program in the Solana case)
223
- *
224
- * @param swapData
225
- * @private
226
- */
227
- getAuthPrefix(swapData) {
228
- return swapData.isPayIn() ? "claim_initialize" : "initialize";
229
- }
230
- /**
231
- * Returns "processed" slot required for signature validation, uses preFetchedData if provided & valid
232
- *
233
- * @param preFetchedData
234
- * @private
235
- */
236
- getSlotForSignature(preFetchedData) {
237
- if (preFetchedData != null &&
238
- preFetchedData.latestSlot != null &&
239
- preFetchedData.latestSlot.timestamp > Date.now() - this.root.Slots.SLOT_CACHE_TIME) {
240
- const estimatedSlotsPassed = Math.floor((Date.now() - preFetchedData.latestSlot.timestamp) / this.root._SLOT_TIME);
241
- const estimatedCurrentSlot = preFetchedData.latestSlot.slot + estimatedSlotsPassed;
242
- this.logger.debug("getSlotForSignature(): slot: " + preFetchedData.latestSlot.slot +
243
- " estimated passed slots: " + estimatedSlotsPassed + " estimated current slot: " + estimatedCurrentSlot);
244
- return Promise.resolve(estimatedCurrentSlot);
245
- }
246
- return this.root.Slots.getSlot("processed");
247
- }
248
- /**
249
- * Returns blockhash required for signature validation, uses preFetchedData if provided & valid
250
- *
251
- * @param txSlot
252
- * @param preFetchedData
253
- * @private
254
- */
255
- getBlockhashForSignature(txSlot, preFetchedData) {
256
- if (preFetchedData != null &&
257
- preFetchedData.transactionSlot != null &&
258
- preFetchedData.transactionSlot.slot === txSlot) {
259
- return Promise.resolve(preFetchedData.transactionSlot.blockhash);
260
- }
261
- return this.root.Blocks.getParsedBlock(txSlot).then(val => val.blockhash);
262
- }
263
- /**
264
- * Pre-fetches slot & block based on priorly received SolanaPreFetchData, such that it can later be used
265
- * by signature verification
266
- *
267
- * @param data
268
- */
269
- async preFetchForInitSignatureVerification(data) {
270
- const [latestSlot, txBlock] = await Promise.all([
271
- this.root.Slots.getSlotAndTimestamp("processed"),
272
- this.root.Blocks.getParsedBlock(data.slot)
273
- ]);
274
- return {
275
- latestSlot,
276
- transactionSlot: {
277
- slot: data.slot,
278
- blockhash: txBlock.blockhash
279
- }
280
- };
281
- }
282
- /**
283
- * Pre-fetches block data required for signing the init message by the LP, this can happen in parallel before
284
- * signing takes place making the quoting quicker
285
- */
286
- async preFetchBlockDataForSignatures() {
287
- const latestParsedBlock = await this.root.Blocks.findLatestParsedBlock("finalized");
288
- return {
289
- block: latestParsedBlock.block,
290
- slot: latestParsedBlock.slot,
291
- timestamp: Date.now()
292
- };
293
- }
294
- /**
295
- * Signs swap initialization authorization, using data from preFetchedBlockData if provided & still valid (subject
296
- * to SIGNATURE_PREFETCH_DATA_VALIDITY)
297
- *
298
- * @param signer
299
- * @param swapData
300
- * @param authorizationTimeout
301
- * @param feeRate
302
- * @param preFetchedBlockData
303
- * @public
304
- */
305
- async signSwapInitialization(signer, swapData, authorizationTimeout, preFetchedBlockData, feeRate) {
306
- if (signer.keypair == null)
307
- throw new Error("Unsupported");
308
- if ((0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram)) {
309
- if (!signer.getPublicKey().equals(swapData.isPayIn() ? swapData.claimer : swapData.offerer))
310
- throw new Error("Invalid signer, wrong public key!");
311
- }
312
- else {
313
- if (!signer.getPublicKey().equals(swapData.offerer) && !signer.getPublicKey().equals(swapData.claimer))
314
- throw new Error("Invalid signer, must be either offerer or claimer claimer!");
315
- }
316
- if (preFetchedBlockData != null && Date.now() - preFetchedBlockData.timestamp > this.SIGNATURE_PREFETCH_DATA_VALIDITY)
317
- preFetchedBlockData = undefined;
318
- const { block: latestBlock, slot: latestSlot } = preFetchedBlockData || await this.root.Blocks.findLatestParsedBlock("finalized");
319
- const authTimeout = Math.floor(Date.now() / 1000) + authorizationTimeout;
320
- const txToSign = await this.getTxToSign(signer.getPublicKey(), swapData, authTimeout.toString(10), feeRate);
321
- txToSign.feePayer = signer.getPublicKey().equals(swapData.offerer) ? swapData.claimer : swapData.offerer;
322
- txToSign.recentBlockhash = latestBlock.blockhash;
323
- txToSign.sign(signer.keypair);
324
- // this.logger.debug("signSwapInitialization(): Signed tx: ",txToSign);
325
- const sig = txToSign.signatures.find(e => e.publicKey.equals(signer.getPublicKey()));
326
- if (sig == null || sig.signature == null)
327
- throw new Error(`Unable to extract transaction signature! Signer: ${signer.getAddress()}`);
328
- return {
329
- prefix: this.getAuthPrefix(swapData),
330
- timeout: authTimeout.toString(10),
331
- signature: latestSlot + ";" + sig.signature.toString("hex")
332
- };
333
- }
334
- /**
335
- * Checks whether the provided signature data is valid, using preFetchedData if provided and still valid
336
- *
337
- * @param sender
338
- * @param swapData
339
- * @param timeout
340
- * @param prefix
341
- * @param signature
342
- * @param feeRate
343
- * @param preFetchedData
344
- * @public
345
- */
346
- async isSignatureValid(sender, swapData, timeout, prefix, signature, feeRate, preFetchedData) {
347
- if ((0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram)) {
348
- if (swapData.isPayIn()) {
349
- if (!swapData.offerer.equals(sender))
350
- throw new base_1.SignatureVerificationError("Sender needs to be offerer in payIn=true swaps");
351
- }
352
- else {
353
- if (!swapData.claimer.equals(sender))
354
- throw new base_1.SignatureVerificationError("Sender needs to be claimer in payIn=false swaps");
355
- }
356
- }
357
- let signer;
358
- if (sender.equals(swapData.offerer)) {
359
- signer = swapData.claimer;
360
- }
361
- else if (sender.equals(swapData.claimer)) {
362
- signer = swapData.offerer;
363
- }
364
- else
365
- throw new Error("Signer needs to be either claimer or offerer of the swap!");
366
- if (!swapData.isPayIn() && await this.program.isExpired(sender.toString(), swapData)) {
367
- throw new base_1.SignatureVerificationError("Swap will expire too soon!");
368
- }
369
- if (prefix !== this.getAuthPrefix(swapData))
370
- throw new base_1.SignatureVerificationError("Invalid prefix");
371
- const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
372
- const isExpired = (BigInt(timeout) - currentTimestamp) < BigInt(this.program._authGracePeriod);
373
- if (isExpired)
374
- throw new base_1.SignatureVerificationError("Authorization expired!");
375
- const requiresCounterpartySignature = (0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram) || !swapData.isPayOut() || sender.equals(swapData.claimer);
376
- if (requiresCounterpartySignature) {
377
- if (signature == null)
378
- throw new base_1.SignatureVerificationError("Counterparty signature is required to initiate the swap!");
379
- const [transactionSlot, signatureString] = signature.split(";");
380
- const txSlot = parseInt(transactionSlot);
381
- const [latestSlot, blockhash] = await Promise.all([
382
- this.getSlotForSignature(preFetchedData),
383
- this.getBlockhashForSignature(txSlot, preFetchedData)
384
- ]);
385
- const lastValidTransactionSlot = txSlot + this.root._TX_SLOT_VALIDITY;
386
- const slotsLeft = lastValidTransactionSlot - latestSlot - this.SIGNATURE_SLOT_BUFFER;
387
- if (slotsLeft < 0)
388
- throw new base_1.SignatureVerificationError("Authorization expired!");
389
- const txToSign = await this.getTxToSign(signer, swapData, timeout, feeRate);
390
- txToSign.feePayer = sender;
391
- txToSign.recentBlockhash = blockhash;
392
- txToSign.addSignature(signer, buffer_1.Buffer.from(signatureString, "hex"));
393
- // this.logger.debug("isSignatureValid(): Signed tx: ",txToSign);
394
- const valid = txToSign.verifySignatures(false);
395
- if (!valid)
396
- throw new base_1.SignatureVerificationError("Invalid signature!");
397
- return buffer_1.Buffer.from(blockhash);
398
- }
399
- return buffer_1.Buffer.alloc(32, 0);
400
- }
401
- /**
402
- * Gets expiry of the provided signature data, this is a minimum of slot expiry & swap signature expiry
403
- *
404
- * @param timeout
405
- * @param signature
406
- * @param preFetchedData
407
- * @public
408
- */
409
- async getSignatureExpiry(timeout, signature, preFetchedData) {
410
- let expiry = (parseInt(timeout) - this.program._authGracePeriod) * 1000;
411
- if (signature != null) {
412
- const [transactionSlotStr, signatureString] = signature.split(";");
413
- const txSlot = parseInt(transactionSlotStr);
414
- const latestSlot = await this.getSlotForSignature(preFetchedData);
415
- const lastValidTransactionSlot = txSlot + this.root._TX_SLOT_VALIDITY;
416
- const slotsLeft = lastValidTransactionSlot - latestSlot - this.SIGNATURE_SLOT_BUFFER;
417
- const slotExpiryTime = Date.now() + (slotsLeft * this.root._SLOT_TIME);
418
- if (slotExpiryTime < expiry)
419
- expiry = slotExpiryTime;
420
- }
421
- if (expiry < Date.now())
422
- return 0;
423
- return expiry;
424
- }
425
- /**
426
- * Checks whether signature is expired for good (uses "finalized" slot)
427
- *
428
- * @param signature
429
- * @param timeout
430
- * @public
431
- */
432
- async isSignatureExpired(signature, timeout) {
433
- if (signature != null) {
434
- const [transactionSlotStr, signatureString] = signature.split(";");
435
- const txSlot = parseInt(transactionSlotStr);
436
- const lastValidTransactionSlot = txSlot + this.root._TX_SLOT_VALIDITY;
437
- const latestSlot = await this.root.Slots.getSlot("finalized");
438
- const slotsLeft = lastValidTransactionSlot - latestSlot + this.SIGNATURE_SLOT_BUFFER;
439
- if (slotsLeft < 0)
440
- return true;
441
- }
442
- if ((parseInt(timeout) + this.program._authGracePeriod) * 1000 < Date.now())
443
- return true;
444
- return false;
445
- }
446
- /**
447
- * Creates init transaction (InitPayIn) with a valid signature from an LP, also adds a SOL to WSOL wrapping ix to
448
- * the init transaction (if indicated by the fee rate) or adds the wrapping in a separate transaction (if no
449
- * indication in the fee rate)
450
- *
451
- * @param sender
452
- * @param swapData swap to initialize
453
- * @param timeout init signature timeout
454
- * @param prefix init signature prefix
455
- * @param signature init signature
456
- * @param skipChecks whether to skip signature validity checks
457
- * @param feeRate fee rate to use for the transaction
458
- */
459
- async txsInitPayIn(sender, swapData, timeout, prefix, signature, skipChecks, feeRate) {
460
- if ((0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram)) {
461
- if (!sender.equals(swapData.offerer))
462
- throw new Error("Transaction sender has to be the offerer!");
463
- }
464
- let signer;
465
- if (sender.equals(swapData.offerer)) {
466
- signer = swapData.claimer;
467
- }
468
- else if (sender.equals(swapData.claimer)) {
469
- signer = swapData.offerer;
470
- }
471
- else
472
- throw new Error("Signer needs to be either claimer or offerer of the swap!");
473
- if (swapData.offererAta == undefined)
474
- throw new base_1.SwapDataVerificationError("No offererAta specified for payIn swap!");
475
- const offererAta = swapData.offererAta;
476
- const requiresCounterpartySignature = (0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram) || !swapData.isPayOut() || sender.equals(swapData.claimer);
477
- if (!skipChecks) {
478
- const [_, payStatus] = await Promise.all([
479
- requiresCounterpartySignature ? this.isSignatureValid(sender, swapData, timeout, prefix, signature, feeRate) : Promise.resolve(),
480
- this.program.getClaimHashStatus(swapData.getClaimHash())
481
- ]);
482
- if (payStatus !== base_1.SwapCommitStateType.NOT_COMMITED)
483
- throw new base_1.SwapDataVerificationError("Invoice already being paid for or paid");
484
- }
485
- let block;
486
- if (requiresCounterpartySignature) {
487
- const slotNumber = signature.split(";")[0];
488
- block = await (0, Utils_1.tryWithRetries)(() => this.root.Blocks.getParsedBlock(parseInt(slotNumber)), { maxRetries: 3, delay: 100, exponential: true });
489
- }
490
- const txs = [];
491
- let isWrapping = false;
492
- const isWrappedInSignedTx = feeRate != null && feeRate.split("#").length > 1;
493
- if (!isWrappedInSignedTx && swapData.token.equals(SolanaTokens_1.SolanaTokens.WSOL_ADDRESS)) {
494
- const ataAcc = await this.root.Tokens.getATAOrNull(offererAta);
495
- const balance = ataAcc?.amount ?? 0n;
496
- if (balance < swapData.getAmount()) {
497
- if (!swapData.offerer.equals(sender))
498
- throw new Error("Additional SOL needs to be wrapped but the sender is not offerer!");
499
- //Need to wrap more SOL to WSOL
500
- await this.root.Tokens.Wrap(swapData.offerer, swapData.getAmount() - balance, ataAcc == null)
501
- .addToTxs(txs, feeRate, block);
502
- isWrapping = true;
503
- }
504
- }
505
- const initTx = await (await this.InitPayIn(sender, swapData, BigInt(timeout), feeRate)).tx(feeRate, block);
506
- if (requiresCounterpartySignature)
507
- initTx.tx.addSignature(signer, buffer_1.Buffer.from(signature.split(";")[1], "hex"));
508
- txs.push(initTx);
509
- this.logger.debug("txsInitPayIn(): create swap init TX, swap: " + swapData.getClaimHash() +
510
- " wrapping client-side: " + isWrapping + " feerate: " + feeRate);
511
- return txs;
512
- }
513
- /**
514
- * Creates init transactions (InitNotPayIn) with a valid signature from an intermediary
515
- *
516
- * @param sender
517
- * @param swapData swap to initialize
518
- * @param timeout init signature timeout
519
- * @param prefix init signature prefix
520
- * @param signature init signature
521
- * @param skipChecks whether to skip signature validity checks
522
- * @param feeRate fee rate to use for the transaction
523
- */
524
- async txsInit(sender, swapData, timeout, prefix, signature, skipChecks, feeRate) {
525
- if ((0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram)) {
526
- if (!sender.equals(swapData.claimer))
527
- throw new Error("Transaction sender has to be the claimer!");
528
- }
529
- let signer;
530
- if (sender.equals(swapData.offerer)) {
531
- signer = swapData.claimer;
532
- }
533
- else if (sender.equals(swapData.claimer)) {
534
- signer = swapData.offerer;
535
- }
536
- else
537
- throw new Error("Signer needs to be either claimer or offerer of the swap!");
538
- const requiresCounterpartySignature = (0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram) || !swapData.isPayOut() || sender.equals(swapData.claimer);
539
- let block;
540
- if (requiresCounterpartySignature) {
541
- if (!skipChecks) {
542
- await this.isSignatureValid(sender, swapData, timeout, prefix, signature, feeRate);
543
- }
544
- const slotNumber = signature.split(";")[0];
545
- block = await (0, Utils_1.tryWithRetries)(() => this.root.Blocks.getParsedBlock(parseInt(slotNumber)), { maxRetries: 3, delay: 100, exponential: true });
546
- }
547
- const initTx = await (await this.InitNotPayIn(sender, swapData, BigInt(timeout))).tx(feeRate, block);
548
- if (requiresCounterpartySignature)
549
- initTx.tx.addSignature(signer, buffer_1.Buffer.from(signature.split(";")[1], "hex"));
550
- this.logger.debug("txsInit(): create swap init TX, swap: " + swapData.getClaimHash() + " feerate: " + feeRate);
551
- return [initTx];
552
- }
553
- /**
554
- * Returns the fee rate to be used for a specific init transaction, also adding indication whether the WSOL ATA
555
- * should be initialized in the init transaction and/or current balance in the WSOL ATA
556
- *
557
- * @param offerer
558
- * @param claimer
559
- * @param token
560
- * @param paymentHash
561
- */
562
- async getInitPayInFeeRate(offerer, claimer, token, paymentHash) {
563
- const accounts = [];
564
- if (offerer != null)
565
- accounts.push(offerer);
566
- if (token != null) {
567
- accounts.push(this.program._SwapVault(token));
568
- if (offerer != null)
569
- accounts.push((0, spl_token_1.getAssociatedTokenAddressSync)(token, offerer));
570
- if (claimer != null)
571
- accounts.push(this.program._SwapUserVault(claimer, token));
572
- }
573
- if (paymentHash != null)
574
- accounts.push(this.program._SwapEscrowState(buffer_1.Buffer.from(paymentHash, "hex")));
575
- const shouldCheckWSOLAta = token != null && offerer != null && token.equals(SolanaTokens_1.SolanaTokens.WSOL_ADDRESS);
576
- let [feeRate, account] = await Promise.all([
577
- this.root.Fees.getFeeRate(accounts),
578
- shouldCheckWSOLAta ?
579
- this.root.Tokens.getATAOrNull((0, spl_token_1.getAssociatedTokenAddressSync)(token, offerer)) :
580
- Promise.resolve(null)
581
- ]);
582
- if (shouldCheckWSOLAta) {
583
- const balance = account?.amount ?? 0n;
584
- //Add an indication about whether the ATA is initialized & balance it contains
585
- feeRate += "#" + (account != null ? "0" : "1") + ";" + balance.toString(10);
586
- }
587
- this.logger.debug("getInitPayInFeeRate(): feerate computed: " + feeRate);
588
- return feeRate;
589
- }
590
- /**
591
- * Returns the fee rate to be used for a specific init transaction
592
- *
593
- * @param offerer
594
- * @param claimer
595
- * @param token
596
- * @param paymentHash
597
- */
598
- getInitFeeRate(offerer, claimer, token, paymentHash) {
599
- const accounts = [];
600
- if (offerer != null && token != null)
601
- accounts.push(this.program._SwapUserVault(offerer, token));
602
- if (claimer != null)
603
- accounts.push(claimer);
604
- if (paymentHash != null)
605
- accounts.push(this.program._SwapEscrowState(buffer_1.Buffer.from(paymentHash, "hex")));
606
- return this.root.Fees.getFeeRate(accounts);
607
- }
608
- /**
609
- * Get the estimated solana fee of the init transaction, this includes the required deposit for creating swap PDA
610
- * and also deposit for ATAs
611
- */
612
- async getInitFee(swapData, feeRate) {
613
- if (swapData == null)
614
- return BigInt(this.program.ESCROW_STATE_RENT_EXEMPT) + await this.getRawInitFee(swapData, feeRate);
615
- feeRate = feeRate ||
616
- (swapData.payIn
617
- ? await this.getInitPayInFeeRate(swapData.offerer, swapData.claimer, swapData.token, swapData.paymentHash)
618
- : await this.getInitFeeRate(swapData.offerer, swapData.claimer, swapData.token, swapData.paymentHash));
619
- const [rawFee, initAta] = await Promise.all([
620
- this.getRawInitFee(swapData, feeRate),
621
- (0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram) && swapData != null && swapData.payOut ?
622
- this.root.Tokens.getATAOrNull((0, spl_token_1.getAssociatedTokenAddressSync)(swapData.token, swapData.claimer)).then(acc => acc == null) :
623
- Promise.resolve(null)
624
- ]);
625
- let resultingFee = BigInt(this.program.ESCROW_STATE_RENT_EXEMPT) + rawFee;
626
- if (initAta)
627
- resultingFee += BigInt(SolanaTokens_1.SolanaTokens.SPL_ATA_RENT_EXEMPT);
628
- if (swapData.payIn && this.shouldWrapOnInit(swapData, feeRate) && this.extractAtaDataFromFeeRate(feeRate).initAta) {
629
- resultingFee += BigInt(SolanaTokens_1.SolanaTokens.SPL_ATA_RENT_EXEMPT);
630
- }
631
- return resultingFee;
632
- }
633
- /**
634
- * Get the estimated solana fee of the init transaction, without the required deposit for creating swap PDA
635
- */
636
- async getRawInitFee(swapData, feeRate) {
637
- if (swapData == null)
638
- return 10000n;
639
- feeRate = feeRate ??
640
- (swapData.payIn
641
- ? await this.getInitPayInFeeRate(swapData.offerer, swapData.claimer, swapData.token, swapData.paymentHash)
642
- : await this.getInitFeeRate(swapData.offerer, swapData.claimer, swapData.token, swapData.paymentHash));
643
- let computeBudget = swapData.payIn ? SwapInit.CUCosts.INIT_PAY_IN : SwapInit.CUCosts.INIT;
644
- if (swapData.payIn && this.shouldWrapOnInit(swapData, feeRate)) {
645
- computeBudget += SolanaTokens_1.SolanaTokens.CUCosts.WRAP_SOL;
646
- const data = this.extractAtaDataFromFeeRate(feeRate);
647
- if (data.initAta)
648
- computeBudget += SolanaTokens_1.SolanaTokens.CUCosts.ATA_INIT;
649
- }
650
- const baseFee = swapData.payIn ? 10000n : 10000n + 5000n;
651
- return baseFee + this.root.Fees.getPriorityFee(computeBudget, feeRate);
652
- }
653
- }
654
- exports.SwapInit = SwapInit;
655
- SwapInit.CUCosts = {
656
- INIT: 90000,
657
- INIT_PAY_IN: 50000,
658
- };
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SwapInit = void 0;
4
+ const web3_js_1 = require("@solana/web3.js");
5
+ const base_1 = require("@atomiqlabs/base");
6
+ const SolanaAction_1 = require("../../chain/SolanaAction");
7
+ const spl_token_1 = require("@solana/spl-token");
8
+ const SolanaSwapModule_1 = require("../SolanaSwapModule");
9
+ const Utils_1 = require("../../../utils/Utils");
10
+ const buffer_1 = require("buffer");
11
+ const SolanaTokens_1 = require("../../chain/modules/SolanaTokens");
12
+ const SolanaSwapProgram_1 = require("../SolanaSwapProgram");
13
+ const BN = require("bn.js");
14
+ class SwapInit extends SolanaSwapModule_1.SolanaSwapModule {
15
+ constructor() {
16
+ super(...arguments);
17
+ this.SIGNATURE_SLOT_BUFFER = 20;
18
+ this.SIGNATURE_PREFETCH_DATA_VALIDITY = 5000;
19
+ }
20
+ /**
21
+ * bare Init action based on the data passed in swapData
22
+ *
23
+ * @param sender
24
+ * @param swapData
25
+ * @param timeout
26
+ * @private
27
+ */
28
+ async Init(sender, swapData, timeout) {
29
+ const claimerAta = (0, spl_token_1.getAssociatedTokenAddressSync)(swapData.token, swapData.claimer);
30
+ const paymentHash = buffer_1.Buffer.from(swapData.paymentHash, "hex");
31
+ const accounts = {
32
+ initializer: sender,
33
+ claimer: swapData.claimer,
34
+ offerer: swapData.offerer,
35
+ escrowState: this.program._SwapEscrowState(paymentHash),
36
+ mint: swapData.token,
37
+ systemProgram: web3_js_1.SystemProgram.programId,
38
+ claimerAta: swapData.payOut ? claimerAta : null,
39
+ claimerUserData: !swapData.payOut ? this.program._SwapUserVault(swapData.claimer, swapData.token) : null
40
+ };
41
+ if (swapData.payIn) {
42
+ const ata = (0, spl_token_1.getAssociatedTokenAddressSync)(swapData.token, swapData.offerer);
43
+ let instruction;
44
+ const program = this.swapProgram;
45
+ if ((0, SolanaSwapProgram_1.isSwapProgramV1)(program)) {
46
+ if (!swapData.securityDeposit.eq(new BN(0)))
47
+ throw new Error("Swap data for V1 payIn=true swaps cannot have any security deposit!");
48
+ if (!swapData.claimerBounty.eq(new BN(0)))
49
+ throw new Error("Swap data for V1 payIn=true swaps cannot have any claimer bounty!");
50
+ instruction = await program.methods
51
+ .offererInitializePayIn(swapData.toSwapDataStruct(), [...buffer_1.Buffer.alloc(32, 0)], (0, Utils_1.toBN)(timeout))
52
+ .accounts({
53
+ ...accounts,
54
+ offererAta: ata,
55
+ vault: this.program._SwapVault(swapData.token),
56
+ vaultAuthority: this.program._SwapVaultAuthority,
57
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
58
+ })
59
+ .instruction();
60
+ }
61
+ else if ((0, SolanaSwapProgram_1.isSwapProgramV2)(program)) {
62
+ instruction = await program.methods
63
+ .offererInitializePayIn(swapData.toSwapDataStruct(), swapData.securityDeposit, swapData.claimerBounty, [...(swapData.txoHash != null ? buffer_1.Buffer.from(swapData.txoHash, "hex") : buffer_1.Buffer.alloc(32, 0))], (0, Utils_1.toBN)(timeout))
64
+ .accounts({
65
+ ...accounts,
66
+ offererAta: ata,
67
+ vault: this.program._SwapVault(swapData.token),
68
+ vaultAuthority: this.program._SwapVaultAuthority,
69
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
70
+ })
71
+ .instruction();
72
+ // Mark the claimer as signer for non payOut swaps
73
+ if (!swapData.isPayOut()) {
74
+ instruction.keys.forEach(key => {
75
+ if (key.pubkey.equals(swapData.claimer))
76
+ key.isSigner = true;
77
+ });
78
+ }
79
+ }
80
+ else
81
+ throw new Error("Invalid swap program version!");
82
+ return new SolanaAction_1.SolanaAction(sender, this.root, instruction, SwapInit.CUCosts.INIT_PAY_IN);
83
+ }
84
+ else {
85
+ const instruction = await this.swapProgram.methods
86
+ .offererInitialize(swapData.toSwapDataStruct(), swapData.securityDeposit, swapData.claimerBounty, [...(swapData.txoHash != null ? buffer_1.Buffer.from(swapData.txoHash, "hex") : buffer_1.Buffer.alloc(32, 0))], (0, Utils_1.toBN)(timeout))
87
+ .accounts({
88
+ ...accounts,
89
+ offererUserData: this.program._SwapUserVault(swapData.offerer, swapData.token),
90
+ })
91
+ .instruction();
92
+ // Mark the claimer as signer for non payOut swaps
93
+ if ((0, SolanaSwapProgram_1.isSwapProgramV2)(this.swapProgram) && !swapData.isPayOut()) {
94
+ instruction.keys.forEach(key => {
95
+ if (key.pubkey.equals(swapData.claimer))
96
+ key.isSigner = true;
97
+ });
98
+ }
99
+ return new SolanaAction_1.SolanaAction(sender, this.root, instruction, SwapInit.CUCosts.INIT);
100
+ }
101
+ }
102
+ /**
103
+ * InitPayIn action which includes SOL to WSOL wrapping if indicated by the fee rate
104
+ *
105
+ * @param signer
106
+ * @param swapData
107
+ * @param timeout
108
+ * @param feeRate
109
+ * @private
110
+ */
111
+ async InitPayIn(sender, swapData, timeout, feeRate) {
112
+ if (!swapData.isPayIn())
113
+ throw new Error("Must be payIn==true");
114
+ if ((0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram)) {
115
+ if (!sender.equals(swapData.offerer))
116
+ throw new Error("Transaction signer must be offerer for payIn=true escrows!");
117
+ }
118
+ else {
119
+ if (!sender.equals(swapData.offerer) && !sender.equals(swapData.claimer))
120
+ throw new Error("Transaction signer must be either offerer or claimer claimer!");
121
+ }
122
+ const action = new SolanaAction_1.SolanaAction(sender, this.root);
123
+ if (this.shouldWrapOnInit(swapData, feeRate))
124
+ action.addAction(this.Wrap(swapData, feeRate), undefined, true);
125
+ action.addAction(await this.Init(sender, swapData, timeout));
126
+ return action;
127
+ }
128
+ /**
129
+ * InitNotPayIn action with additional createAssociatedTokenAccountIdempotentInstruction instruction, such that
130
+ * a recipient ATA is created if it doesn't exist
131
+ *
132
+ * @param sender
133
+ * @param swapData
134
+ * @param timeout
135
+ * @private
136
+ */
137
+ async InitNotPayIn(sender, swapData, timeout) {
138
+ if (swapData.isPayIn())
139
+ throw new Error("Must be payIn==false");
140
+ if ((0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram)) {
141
+ if (!sender.equals(swapData.claimer))
142
+ throw new Error("Transaction signer must be claimer for payIn=false escrows!");
143
+ }
144
+ else {
145
+ if (!sender.equals(swapData.offerer) && !sender.equals(swapData.claimer))
146
+ throw new Error("Transaction signer must be either offerer or claimer claimer!");
147
+ }
148
+ const action = new SolanaAction_1.SolanaAction(sender, this.root);
149
+ if ((0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram)) {
150
+ action.addIx((0, spl_token_1.createAssociatedTokenAccountIdempotentInstruction)(sender, swapData.claimerAta ?? await (0, spl_token_1.getAssociatedTokenAddress)(swapData.token, swapData.claimer), swapData.claimer, swapData.token));
151
+ } // V2 doesn't explicitly check the token account on initialization, no need to open it
152
+ action.addAction(await this.Init(sender, swapData, timeout));
153
+ return action;
154
+ }
155
+ Wrap(swapData, feeRate) {
156
+ const data = this.extractAtaDataFromFeeRate(feeRate);
157
+ if (feeRate == null || data == null)
158
+ throw new Error("Tried to add wrap instruction, but feeRate malformed: " + feeRate);
159
+ return this.root.Tokens.Wrap(swapData.offerer, swapData.getAmount() - data.balance, data.initAta);
160
+ }
161
+ /**
162
+ * Extracts data about SOL to WSOL wrapping from the fee rate, fee rate is used to convey this information from
163
+ * the user to the intermediary, such that the intermediary creates valid signature for transaction including
164
+ * the SOL to WSOL wrapping instructions
165
+ *
166
+ * @param feeRate
167
+ * @private
168
+ */
169
+ extractAtaDataFromFeeRate(feeRate) {
170
+ const hashArr = feeRate == null ? [] : feeRate.split("#");
171
+ if (hashArr.length <= 1)
172
+ return null;
173
+ const arr = hashArr[1].split(";");
174
+ if (arr.length <= 1)
175
+ return null;
176
+ return {
177
+ balance: BigInt(arr[1]),
178
+ initAta: arr[0] === "1"
179
+ };
180
+ }
181
+ /**
182
+ * Checks whether a wrap instruction (SOL -> WSOL) should be a part of the signed init message
183
+ *
184
+ * @param swapData
185
+ * @param feeRate
186
+ * @private
187
+ * @returns {boolean} returns true if wrap instruction should be added
188
+ */
189
+ shouldWrapOnInit(swapData, feeRate) {
190
+ const data = this.extractAtaDataFromFeeRate(feeRate);
191
+ if (data == null)
192
+ return false;
193
+ return data.balance < swapData.getAmount();
194
+ }
195
+ /**
196
+ * Returns the transaction to be signed as an initialization signature from the intermediary, also adds
197
+ * SOL to WSOL wrapping if indicated by the fee rate
198
+ *
199
+ * @param swapData
200
+ * @param timeout
201
+ * @param feeRate
202
+ * @private
203
+ */
204
+ async getTxToSign(signer, swapData, timeout, feeRate) {
205
+ let txSender;
206
+ if (signer.equals(swapData.offerer)) {
207
+ txSender = swapData.claimer;
208
+ }
209
+ else if (signer.equals(swapData.claimer)) {
210
+ txSender = swapData.offerer;
211
+ }
212
+ else
213
+ throw new Error("Signer needs to be either claimer or offerer of the swap!");
214
+ const action = swapData.isPayIn() ?
215
+ await this.InitPayIn(txSender, swapData, BigInt(timeout), feeRate) :
216
+ await this.InitNotPayIn(txSender, swapData, BigInt(timeout));
217
+ const tx = (await action.tx(feeRate)).tx;
218
+ return tx;
219
+ }
220
+ /**
221
+ * Returns auth prefix to be used with a specific swap, payIn=true & payIn=false use different prefixes (these
222
+ * actually have no meaning for the smart contract/solana program in the Solana case)
223
+ *
224
+ * @param swapData
225
+ * @private
226
+ */
227
+ getAuthPrefix(swapData) {
228
+ return swapData.isPayIn() ? "claim_initialize" : "initialize";
229
+ }
230
+ /**
231
+ * Returns "processed" slot required for signature validation, uses preFetchedData if provided & valid
232
+ *
233
+ * @param preFetchedData
234
+ * @private
235
+ */
236
+ getSlotForSignature(preFetchedData) {
237
+ if (preFetchedData != null &&
238
+ preFetchedData.latestSlot != null &&
239
+ preFetchedData.latestSlot.timestamp > Date.now() - this.root.Slots.SLOT_CACHE_TIME) {
240
+ const estimatedSlotsPassed = Math.floor((Date.now() - preFetchedData.latestSlot.timestamp) / this.root._SLOT_TIME);
241
+ const estimatedCurrentSlot = preFetchedData.latestSlot.slot + estimatedSlotsPassed;
242
+ this.logger.debug("getSlotForSignature(): slot: " + preFetchedData.latestSlot.slot +
243
+ " estimated passed slots: " + estimatedSlotsPassed + " estimated current slot: " + estimatedCurrentSlot);
244
+ return Promise.resolve(estimatedCurrentSlot);
245
+ }
246
+ return this.root.Slots.getSlot("processed");
247
+ }
248
+ /**
249
+ * Returns blockhash required for signature validation, uses preFetchedData if provided & valid
250
+ *
251
+ * @param txSlot
252
+ * @param preFetchedData
253
+ * @private
254
+ */
255
+ getBlockhashForSignature(txSlot, preFetchedData) {
256
+ if (preFetchedData != null &&
257
+ preFetchedData.transactionSlot != null &&
258
+ preFetchedData.transactionSlot.slot === txSlot) {
259
+ return Promise.resolve(preFetchedData.transactionSlot.blockhash);
260
+ }
261
+ return this.root.Blocks.getParsedBlock(txSlot).then(val => val.blockhash);
262
+ }
263
+ /**
264
+ * Pre-fetches slot & block based on priorly received SolanaPreFetchData, such that it can later be used
265
+ * by signature verification
266
+ *
267
+ * @param data
268
+ */
269
+ async preFetchForInitSignatureVerification(data) {
270
+ const [latestSlot, txBlock] = await Promise.all([
271
+ this.root.Slots.getSlotAndTimestamp("processed"),
272
+ this.root.Blocks.getParsedBlock(data.slot)
273
+ ]);
274
+ return {
275
+ latestSlot,
276
+ transactionSlot: {
277
+ slot: data.slot,
278
+ blockhash: txBlock.blockhash
279
+ }
280
+ };
281
+ }
282
+ /**
283
+ * Pre-fetches block data required for signing the init message by the LP, this can happen in parallel before
284
+ * signing takes place making the quoting quicker
285
+ */
286
+ async preFetchBlockDataForSignatures() {
287
+ const latestParsedBlock = await this.root.Blocks.findLatestParsedBlock("finalized");
288
+ return {
289
+ block: latestParsedBlock.block,
290
+ slot: latestParsedBlock.slot,
291
+ timestamp: Date.now()
292
+ };
293
+ }
294
+ /**
295
+ * Signs swap initialization authorization, using data from preFetchedBlockData if provided & still valid (subject
296
+ * to SIGNATURE_PREFETCH_DATA_VALIDITY)
297
+ *
298
+ * @param signer
299
+ * @param swapData
300
+ * @param authorizationTimeout
301
+ * @param feeRate
302
+ * @param preFetchedBlockData
303
+ * @public
304
+ */
305
+ async signSwapInitialization(signer, swapData, authorizationTimeout, preFetchedBlockData, feeRate) {
306
+ if (signer.keypair == null)
307
+ throw new Error("Unsupported");
308
+ if ((0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram)) {
309
+ if (!signer.getPublicKey().equals(swapData.isPayIn() ? swapData.claimer : swapData.offerer))
310
+ throw new Error("Invalid signer, wrong public key!");
311
+ }
312
+ else {
313
+ if (!signer.getPublicKey().equals(swapData.offerer) && !signer.getPublicKey().equals(swapData.claimer))
314
+ throw new Error("Invalid signer, must be either offerer or claimer claimer!");
315
+ }
316
+ if (preFetchedBlockData != null && Date.now() - preFetchedBlockData.timestamp > this.SIGNATURE_PREFETCH_DATA_VALIDITY)
317
+ preFetchedBlockData = undefined;
318
+ const { block: latestBlock, slot: latestSlot } = preFetchedBlockData || await this.root.Blocks.findLatestParsedBlock("finalized");
319
+ const authTimeout = Math.floor(Date.now() / 1000) + authorizationTimeout;
320
+ const txToSign = await this.getTxToSign(signer.getPublicKey(), swapData, authTimeout.toString(10), feeRate);
321
+ txToSign.feePayer = signer.getPublicKey().equals(swapData.offerer) ? swapData.claimer : swapData.offerer;
322
+ txToSign.recentBlockhash = latestBlock.blockhash;
323
+ txToSign.sign(signer.keypair);
324
+ // this.logger.debug("signSwapInitialization(): Signed tx: ",txToSign);
325
+ const sig = txToSign.signatures.find(e => e.publicKey.equals(signer.getPublicKey()));
326
+ if (sig == null || sig.signature == null)
327
+ throw new Error(`Unable to extract transaction signature! Signer: ${signer.getAddress()}`);
328
+ return {
329
+ prefix: this.getAuthPrefix(swapData),
330
+ timeout: authTimeout.toString(10),
331
+ signature: latestSlot + ";" + sig.signature.toString("hex")
332
+ };
333
+ }
334
+ /**
335
+ * Checks whether the provided signature data is valid, using preFetchedData if provided and still valid
336
+ *
337
+ * @param sender
338
+ * @param swapData
339
+ * @param timeout
340
+ * @param prefix
341
+ * @param signature
342
+ * @param feeRate
343
+ * @param preFetchedData
344
+ * @public
345
+ */
346
+ async isSignatureValid(sender, swapData, timeout, prefix, signature, feeRate, preFetchedData) {
347
+ if ((0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram)) {
348
+ if (swapData.isPayIn()) {
349
+ if (!swapData.offerer.equals(sender))
350
+ throw new base_1.SignatureVerificationError("Sender needs to be offerer in payIn=true swaps");
351
+ }
352
+ else {
353
+ if (!swapData.claimer.equals(sender))
354
+ throw new base_1.SignatureVerificationError("Sender needs to be claimer in payIn=false swaps");
355
+ }
356
+ }
357
+ let signer;
358
+ if (sender.equals(swapData.offerer)) {
359
+ signer = swapData.claimer;
360
+ }
361
+ else if (sender.equals(swapData.claimer)) {
362
+ signer = swapData.offerer;
363
+ }
364
+ else
365
+ throw new Error("Signer needs to be either claimer or offerer of the swap!");
366
+ if (!swapData.isPayIn() && await this.program.isExpired(sender.toString(), swapData)) {
367
+ throw new base_1.SignatureVerificationError("Swap will expire too soon!");
368
+ }
369
+ if (prefix !== this.getAuthPrefix(swapData))
370
+ throw new base_1.SignatureVerificationError("Invalid prefix");
371
+ const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
372
+ const isExpired = (BigInt(timeout) - currentTimestamp) < BigInt(this.program._authGracePeriod);
373
+ if (isExpired)
374
+ throw new base_1.SignatureVerificationError("Authorization expired!");
375
+ const requiresCounterpartySignature = (0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram) || !swapData.isPayOut() || sender.equals(swapData.claimer);
376
+ if (requiresCounterpartySignature) {
377
+ if (signature == null)
378
+ throw new base_1.SignatureVerificationError("Counterparty signature is required to initiate the swap!");
379
+ const [transactionSlot, signatureString] = signature.split(";");
380
+ const txSlot = parseInt(transactionSlot);
381
+ const [latestSlot, blockhash] = await Promise.all([
382
+ this.getSlotForSignature(preFetchedData),
383
+ this.getBlockhashForSignature(txSlot, preFetchedData)
384
+ ]);
385
+ const lastValidTransactionSlot = txSlot + this.root._TX_SLOT_VALIDITY;
386
+ const slotsLeft = lastValidTransactionSlot - latestSlot - this.SIGNATURE_SLOT_BUFFER;
387
+ if (slotsLeft < 0)
388
+ throw new base_1.SignatureVerificationError("Authorization expired!");
389
+ const txToSign = await this.getTxToSign(signer, swapData, timeout, feeRate);
390
+ txToSign.feePayer = sender;
391
+ txToSign.recentBlockhash = blockhash;
392
+ txToSign.addSignature(signer, buffer_1.Buffer.from(signatureString, "hex"));
393
+ // this.logger.debug("isSignatureValid(): Signed tx: ",txToSign);
394
+ const valid = txToSign.verifySignatures(false);
395
+ if (!valid)
396
+ throw new base_1.SignatureVerificationError("Invalid signature!");
397
+ return buffer_1.Buffer.from(blockhash);
398
+ }
399
+ return buffer_1.Buffer.alloc(32, 0);
400
+ }
401
+ /**
402
+ * Gets expiry of the provided signature data, this is a minimum of slot expiry & swap signature expiry
403
+ *
404
+ * @param timeout
405
+ * @param signature
406
+ * @param preFetchedData
407
+ * @public
408
+ */
409
+ async getSignatureExpiry(timeout, signature, preFetchedData) {
410
+ let expiry = (parseInt(timeout) - this.program._authGracePeriod) * 1000;
411
+ if (signature != null) {
412
+ const [transactionSlotStr, signatureString] = signature.split(";");
413
+ const txSlot = parseInt(transactionSlotStr);
414
+ const latestSlot = await this.getSlotForSignature(preFetchedData);
415
+ const lastValidTransactionSlot = txSlot + this.root._TX_SLOT_VALIDITY;
416
+ const slotsLeft = lastValidTransactionSlot - latestSlot - this.SIGNATURE_SLOT_BUFFER;
417
+ const slotExpiryTime = Date.now() + (slotsLeft * this.root._SLOT_TIME);
418
+ if (slotExpiryTime < expiry)
419
+ expiry = slotExpiryTime;
420
+ }
421
+ if (expiry < Date.now())
422
+ return 0;
423
+ return expiry;
424
+ }
425
+ /**
426
+ * Checks whether signature is expired for good (uses "finalized" slot)
427
+ *
428
+ * @param signature
429
+ * @param timeout
430
+ * @public
431
+ */
432
+ async isSignatureExpired(signature, timeout) {
433
+ if (signature != null) {
434
+ const [transactionSlotStr, signatureString] = signature.split(";");
435
+ const txSlot = parseInt(transactionSlotStr);
436
+ const lastValidTransactionSlot = txSlot + this.root._TX_SLOT_VALIDITY;
437
+ const latestSlot = await this.root.Slots.getSlot("finalized");
438
+ const slotsLeft = lastValidTransactionSlot - latestSlot + this.SIGNATURE_SLOT_BUFFER;
439
+ if (slotsLeft < 0)
440
+ return true;
441
+ }
442
+ if ((parseInt(timeout) + this.program._authGracePeriod) * 1000 < Date.now())
443
+ return true;
444
+ return false;
445
+ }
446
+ /**
447
+ * Creates init transaction (InitPayIn) with a valid signature from an LP, also adds a SOL to WSOL wrapping ix to
448
+ * the init transaction (if indicated by the fee rate) or adds the wrapping in a separate transaction (if no
449
+ * indication in the fee rate)
450
+ *
451
+ * @param sender
452
+ * @param swapData swap to initialize
453
+ * @param timeout init signature timeout
454
+ * @param prefix init signature prefix
455
+ * @param signature init signature
456
+ * @param skipChecks whether to skip signature validity checks
457
+ * @param feeRate fee rate to use for the transaction
458
+ */
459
+ async txsInitPayIn(sender, swapData, timeout, prefix, signature, skipChecks, feeRate) {
460
+ if ((0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram)) {
461
+ if (!sender.equals(swapData.offerer))
462
+ throw new Error("Transaction sender has to be the offerer!");
463
+ }
464
+ let signer;
465
+ if (sender.equals(swapData.offerer)) {
466
+ signer = swapData.claimer;
467
+ }
468
+ else if (sender.equals(swapData.claimer)) {
469
+ signer = swapData.offerer;
470
+ }
471
+ else
472
+ throw new Error("Signer needs to be either claimer or offerer of the swap!");
473
+ if (swapData.offererAta == undefined)
474
+ throw new base_1.SwapDataVerificationError("No offererAta specified for payIn swap!");
475
+ const offererAta = swapData.offererAta;
476
+ const requiresCounterpartySignature = (0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram) || !swapData.isPayOut() || sender.equals(swapData.claimer);
477
+ if (!skipChecks) {
478
+ const [_, payStatus] = await Promise.all([
479
+ requiresCounterpartySignature ? this.isSignatureValid(sender, swapData, timeout, prefix, signature, feeRate) : Promise.resolve(),
480
+ this.program.getClaimHashStatus(swapData.getClaimHash())
481
+ ]);
482
+ if (payStatus !== base_1.SwapCommitStateType.NOT_COMMITED)
483
+ throw new base_1.SwapDataVerificationError("Invoice already being paid for or paid");
484
+ }
485
+ let block;
486
+ if (requiresCounterpartySignature) {
487
+ const slotNumber = signature.split(";")[0];
488
+ block = await (0, Utils_1.tryWithRetries)(() => this.root.Blocks.getParsedBlock(parseInt(slotNumber)), { maxRetries: 3, delay: 100, exponential: true });
489
+ }
490
+ const txs = [];
491
+ let isWrapping = false;
492
+ const isWrappedInSignedTx = feeRate != null && feeRate.split("#").length > 1;
493
+ if (!isWrappedInSignedTx && swapData.token.equals(SolanaTokens_1.SolanaTokens.WSOL_ADDRESS)) {
494
+ const ataAcc = await this.root.Tokens.getATAOrNull(offererAta);
495
+ const balance = ataAcc?.amount ?? 0n;
496
+ if (balance < swapData.getAmount()) {
497
+ if (!swapData.offerer.equals(sender))
498
+ throw new Error("Additional SOL needs to be wrapped but the sender is not offerer!");
499
+ //Need to wrap more SOL to WSOL
500
+ await this.root.Tokens.Wrap(swapData.offerer, swapData.getAmount() - balance, ataAcc == null)
501
+ .addToTxs(txs, feeRate, block);
502
+ isWrapping = true;
503
+ }
504
+ }
505
+ const initTx = await (await this.InitPayIn(sender, swapData, BigInt(timeout), feeRate)).tx(feeRate, block);
506
+ if (requiresCounterpartySignature)
507
+ initTx.tx.addSignature(signer, buffer_1.Buffer.from(signature.split(";")[1], "hex"));
508
+ txs.push(initTx);
509
+ this.logger.debug("txsInitPayIn(): create swap init TX, swap: " + swapData.getClaimHash() +
510
+ " wrapping client-side: " + isWrapping + " feerate: " + feeRate);
511
+ return txs;
512
+ }
513
+ /**
514
+ * Creates init transactions (InitNotPayIn) with a valid signature from an intermediary
515
+ *
516
+ * @param sender
517
+ * @param swapData swap to initialize
518
+ * @param timeout init signature timeout
519
+ * @param prefix init signature prefix
520
+ * @param signature init signature
521
+ * @param skipChecks whether to skip signature validity checks
522
+ * @param feeRate fee rate to use for the transaction
523
+ */
524
+ async txsInit(sender, swapData, timeout, prefix, signature, skipChecks, feeRate) {
525
+ if ((0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram)) {
526
+ if (!sender.equals(swapData.claimer))
527
+ throw new Error("Transaction sender has to be the claimer!");
528
+ }
529
+ let signer;
530
+ if (sender.equals(swapData.offerer)) {
531
+ signer = swapData.claimer;
532
+ }
533
+ else if (sender.equals(swapData.claimer)) {
534
+ signer = swapData.offerer;
535
+ }
536
+ else
537
+ throw new Error("Signer needs to be either claimer or offerer of the swap!");
538
+ const requiresCounterpartySignature = (0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram) || !swapData.isPayOut() || sender.equals(swapData.claimer);
539
+ let block;
540
+ if (requiresCounterpartySignature) {
541
+ if (!skipChecks) {
542
+ await this.isSignatureValid(sender, swapData, timeout, prefix, signature, feeRate);
543
+ }
544
+ const slotNumber = signature.split(";")[0];
545
+ block = await (0, Utils_1.tryWithRetries)(() => this.root.Blocks.getParsedBlock(parseInt(slotNumber)), { maxRetries: 3, delay: 100, exponential: true });
546
+ }
547
+ const initTx = await (await this.InitNotPayIn(sender, swapData, BigInt(timeout))).tx(feeRate, block);
548
+ if (requiresCounterpartySignature)
549
+ initTx.tx.addSignature(signer, buffer_1.Buffer.from(signature.split(";")[1], "hex"));
550
+ this.logger.debug("txsInit(): create swap init TX, swap: " + swapData.getClaimHash() + " feerate: " + feeRate);
551
+ return [initTx];
552
+ }
553
+ /**
554
+ * Returns the fee rate to be used for a specific init transaction, also adding indication whether the WSOL ATA
555
+ * should be initialized in the init transaction and/or current balance in the WSOL ATA
556
+ *
557
+ * @param offerer
558
+ * @param claimer
559
+ * @param token
560
+ * @param paymentHash
561
+ */
562
+ async getInitPayInFeeRate(offerer, claimer, token, paymentHash) {
563
+ const accounts = [];
564
+ if (offerer != null)
565
+ accounts.push(offerer);
566
+ if (token != null) {
567
+ accounts.push(this.program._SwapVault(token));
568
+ if (offerer != null)
569
+ accounts.push((0, spl_token_1.getAssociatedTokenAddressSync)(token, offerer));
570
+ if (claimer != null)
571
+ accounts.push(this.program._SwapUserVault(claimer, token));
572
+ }
573
+ if (paymentHash != null)
574
+ accounts.push(this.program._SwapEscrowState(buffer_1.Buffer.from(paymentHash, "hex")));
575
+ const shouldCheckWSOLAta = token != null && offerer != null && token.equals(SolanaTokens_1.SolanaTokens.WSOL_ADDRESS);
576
+ let [feeRate, account] = await Promise.all([
577
+ this.root.Fees.getFeeRate(accounts),
578
+ shouldCheckWSOLAta ?
579
+ this.root.Tokens.getATAOrNull((0, spl_token_1.getAssociatedTokenAddressSync)(token, offerer)) :
580
+ Promise.resolve(null)
581
+ ]);
582
+ if (shouldCheckWSOLAta) {
583
+ const balance = account?.amount ?? 0n;
584
+ //Add an indication about whether the ATA is initialized & balance it contains
585
+ feeRate += "#" + (account != null ? "0" : "1") + ";" + balance.toString(10);
586
+ }
587
+ this.logger.debug("getInitPayInFeeRate(): feerate computed: " + feeRate);
588
+ return feeRate;
589
+ }
590
+ /**
591
+ * Returns the fee rate to be used for a specific init transaction
592
+ *
593
+ * @param offerer
594
+ * @param claimer
595
+ * @param token
596
+ * @param paymentHash
597
+ */
598
+ getInitFeeRate(offerer, claimer, token, paymentHash) {
599
+ const accounts = [];
600
+ if (offerer != null && token != null)
601
+ accounts.push(this.program._SwapUserVault(offerer, token));
602
+ if (claimer != null)
603
+ accounts.push(claimer);
604
+ if (paymentHash != null)
605
+ accounts.push(this.program._SwapEscrowState(buffer_1.Buffer.from(paymentHash, "hex")));
606
+ return this.root.Fees.getFeeRate(accounts);
607
+ }
608
+ /**
609
+ * Get the estimated solana fee of the init transaction, this includes the required deposit for creating swap PDA
610
+ * and also deposit for ATAs
611
+ */
612
+ async getInitFee(swapData, feeRate) {
613
+ if (swapData == null)
614
+ return BigInt(this.program.ESCROW_STATE_RENT_EXEMPT) + await this.getRawInitFee(swapData, feeRate);
615
+ feeRate = feeRate ||
616
+ (swapData.payIn
617
+ ? await this.getInitPayInFeeRate(swapData.offerer, swapData.claimer, swapData.token, swapData.paymentHash)
618
+ : await this.getInitFeeRate(swapData.offerer, swapData.claimer, swapData.token, swapData.paymentHash));
619
+ const [rawFee, initAta] = await Promise.all([
620
+ this.getRawInitFee(swapData, feeRate),
621
+ (0, SolanaSwapProgram_1.isSwapProgramV1)(this.swapProgram) && swapData != null && swapData.payOut ?
622
+ this.root.Tokens.getATAOrNull((0, spl_token_1.getAssociatedTokenAddressSync)(swapData.token, swapData.claimer)).then(acc => acc == null) :
623
+ Promise.resolve(null)
624
+ ]);
625
+ let resultingFee = BigInt(this.program.ESCROW_STATE_RENT_EXEMPT) + rawFee;
626
+ if (initAta)
627
+ resultingFee += BigInt(SolanaTokens_1.SolanaTokens.SPL_ATA_RENT_EXEMPT);
628
+ if (swapData.payIn && this.shouldWrapOnInit(swapData, feeRate) && this.extractAtaDataFromFeeRate(feeRate).initAta) {
629
+ resultingFee += BigInt(SolanaTokens_1.SolanaTokens.SPL_ATA_RENT_EXEMPT);
630
+ }
631
+ return resultingFee;
632
+ }
633
+ /**
634
+ * Get the estimated solana fee of the init transaction, without the required deposit for creating swap PDA
635
+ */
636
+ async getRawInitFee(swapData, feeRate) {
637
+ if (swapData == null)
638
+ return 10000n;
639
+ feeRate = feeRate ??
640
+ (swapData.payIn
641
+ ? await this.getInitPayInFeeRate(swapData.offerer, swapData.claimer, swapData.token, swapData.paymentHash)
642
+ : await this.getInitFeeRate(swapData.offerer, swapData.claimer, swapData.token, swapData.paymentHash));
643
+ let computeBudget = swapData.payIn ? SwapInit.CUCosts.INIT_PAY_IN : SwapInit.CUCosts.INIT;
644
+ if (swapData.payIn && this.shouldWrapOnInit(swapData, feeRate)) {
645
+ computeBudget += SolanaTokens_1.SolanaTokens.CUCosts.WRAP_SOL;
646
+ const data = this.extractAtaDataFromFeeRate(feeRate);
647
+ if (data.initAta)
648
+ computeBudget += SolanaTokens_1.SolanaTokens.CUCosts.ATA_INIT;
649
+ }
650
+ const baseFee = swapData.payIn ? 10000n : 10000n + 5000n;
651
+ return baseFee + this.root.Fees.getPriorityFee(computeBudget, feeRate);
652
+ }
653
+ }
654
+ exports.SwapInit = SwapInit;
655
+ SwapInit.CUCosts = {
656
+ INIT: 90000,
657
+ INIT_PAY_IN: 50000,
658
+ };