@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,463 +1,470 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SolanaSwapProgram = void 0;
4
- const SolanaSwapData_1 = require("./SolanaSwapData");
5
- const web3_js_1 = require("@solana/web3.js");
6
- const sha2_1 = require("@noble/hashes/sha2");
7
- const programIdl = require("./programIdl.json");
8
- const base_1 = require("@atomiqlabs/base");
9
- const spl_token_1 = require("@solana/spl-token");
10
- const SolanaProgramBase_1 = require("../program/SolanaProgramBase");
11
- const SwapInit_1 = require("./modules/SwapInit");
12
- const SolanaDataAccount_1 = require("./modules/SolanaDataAccount");
13
- const SwapRefund_1 = require("./modules/SwapRefund");
14
- const SwapClaim_1 = require("./modules/SwapClaim");
15
- const SolanaLpVault_1 = require("./modules/SolanaLpVault");
16
- const buffer_1 = require("buffer");
17
- const Utils_1 = require("../../utils/Utils");
18
- const SolanaTokens_1 = require("../chain/modules/SolanaTokens");
19
- const BN = require("bn.js");
20
- function toPublicKeyOrNull(str) {
21
- return str == null ? null : new web3_js_1.PublicKey(str);
22
- }
23
- class SolanaSwapProgram extends SolanaProgramBase_1.SolanaProgramBase {
24
- constructor(chainInterface, btcRelay, storage, programAddress) {
25
- super(chainInterface, programIdl, programAddress);
26
- ////////////////////////
27
- //// Constants
28
- this.ESCROW_STATE_RENT_EXEMPT = 2658720;
29
- ////////////////////////
30
- //// PDA accessors
31
- this.SwapVaultAuthority = this.pda("authority");
32
- this.SwapVault = this.pda("vault", (tokenAddress) => [tokenAddress.toBuffer()]);
33
- this.SwapUserVault = this.pda("uservault", (publicKey, tokenAddress) => [publicKey.toBuffer(), tokenAddress.toBuffer()]);
34
- this.SwapEscrowState = this.pda("state", (hash) => [hash]);
35
- ////////////////////////
36
- //// Timeouts
37
- this.chainId = "SOLANA";
38
- this.claimWithSecretTimeout = 45;
39
- this.claimWithTxDataTimeout = 120;
40
- this.refundTimeout = 45;
41
- this.claimGracePeriod = 10 * 60;
42
- this.refundGracePeriod = 10 * 60;
43
- this.authGracePeriod = 5 * 60;
44
- this.Init = new SwapInit_1.SwapInit(chainInterface, this);
45
- this.Refund = new SwapRefund_1.SwapRefund(chainInterface, this);
46
- this.Claim = new SwapClaim_1.SwapClaim(chainInterface, this, btcRelay);
47
- this.DataAccount = new SolanaDataAccount_1.SolanaDataAccount(chainInterface, this, storage);
48
- this.LpVault = new SolanaLpVault_1.SolanaLpVault(chainInterface, this);
49
- }
50
- async start() {
51
- await this.DataAccount.init();
52
- }
53
- getClaimableDeposits(signer) {
54
- return this.DataAccount.getDataAccountsInfo(new web3_js_1.PublicKey(signer));
55
- }
56
- claimDeposits(signer) {
57
- return this.DataAccount.sweepDataAccounts(signer);
58
- }
59
- ////////////////////////////////////////////
60
- //// Signatures
61
- preFetchForInitSignatureVerification(data) {
62
- return this.Init.preFetchForInitSignatureVerification(data);
63
- }
64
- preFetchBlockDataForSignatures() {
65
- return this.Init.preFetchBlockDataForSignatures();
66
- }
67
- getInitSignature(signer, swapData, authorizationTimeout, preFetchedBlockData, feeRate) {
68
- return this.Init.signSwapInitialization(signer, swapData, authorizationTimeout, preFetchedBlockData, feeRate);
69
- }
70
- isValidInitAuthorization(signer, swapData, { timeout, prefix, signature }, feeRate, preFetchedData) {
71
- return this.Init.isSignatureValid(signer, swapData, timeout, prefix, signature, feeRate, preFetchedData);
72
- }
73
- getInitAuthorizationExpiry(swapData, { timeout, prefix, signature }, preFetchedData) {
74
- return this.Init.getSignatureExpiry(timeout, signature, preFetchedData);
75
- }
76
- isInitAuthorizationExpired(swapData, { timeout, prefix, signature }) {
77
- return this.Init.isSignatureExpired(signature, timeout);
78
- }
79
- getRefundSignature(signer, swapData, authorizationTimeout) {
80
- return this.Refund.signSwapRefund(signer, swapData, authorizationTimeout);
81
- }
82
- isValidRefundAuthorization(swapData, { timeout, prefix, signature }) {
83
- return this.Refund.isSignatureValid(swapData, timeout, prefix, signature);
84
- }
85
- getDataSignature(signer, data) {
86
- return this.Chain.Signatures.getDataSignature(signer, data);
87
- }
88
- isValidDataSignature(data, signature, publicKey) {
89
- return this.Chain.Signatures.isValidDataSignature(data, signature, publicKey);
90
- }
91
- ////////////////////////////////////////////
92
- //// Swap data utils
93
- /**
94
- * Checks whether the claim is claimable by us, that means not expired, we are claimer & the swap is commited
95
- *
96
- * @param signer
97
- * @param data
98
- */
99
- async isClaimable(signer, data) {
100
- if (!data.isClaimer(signer))
101
- return false;
102
- if (await this.isExpired(signer, data))
103
- return false;
104
- return await this.isCommited(data);
105
- }
106
- /**
107
- * Checks whether a swap is commited, i.e. the swap still exists on-chain and was not claimed nor refunded
108
- *
109
- * @param swapData
110
- */
111
- async isCommited(swapData) {
112
- const paymentHash = buffer_1.Buffer.from(swapData.paymentHash, "hex");
113
- const account = await this.program.account.escrowState.fetchNullable(this.SwapEscrowState(paymentHash));
114
- if (account == null)
115
- return false;
116
- return swapData.correctPDA(account);
117
- }
118
- /**
119
- * Checks whether the swap is expired, takes into consideration possible on-chain time skew, therefore for claimer
120
- * the swap expires a bit sooner than it should've & for the offerer it expires a bit later
121
- *
122
- * @param signer
123
- * @param data
124
- */
125
- isExpired(signer, data) {
126
- let currentTimestamp = new BN(Math.floor(Date.now() / 1000));
127
- if (data.isClaimer(signer))
128
- currentTimestamp = currentTimestamp.add(new BN(this.claimGracePeriod));
129
- if (data.isOfferer(signer))
130
- currentTimestamp = currentTimestamp.sub(new BN(this.refundGracePeriod));
131
- return Promise.resolve(data.expiry.lt(currentTimestamp));
132
- }
133
- /**
134
- * Checks if the swap is refundable by us, checks if we are offerer, if the swap is already expired & if the swap
135
- * is still commited
136
- *
137
- * @param signer
138
- * @param data
139
- */
140
- async isRequestRefundable(signer, data) {
141
- //Swap can only be refunded by the offerer
142
- if (!data.isOfferer(signer))
143
- return false;
144
- if (!(await this.isExpired(signer, data)))
145
- return false;
146
- return await this.isCommited(data);
147
- }
148
- /**
149
- * Get the swap payment hash to be used for an on-chain swap, this just uses a sha256 hash of the values
150
- *
151
- * @param outputScript output script required to claim the swap
152
- * @param amount sats sent required to claim the swap
153
- * @param confirmations
154
- * @param nonce swap nonce uniquely identifying the transaction to prevent replay attacks
155
- */
156
- getHashForOnchain(outputScript, amount, confirmations, nonce) {
157
- nonce ?? (nonce = 0n);
158
- const paymentHash = buffer_1.Buffer.from((0, sha2_1.sha256)(buffer_1.Buffer.concat([
159
- base_1.BigIntBufferUtils.toBuffer(nonce, "le", 8),
160
- base_1.BigIntBufferUtils.toBuffer(amount, "le", 8),
161
- outputScript
162
- ]))).toString("hex");
163
- return buffer_1.Buffer.from((0, Utils_1.toClaimHash)(paymentHash, nonce, confirmations), "hex");
164
- }
165
- getHashForHtlc(swapHash) {
166
- return buffer_1.Buffer.from((0, Utils_1.toClaimHash)(swapHash.toString("hex"), 0n, 0), "hex");
167
- }
168
- getHashForTxId(txId, confirmations) {
169
- return buffer_1.Buffer.from((0, Utils_1.toClaimHash)(buffer_1.Buffer.from(txId, "hex").reverse().toString("hex"), 0n, confirmations), "hex");
170
- }
171
- ////////////////////////////////////////////
172
- //// Swap data getters
173
- /**
174
- * Gets the status of the specific swap, this also checks if we are offerer/claimer & checks for expiry (to see
175
- * if swap is refundable)
176
- *
177
- * @param signer
178
- * @param data
179
- */
180
- async getCommitStatus(signer, data) {
181
- const escrowStateKey = this.SwapEscrowState(buffer_1.Buffer.from(data.paymentHash, "hex"));
182
- const [escrowState, isExpired] = await Promise.all([
183
- this.program.account.escrowState.fetchNullable(escrowStateKey),
184
- this.isExpired(signer, data)
185
- ]);
186
- if (escrowState != null) {
187
- if (data.correctPDA(escrowState)) {
188
- if (data.isOfferer(signer) && isExpired)
189
- return { type: base_1.SwapCommitStateType.REFUNDABLE };
190
- return { type: base_1.SwapCommitStateType.COMMITED };
191
- }
192
- if (data.isOfferer(signer) && isExpired)
193
- return { type: base_1.SwapCommitStateType.EXPIRED };
194
- return { type: base_1.SwapCommitStateType.NOT_COMMITED };
195
- }
196
- //Check if paid or what
197
- const status = await this.Events.findInEvents(escrowStateKey, async (event, info) => {
198
- if (event.name === "ClaimEvent") {
199
- if (!event.data.sequence.eq(data.sequence))
200
- return null;
201
- return {
202
- type: base_1.SwapCommitStateType.PAID,
203
- getClaimTxId: () => Promise.resolve(info.signature),
204
- getTxBlock: async () => {
205
- return {
206
- blockHeight: (await this.Chain.Blocks.getParsedBlock(info.slot)).blockHeight,
207
- blockTime: info.blockTime
208
- };
209
- }
210
- };
211
- }
212
- if (event.name === "RefundEvent") {
213
- if (!event.data.sequence.eq(data.sequence))
214
- return null;
215
- return {
216
- type: isExpired ? base_1.SwapCommitStateType.EXPIRED : base_1.SwapCommitStateType.NOT_COMMITED,
217
- getRefundTxId: () => Promise.resolve(info.signature),
218
- getTxBlock: async () => {
219
- return {
220
- blockHeight: (await this.Chain.Blocks.getParsedBlock(info.slot)).blockHeight,
221
- blockTime: info.blockTime
222
- };
223
- }
224
- };
225
- }
226
- });
227
- if (status != null)
228
- return status;
229
- if (isExpired)
230
- return { type: base_1.SwapCommitStateType.EXPIRED };
231
- return { type: base_1.SwapCommitStateType.NOT_COMMITED };
232
- }
233
- /**
234
- * Checks the status of the specific payment hash
235
- *
236
- * @param claimHash
237
- */
238
- async getClaimHashStatus(claimHash) {
239
- const { paymentHash } = (0, Utils_1.fromClaimHash)(claimHash);
240
- const escrowStateKey = this.SwapEscrowState(buffer_1.Buffer.from(paymentHash, "hex"));
241
- const abortController = new AbortController();
242
- //Start fetching events before checking escrow PDA, this call is used when quoting, so saving 100ms here helps a lot!
243
- const eventsPromise = this.Events.findInEvents(escrowStateKey, async (event) => {
244
- if (event.name === "ClaimEvent")
245
- return base_1.SwapCommitStateType.PAID;
246
- if (event.name === "RefundEvent")
247
- return base_1.SwapCommitStateType.NOT_COMMITED;
248
- }, abortController.signal).catch(e => {
249
- abortController.abort(e);
250
- return null;
251
- });
252
- const escrowState = await this.program.account.escrowState.fetchNullable(escrowStateKey);
253
- abortController.signal.throwIfAborted();
254
- if (escrowState != null) {
255
- abortController.abort();
256
- return base_1.SwapCommitStateType.COMMITED;
257
- }
258
- //Check if paid or what
259
- const eventsStatus = await eventsPromise;
260
- abortController.signal.throwIfAborted();
261
- if (eventsStatus != null)
262
- return eventsStatus;
263
- return base_1.SwapCommitStateType.NOT_COMMITED;
264
- }
265
- /**
266
- * Returns the data committed for a specific payment hash, or null if no data is currently commited for
267
- * the specific swap
268
- *
269
- * @param claimHashHex
270
- */
271
- async getCommitedData(claimHashHex) {
272
- const { paymentHash } = (0, Utils_1.fromClaimHash)(claimHashHex);
273
- const paymentHashBuffer = buffer_1.Buffer.from(paymentHash, "hex");
274
- const account = await this.program.account.escrowState.fetchNullable(this.SwapEscrowState(paymentHashBuffer));
275
- if (account == null)
276
- return null;
277
- return SolanaSwapData_1.SolanaSwapData.fromEscrowState(account);
278
- }
279
- ////////////////////////////////////////////
280
- //// Swap data initializer
281
- createSwapData(type, offerer, claimer, token, amount, claimHash, sequence, expiry, payIn, payOut, securityDeposit, claimerBounty, depositToken) {
282
- if (depositToken != null) {
283
- if (!new web3_js_1.PublicKey(depositToken).equals(SolanaTokens_1.SolanaTokens.WSOL_ADDRESS))
284
- throw new Error("Only SOL supported as deposit token!");
285
- }
286
- const tokenAddr = new web3_js_1.PublicKey(token);
287
- const offererKey = offerer == null ? null : new web3_js_1.PublicKey(offerer);
288
- const claimerKey = claimer == null ? null : new web3_js_1.PublicKey(claimer);
289
- const { paymentHash, nonce, confirmations } = (0, Utils_1.fromClaimHash)(claimHash);
290
- return Promise.resolve(new SolanaSwapData_1.SolanaSwapData(offererKey, claimerKey, tokenAddr, (0, Utils_1.toBN)(amount), paymentHash, (0, Utils_1.toBN)(sequence), (0, Utils_1.toBN)(expiry), nonce, confirmations, payOut, type == null ? null : SolanaSwapData_1.SolanaSwapData.typeToKind(type), payIn, offererKey == null ? null : payIn ? (0, spl_token_1.getAssociatedTokenAddressSync)(tokenAddr, offererKey) : web3_js_1.PublicKey.default, claimerKey == null ? null : payOut ? (0, spl_token_1.getAssociatedTokenAddressSync)(tokenAddr, claimerKey) : web3_js_1.PublicKey.default, (0, Utils_1.toBN)(securityDeposit), (0, Utils_1.toBN)(claimerBounty), null));
291
- }
292
- ////////////////////////////////////////////
293
- //// Utils
294
- async getBalance(signer, tokenAddress, inContract) {
295
- if (!inContract) {
296
- return await this.Chain.getBalance(signer, tokenAddress);
297
- }
298
- const token = new web3_js_1.PublicKey(tokenAddress);
299
- const publicKey = new web3_js_1.PublicKey(signer);
300
- return await this.getIntermediaryBalance(publicKey, token);
301
- }
302
- getIntermediaryData(address, token) {
303
- return this.LpVault.getIntermediaryData(new web3_js_1.PublicKey(address), new web3_js_1.PublicKey(token));
304
- }
305
- getIntermediaryReputation(address, token) {
306
- return this.LpVault.getIntermediaryReputation(new web3_js_1.PublicKey(address), new web3_js_1.PublicKey(token));
307
- }
308
- getIntermediaryBalance(address, token) {
309
- return this.LpVault.getIntermediaryBalance(address, token);
310
- }
311
- ////////////////////////////////////////////
312
- //// Transaction initializers
313
- async txsClaimWithSecret(signer, swapData, secret, checkExpiry, initAta, feeRate, skipAtaCheck) {
314
- return this.Claim.txsClaimWithSecret(typeof (signer) === "string" ? new web3_js_1.PublicKey(signer) : signer.getPublicKey(), swapData, secret, checkExpiry, initAta, feeRate, skipAtaCheck);
315
- }
316
- async txsClaimWithTxData(signer, swapData, tx, requiredConfirmations, vout, commitedHeader, synchronizer, initAta, feeRate, storageAccHolder) {
317
- if (swapData.confirmations !== requiredConfirmations)
318
- throw new Error("Invalid requiredConfirmations provided!");
319
- return this.Claim.txsClaimWithTxData(typeof (signer) === "string" ? new web3_js_1.PublicKey(signer) : signer, swapData, tx, vout, commitedHeader, synchronizer, initAta, storageAccHolder, feeRate);
320
- }
321
- txsRefund(signer, swapData, check, initAta, feeRate) {
322
- if (!swapData.isOfferer(signer))
323
- throw new Error("Only offerer can refund on Solana");
324
- return this.Refund.txsRefund(swapData, check, initAta, feeRate);
325
- }
326
- txsRefundWithAuthorization(signer, swapData, { timeout, prefix, signature }, check, initAta, feeRate) {
327
- if (!swapData.isOfferer(signer))
328
- throw new Error("Only offerer can refund on Solana");
329
- return this.Refund.txsRefundWithAuthorization(swapData, timeout, prefix, signature, check, initAta, feeRate);
330
- }
331
- txsInit(sender, swapData, { timeout, prefix, signature }, skipChecks, feeRate) {
332
- if (swapData.isPayIn()) {
333
- if (!swapData.isOfferer(sender))
334
- throw new Error("Only offerer can create payIn=true swap");
335
- return this.Init.txsInitPayIn(swapData, timeout, prefix, signature, skipChecks, feeRate);
336
- }
337
- else {
338
- if (!swapData.isClaimer(sender))
339
- throw new Error("Only claimer can create payIn=false swap");
340
- return this.Init.txsInit(swapData, timeout, prefix, signature, skipChecks, feeRate);
341
- }
342
- }
343
- txsWithdraw(signer, token, amount, feeRate) {
344
- return this.LpVault.txsWithdraw(new web3_js_1.PublicKey(signer), new web3_js_1.PublicKey(token), amount, feeRate);
345
- }
346
- txsDeposit(signer, token, amount, feeRate) {
347
- return this.LpVault.txsDeposit(new web3_js_1.PublicKey(signer), new web3_js_1.PublicKey(token), amount, feeRate);
348
- }
349
- ////////////////////////////////////////////
350
- //// Executors
351
- async claimWithSecret(signer, swapData, secret, checkExpiry, initAta, txOptions) {
352
- const result = await this.Claim.txsClaimWithSecret(signer.getPublicKey(), swapData, secret, checkExpiry, initAta, txOptions?.feeRate);
353
- const [signature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
354
- return signature;
355
- }
356
- async claimWithTxData(signer, swapData, tx, requiredConfirmations, vout, commitedHeader, synchronizer, initAta, txOptions) {
357
- if (requiredConfirmations !== swapData.confirmations)
358
- throw new Error("Invalid requiredConfirmations provided!");
359
- const data = {
360
- storageAcc: null
361
- };
362
- const txs = await this.Claim.txsClaimWithTxData(signer, swapData, tx, vout, commitedHeader, synchronizer, initAta, data, txOptions?.feeRate);
363
- if (txs === null)
364
- throw new Error("Btc relay not synchronized to required blockheight!");
365
- //TODO: This doesn't return proper tx signature
366
- const [signature] = await this.Chain.sendAndConfirm(signer, txs, txOptions?.waitForConfirmation, txOptions?.abortSignal);
367
- await this.DataAccount.removeDataAccount(data.storageAcc);
368
- return signature;
369
- }
370
- async refund(signer, swapData, check, initAta, txOptions) {
371
- let result = await this.txsRefund(signer.getAddress(), swapData, check, initAta, txOptions?.feeRate);
372
- const [signature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
373
- return signature;
374
- }
375
- async refundWithAuthorization(signer, swapData, signature, check, initAta, txOptions) {
376
- let result = await this.txsRefundWithAuthorization(signer.getAddress(), swapData, signature, check, initAta, txOptions?.feeRate);
377
- const [txSignature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
378
- return txSignature;
379
- }
380
- async init(signer, swapData, signature, skipChecks, txOptions) {
381
- if (swapData.isPayIn()) {
382
- if (!signer.getPublicKey().equals(swapData.offerer))
383
- throw new Error("Invalid signer provided!");
384
- }
385
- else {
386
- if (!signer.getPublicKey().equals(swapData.claimer))
387
- throw new Error("Invalid signer provided!");
388
- }
389
- const result = await this.txsInit(signer.getAddress(), swapData, signature, skipChecks, txOptions?.feeRate);
390
- const [txSignature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
391
- return txSignature;
392
- }
393
- async initAndClaimWithSecret(signer, swapData, signature, secret, skipChecks, txOptions) {
394
- if (!signer.getPublicKey().equals(swapData.claimer))
395
- throw new Error("Invalid signer provided!");
396
- const txsCommit = await this.txsInit(signer.getAddress(), swapData, signature, skipChecks, txOptions?.feeRate);
397
- const txsClaim = await this.Claim.txsClaimWithSecret(signer.getPublicKey(), swapData, secret, true, false, txOptions?.feeRate, true);
398
- return await this.Chain.sendAndConfirm(signer, txsCommit.concat(txsClaim), txOptions?.waitForConfirmation, txOptions?.abortSignal);
399
- }
400
- async withdraw(signer, token, amount, txOptions) {
401
- const txs = await this.LpVault.txsWithdraw(signer.getPublicKey(), new web3_js_1.PublicKey(token), amount, txOptions?.feeRate);
402
- const [txId] = await this.Chain.sendAndConfirm(signer, txs, txOptions?.waitForConfirmation, txOptions?.abortSignal, false);
403
- return txId;
404
- }
405
- async deposit(signer, token, amount, txOptions) {
406
- const txs = await this.LpVault.txsDeposit(signer.getPublicKey(), new web3_js_1.PublicKey(token), amount, txOptions?.feeRate);
407
- const [txId] = await this.Chain.sendAndConfirm(signer, txs, txOptions?.waitForConfirmation, txOptions?.abortSignal, false);
408
- return txId;
409
- }
410
- ////////////////////////////////////////////
411
- //// Fees
412
- getInitPayInFeeRate(offerer, claimer, token, claimHash) {
413
- const paymentHash = claimHash == null ? null : (0, Utils_1.fromClaimHash)(claimHash).paymentHash;
414
- return this.Init.getInitPayInFeeRate(toPublicKeyOrNull(offerer), toPublicKeyOrNull(claimer), toPublicKeyOrNull(token), paymentHash);
415
- }
416
- getInitFeeRate(offerer, claimer, token, claimHash) {
417
- const paymentHash = claimHash == null ? null : (0, Utils_1.fromClaimHash)(claimHash).paymentHash;
418
- return this.Init.getInitFeeRate(toPublicKeyOrNull(offerer), toPublicKeyOrNull(claimer), toPublicKeyOrNull(token), paymentHash);
419
- }
420
- getRefundFeeRate(swapData) {
421
- return this.Refund.getRefundFeeRate(swapData);
422
- }
423
- getClaimFeeRate(signer, swapData) {
424
- return this.Claim.getClaimFeeRate(new web3_js_1.PublicKey(signer), swapData);
425
- }
426
- getClaimFee(signer, swapData, feeRate) {
427
- return this.Claim.getClaimFee(new web3_js_1.PublicKey(signer), swapData, feeRate);
428
- }
429
- getRawClaimFee(signer, swapData, feeRate) {
430
- return this.Claim.getRawClaimFee(new web3_js_1.PublicKey(signer), swapData, feeRate);
431
- }
432
- /**
433
- * Get the estimated solana fee of the commit transaction
434
- */
435
- getCommitFee(signer, swapData, feeRate) {
436
- return this.Init.getInitFee(swapData, feeRate);
437
- }
438
- /**
439
- * Get the estimated solana fee of the commit transaction, without any deposits
440
- */
441
- getRawCommitFee(signer, swapData, feeRate) {
442
- return this.Init.getRawInitFee(swapData, feeRate);
443
- }
444
- /**
445
- * Get the estimated solana transaction fee of the refund transaction
446
- */
447
- getRefundFee(signer, swapData, feeRate) {
448
- return this.Refund.getRefundFee(swapData, feeRate);
449
- }
450
- /**
451
- * Get the estimated solana transaction fee of the refund transaction
452
- */
453
- getRawRefundFee(signer, swapData, feeRate) {
454
- return this.Refund.getRawRefundFee(swapData, feeRate);
455
- }
456
- getExtraData(outputScript, amount, confirmations, nonce) {
457
- return buffer_1.Buffer.from((0, sha2_1.sha256)(buffer_1.Buffer.concat([
458
- base_1.BigIntBufferUtils.toBuffer(amount, "le", 8),
459
- outputScript
460
- ])));
461
- }
462
- }
463
- exports.SolanaSwapProgram = SolanaSwapProgram;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SolanaSwapProgram = void 0;
4
+ const SolanaSwapData_1 = require("./SolanaSwapData");
5
+ const web3_js_1 = require("@solana/web3.js");
6
+ const sha2_1 = require("@noble/hashes/sha2");
7
+ const programIdl = require("./programIdl.json");
8
+ const base_1 = require("@atomiqlabs/base");
9
+ const spl_token_1 = require("@solana/spl-token");
10
+ const SolanaProgramBase_1 = require("../program/SolanaProgramBase");
11
+ const SwapInit_1 = require("./modules/SwapInit");
12
+ const SolanaDataAccount_1 = require("./modules/SolanaDataAccount");
13
+ const SwapRefund_1 = require("./modules/SwapRefund");
14
+ const SwapClaim_1 = require("./modules/SwapClaim");
15
+ const SolanaLpVault_1 = require("./modules/SolanaLpVault");
16
+ const buffer_1 = require("buffer");
17
+ const Utils_1 = require("../../utils/Utils");
18
+ const SolanaTokens_1 = require("../chain/modules/SolanaTokens");
19
+ const BN = require("bn.js");
20
+ function toPublicKeyOrNull(str) {
21
+ return str == null ? null : new web3_js_1.PublicKey(str);
22
+ }
23
+ class SolanaSwapProgram extends SolanaProgramBase_1.SolanaProgramBase {
24
+ constructor(chainInterface, btcRelay, storage, programAddress) {
25
+ super(chainInterface, programIdl, programAddress);
26
+ ////////////////////////
27
+ //// Constants
28
+ this.ESCROW_STATE_RENT_EXEMPT = 2658720;
29
+ ////////////////////////
30
+ //// PDA accessors
31
+ this.SwapVaultAuthority = this.pda("authority");
32
+ this.SwapVault = this.pda("vault", (tokenAddress) => [tokenAddress.toBuffer()]);
33
+ this.SwapUserVault = this.pda("uservault", (publicKey, tokenAddress) => [publicKey.toBuffer(), tokenAddress.toBuffer()]);
34
+ this.SwapEscrowState = this.pda("state", (hash) => [hash]);
35
+ ////////////////////////
36
+ //// Timeouts
37
+ this.chainId = "SOLANA";
38
+ this.claimWithSecretTimeout = 45;
39
+ this.claimWithTxDataTimeout = 120;
40
+ this.refundTimeout = 45;
41
+ this.claimGracePeriod = 10 * 60;
42
+ this.refundGracePeriod = 10 * 60;
43
+ this.authGracePeriod = 5 * 60;
44
+ this.Init = new SwapInit_1.SwapInit(chainInterface, this);
45
+ this.Refund = new SwapRefund_1.SwapRefund(chainInterface, this);
46
+ this.Claim = new SwapClaim_1.SwapClaim(chainInterface, this, btcRelay);
47
+ this.DataAccount = new SolanaDataAccount_1.SolanaDataAccount(chainInterface, this, storage);
48
+ this.LpVault = new SolanaLpVault_1.SolanaLpVault(chainInterface, this);
49
+ }
50
+ async start() {
51
+ await this.DataAccount.init();
52
+ }
53
+ getClaimableDeposits(signer) {
54
+ return this.DataAccount.getDataAccountsInfo(new web3_js_1.PublicKey(signer));
55
+ }
56
+ claimDeposits(signer) {
57
+ return this.DataAccount.sweepDataAccounts(signer);
58
+ }
59
+ ////////////////////////////////////////////
60
+ //// Signatures
61
+ preFetchForInitSignatureVerification(data) {
62
+ return this.Init.preFetchForInitSignatureVerification(data);
63
+ }
64
+ preFetchBlockDataForSignatures() {
65
+ return this.Init.preFetchBlockDataForSignatures();
66
+ }
67
+ getInitSignature(signer, swapData, authorizationTimeout, preFetchedBlockData, feeRate) {
68
+ return this.Init.signSwapInitialization(signer, swapData, authorizationTimeout, preFetchedBlockData, feeRate);
69
+ }
70
+ isValidInitAuthorization(signer, swapData, { timeout, prefix, signature }, feeRate, preFetchedData) {
71
+ return this.Init.isSignatureValid(signer, swapData, timeout, prefix, signature, feeRate, preFetchedData);
72
+ }
73
+ getInitAuthorizationExpiry(swapData, { timeout, prefix, signature }, preFetchedData) {
74
+ return this.Init.getSignatureExpiry(timeout, signature, preFetchedData);
75
+ }
76
+ isInitAuthorizationExpired(swapData, { timeout, prefix, signature }) {
77
+ return this.Init.isSignatureExpired(signature, timeout);
78
+ }
79
+ getRefundSignature(signer, swapData, authorizationTimeout) {
80
+ return this.Refund.signSwapRefund(signer, swapData, authorizationTimeout);
81
+ }
82
+ isValidRefundAuthorization(swapData, { timeout, prefix, signature }) {
83
+ return this.Refund.isSignatureValid(swapData, timeout, prefix, signature);
84
+ }
85
+ getDataSignature(signer, data) {
86
+ return this.Chain.Signatures.getDataSignature(signer, data);
87
+ }
88
+ isValidDataSignature(data, signature, publicKey) {
89
+ return this.Chain.Signatures.isValidDataSignature(data, signature, publicKey);
90
+ }
91
+ ////////////////////////////////////////////
92
+ //// Swap data utils
93
+ /**
94
+ * Checks whether the claim is claimable by us, that means not expired, we are claimer & the swap is commited
95
+ *
96
+ * @param signer
97
+ * @param data
98
+ */
99
+ async isClaimable(signer, data) {
100
+ if (!data.isClaimer(signer))
101
+ return false;
102
+ if (await this.isExpired(signer, data))
103
+ return false;
104
+ return await this.isCommited(data);
105
+ }
106
+ /**
107
+ * Checks whether a swap is commited, i.e. the swap still exists on-chain and was not claimed nor refunded
108
+ *
109
+ * @param swapData
110
+ */
111
+ async isCommited(swapData) {
112
+ const paymentHash = buffer_1.Buffer.from(swapData.paymentHash, "hex");
113
+ const account = await this.program.account.escrowState.fetchNullable(this.SwapEscrowState(paymentHash));
114
+ if (account == null)
115
+ return false;
116
+ return swapData.correctPDA(account);
117
+ }
118
+ /**
119
+ * Checks whether the swap is expired, takes into consideration possible on-chain time skew, therefore for claimer
120
+ * the swap expires a bit sooner than it should've & for the offerer it expires a bit later
121
+ *
122
+ * @param signer
123
+ * @param data
124
+ */
125
+ isExpired(signer, data) {
126
+ let currentTimestamp = new BN(Math.floor(Date.now() / 1000));
127
+ if (data.isClaimer(signer))
128
+ currentTimestamp = currentTimestamp.add(new BN(this.claimGracePeriod));
129
+ if (data.isOfferer(signer))
130
+ currentTimestamp = currentTimestamp.sub(new BN(this.refundGracePeriod));
131
+ return Promise.resolve(data.expiry.lt(currentTimestamp));
132
+ }
133
+ /**
134
+ * Checks if the swap is refundable by us, checks if we are offerer, if the swap is already expired & if the swap
135
+ * is still commited
136
+ *
137
+ * @param signer
138
+ * @param data
139
+ */
140
+ async isRequestRefundable(signer, data) {
141
+ //Swap can only be refunded by the offerer
142
+ if (!data.isOfferer(signer))
143
+ return false;
144
+ if (!(await this.isExpired(signer, data)))
145
+ return false;
146
+ return await this.isCommited(data);
147
+ }
148
+ /**
149
+ * Get the swap payment hash to be used for an on-chain swap, this just uses a sha256 hash of the values
150
+ *
151
+ * @param outputScript output script required to claim the swap
152
+ * @param amount sats sent required to claim the swap
153
+ * @param confirmations
154
+ * @param nonce swap nonce uniquely identifying the transaction to prevent replay attacks
155
+ */
156
+ getHashForOnchain(outputScript, amount, confirmations, nonce) {
157
+ nonce ?? (nonce = 0n);
158
+ const paymentHash = buffer_1.Buffer.from((0, sha2_1.sha256)(buffer_1.Buffer.concat([
159
+ base_1.BigIntBufferUtils.toBuffer(nonce, "le", 8),
160
+ base_1.BigIntBufferUtils.toBuffer(amount, "le", 8),
161
+ outputScript
162
+ ]))).toString("hex");
163
+ return buffer_1.Buffer.from((0, Utils_1.toClaimHash)(paymentHash, nonce, confirmations), "hex");
164
+ }
165
+ getHashForHtlc(swapHash) {
166
+ return buffer_1.Buffer.from((0, Utils_1.toClaimHash)(swapHash.toString("hex"), 0n, 0), "hex");
167
+ }
168
+ getHashForTxId(txId, confirmations) {
169
+ return buffer_1.Buffer.from((0, Utils_1.toClaimHash)(buffer_1.Buffer.from(txId, "hex").reverse().toString("hex"), 0n, confirmations), "hex");
170
+ }
171
+ ////////////////////////////////////////////
172
+ //// Swap data getters
173
+ /**
174
+ * Gets the status of the specific swap, this also checks if we are offerer/claimer & checks for expiry (to see
175
+ * if swap is refundable)
176
+ *
177
+ * @param signer
178
+ * @param data
179
+ */
180
+ async getCommitStatus(signer, data) {
181
+ const escrowStateKey = this.SwapEscrowState(buffer_1.Buffer.from(data.paymentHash, "hex"));
182
+ const [escrowState, isExpired] = await Promise.all([
183
+ this.program.account.escrowState.fetchNullable(escrowStateKey),
184
+ this.isExpired(signer, data)
185
+ ]);
186
+ if (escrowState != null) {
187
+ if (data.correctPDA(escrowState)) {
188
+ if (data.isOfferer(signer) && isExpired)
189
+ return { type: base_1.SwapCommitStateType.REFUNDABLE };
190
+ return { type: base_1.SwapCommitStateType.COMMITED };
191
+ }
192
+ if (data.isOfferer(signer) && isExpired)
193
+ return { type: base_1.SwapCommitStateType.EXPIRED };
194
+ return { type: base_1.SwapCommitStateType.NOT_COMMITED };
195
+ }
196
+ //Check if paid or what
197
+ const status = await this.Events.findInEvents(escrowStateKey, async (event, info) => {
198
+ if (event.name === "ClaimEvent") {
199
+ const paymentHash = buffer_1.Buffer.from(event.data.hash).toString("hex");
200
+ if (paymentHash !== data.paymentHash)
201
+ return null;
202
+ if (!event.data.sequence.eq(data.sequence))
203
+ return null;
204
+ return {
205
+ type: base_1.SwapCommitStateType.PAID,
206
+ getClaimTxId: () => Promise.resolve(info.signature),
207
+ getClaimResult: () => Promise.resolve(buffer_1.Buffer.from(event.data.secret).toString("hex")),
208
+ getTxBlock: async () => {
209
+ return {
210
+ blockHeight: (await this.Chain.Blocks.getParsedBlock(info.slot)).blockHeight,
211
+ blockTime: info.blockTime
212
+ };
213
+ }
214
+ };
215
+ }
216
+ if (event.name === "RefundEvent") {
217
+ const paymentHash = buffer_1.Buffer.from(event.data.hash).toString("hex");
218
+ if (paymentHash !== data.paymentHash)
219
+ return null;
220
+ if (!event.data.sequence.eq(data.sequence))
221
+ return null;
222
+ return {
223
+ type: isExpired ? base_1.SwapCommitStateType.EXPIRED : base_1.SwapCommitStateType.NOT_COMMITED,
224
+ getRefundTxId: () => Promise.resolve(info.signature),
225
+ getTxBlock: async () => {
226
+ return {
227
+ blockHeight: (await this.Chain.Blocks.getParsedBlock(info.slot)).blockHeight,
228
+ blockTime: info.blockTime
229
+ };
230
+ }
231
+ };
232
+ }
233
+ });
234
+ if (status != null)
235
+ return status;
236
+ if (isExpired)
237
+ return { type: base_1.SwapCommitStateType.EXPIRED };
238
+ return { type: base_1.SwapCommitStateType.NOT_COMMITED };
239
+ }
240
+ /**
241
+ * Checks the status of the specific payment hash
242
+ *
243
+ * @param claimHash
244
+ */
245
+ async getClaimHashStatus(claimHash) {
246
+ const { paymentHash } = (0, Utils_1.fromClaimHash)(claimHash);
247
+ const escrowStateKey = this.SwapEscrowState(buffer_1.Buffer.from(paymentHash, "hex"));
248
+ const abortController = new AbortController();
249
+ //Start fetching events before checking escrow PDA, this call is used when quoting, so saving 100ms here helps a lot!
250
+ const eventsPromise = this.Events.findInEvents(escrowStateKey, async (event) => {
251
+ if (event.name === "ClaimEvent")
252
+ return base_1.SwapCommitStateType.PAID;
253
+ if (event.name === "RefundEvent")
254
+ return base_1.SwapCommitStateType.NOT_COMMITED;
255
+ }, abortController.signal).catch(e => {
256
+ abortController.abort(e);
257
+ return null;
258
+ });
259
+ const escrowState = await this.program.account.escrowState.fetchNullable(escrowStateKey);
260
+ abortController.signal.throwIfAborted();
261
+ if (escrowState != null) {
262
+ abortController.abort();
263
+ return base_1.SwapCommitStateType.COMMITED;
264
+ }
265
+ //Check if paid or what
266
+ const eventsStatus = await eventsPromise;
267
+ abortController.signal.throwIfAborted();
268
+ if (eventsStatus != null)
269
+ return eventsStatus;
270
+ return base_1.SwapCommitStateType.NOT_COMMITED;
271
+ }
272
+ /**
273
+ * Returns the data committed for a specific payment hash, or null if no data is currently commited for
274
+ * the specific swap
275
+ *
276
+ * @param claimHashHex
277
+ */
278
+ async getCommitedData(claimHashHex) {
279
+ const { paymentHash } = (0, Utils_1.fromClaimHash)(claimHashHex);
280
+ const paymentHashBuffer = buffer_1.Buffer.from(paymentHash, "hex");
281
+ const account = await this.program.account.escrowState.fetchNullable(this.SwapEscrowState(paymentHashBuffer));
282
+ if (account == null)
283
+ return null;
284
+ return SolanaSwapData_1.SolanaSwapData.fromEscrowState(account);
285
+ }
286
+ ////////////////////////////////////////////
287
+ //// Swap data initializer
288
+ createSwapData(type, offerer, claimer, token, amount, claimHash, sequence, expiry, payIn, payOut, securityDeposit, claimerBounty, depositToken) {
289
+ if (depositToken != null) {
290
+ if (!new web3_js_1.PublicKey(depositToken).equals(SolanaTokens_1.SolanaTokens.WSOL_ADDRESS))
291
+ throw new Error("Only SOL supported as deposit token!");
292
+ }
293
+ const tokenAddr = new web3_js_1.PublicKey(token);
294
+ const offererKey = offerer == null ? null : new web3_js_1.PublicKey(offerer);
295
+ const claimerKey = claimer == null ? null : new web3_js_1.PublicKey(claimer);
296
+ const { paymentHash, nonce, confirmations } = (0, Utils_1.fromClaimHash)(claimHash);
297
+ return Promise.resolve(new SolanaSwapData_1.SolanaSwapData(offererKey, claimerKey, tokenAddr, (0, Utils_1.toBN)(amount), paymentHash, (0, Utils_1.toBN)(sequence), (0, Utils_1.toBN)(expiry), nonce, confirmations, payOut, type == null ? null : SolanaSwapData_1.SolanaSwapData.typeToKind(type), payIn, offererKey == null ? null : payIn ? (0, spl_token_1.getAssociatedTokenAddressSync)(tokenAddr, offererKey) : web3_js_1.PublicKey.default, claimerKey == null ? null : payOut ? (0, spl_token_1.getAssociatedTokenAddressSync)(tokenAddr, claimerKey) : web3_js_1.PublicKey.default, (0, Utils_1.toBN)(securityDeposit), (0, Utils_1.toBN)(claimerBounty), null));
298
+ }
299
+ ////////////////////////////////////////////
300
+ //// Utils
301
+ async getBalance(signer, tokenAddress, inContract) {
302
+ if (!inContract) {
303
+ return await this.Chain.getBalance(signer, tokenAddress);
304
+ }
305
+ const token = new web3_js_1.PublicKey(tokenAddress);
306
+ const publicKey = new web3_js_1.PublicKey(signer);
307
+ return await this.getIntermediaryBalance(publicKey, token);
308
+ }
309
+ getIntermediaryData(address, token) {
310
+ return this.LpVault.getIntermediaryData(new web3_js_1.PublicKey(address), new web3_js_1.PublicKey(token));
311
+ }
312
+ getIntermediaryReputation(address, token) {
313
+ return this.LpVault.getIntermediaryReputation(new web3_js_1.PublicKey(address), new web3_js_1.PublicKey(token));
314
+ }
315
+ getIntermediaryBalance(address, token) {
316
+ return this.LpVault.getIntermediaryBalance(address, token);
317
+ }
318
+ ////////////////////////////////////////////
319
+ //// Transaction initializers
320
+ async txsClaimWithSecret(signer, swapData, secret, checkExpiry, initAta, feeRate, skipAtaCheck) {
321
+ return this.Claim.txsClaimWithSecret(typeof (signer) === "string" ? new web3_js_1.PublicKey(signer) : signer.getPublicKey(), swapData, secret, checkExpiry, initAta, feeRate, skipAtaCheck);
322
+ }
323
+ async txsClaimWithTxData(signer, swapData, tx, requiredConfirmations, vout, commitedHeader, synchronizer, initAta, feeRate, storageAccHolder) {
324
+ if (swapData.confirmations !== requiredConfirmations)
325
+ throw new Error("Invalid requiredConfirmations provided!");
326
+ return this.Claim.txsClaimWithTxData(typeof (signer) === "string" ? new web3_js_1.PublicKey(signer) : signer, swapData, tx, vout, commitedHeader, synchronizer, initAta, storageAccHolder, feeRate);
327
+ }
328
+ txsRefund(signer, swapData, check, initAta, feeRate) {
329
+ if (!swapData.isOfferer(signer))
330
+ throw new Error("Only offerer can refund on Solana");
331
+ return this.Refund.txsRefund(swapData, check, initAta, feeRate);
332
+ }
333
+ txsRefundWithAuthorization(signer, swapData, { timeout, prefix, signature }, check, initAta, feeRate) {
334
+ if (!swapData.isOfferer(signer))
335
+ throw new Error("Only offerer can refund on Solana");
336
+ return this.Refund.txsRefundWithAuthorization(swapData, timeout, prefix, signature, check, initAta, feeRate);
337
+ }
338
+ txsInit(sender, swapData, { timeout, prefix, signature }, skipChecks, feeRate) {
339
+ if (swapData.isPayIn()) {
340
+ if (!swapData.isOfferer(sender))
341
+ throw new Error("Only offerer can create payIn=true swap");
342
+ return this.Init.txsInitPayIn(swapData, timeout, prefix, signature, skipChecks, feeRate);
343
+ }
344
+ else {
345
+ if (!swapData.isClaimer(sender))
346
+ throw new Error("Only claimer can create payIn=false swap");
347
+ return this.Init.txsInit(swapData, timeout, prefix, signature, skipChecks, feeRate);
348
+ }
349
+ }
350
+ txsWithdraw(signer, token, amount, feeRate) {
351
+ return this.LpVault.txsWithdraw(new web3_js_1.PublicKey(signer), new web3_js_1.PublicKey(token), amount, feeRate);
352
+ }
353
+ txsDeposit(signer, token, amount, feeRate) {
354
+ return this.LpVault.txsDeposit(new web3_js_1.PublicKey(signer), new web3_js_1.PublicKey(token), amount, feeRate);
355
+ }
356
+ ////////////////////////////////////////////
357
+ //// Executors
358
+ async claimWithSecret(signer, swapData, secret, checkExpiry, initAta, txOptions) {
359
+ const result = await this.Claim.txsClaimWithSecret(signer.getPublicKey(), swapData, secret, checkExpiry, initAta, txOptions?.feeRate);
360
+ const [signature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
361
+ return signature;
362
+ }
363
+ async claimWithTxData(signer, swapData, tx, requiredConfirmations, vout, commitedHeader, synchronizer, initAta, txOptions) {
364
+ if (requiredConfirmations !== swapData.confirmations)
365
+ throw new Error("Invalid requiredConfirmations provided!");
366
+ const data = {
367
+ storageAcc: null
368
+ };
369
+ const txs = await this.Claim.txsClaimWithTxData(signer, swapData, tx, vout, commitedHeader, synchronizer, initAta, data, txOptions?.feeRate);
370
+ if (txs === null)
371
+ throw new Error("Btc relay not synchronized to required blockheight!");
372
+ //TODO: This doesn't return proper tx signature
373
+ const [signature] = await this.Chain.sendAndConfirm(signer, txs, txOptions?.waitForConfirmation, txOptions?.abortSignal);
374
+ await this.DataAccount.removeDataAccount(data.storageAcc);
375
+ return signature;
376
+ }
377
+ async refund(signer, swapData, check, initAta, txOptions) {
378
+ let result = await this.txsRefund(signer.getAddress(), swapData, check, initAta, txOptions?.feeRate);
379
+ const [signature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
380
+ return signature;
381
+ }
382
+ async refundWithAuthorization(signer, swapData, signature, check, initAta, txOptions) {
383
+ let result = await this.txsRefundWithAuthorization(signer.getAddress(), swapData, signature, check, initAta, txOptions?.feeRate);
384
+ const [txSignature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
385
+ return txSignature;
386
+ }
387
+ async init(signer, swapData, signature, skipChecks, txOptions) {
388
+ if (swapData.isPayIn()) {
389
+ if (!signer.getPublicKey().equals(swapData.offerer))
390
+ throw new Error("Invalid signer provided!");
391
+ }
392
+ else {
393
+ if (!signer.getPublicKey().equals(swapData.claimer))
394
+ throw new Error("Invalid signer provided!");
395
+ }
396
+ const result = await this.txsInit(signer.getAddress(), swapData, signature, skipChecks, txOptions?.feeRate);
397
+ const [txSignature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
398
+ return txSignature;
399
+ }
400
+ async initAndClaimWithSecret(signer, swapData, signature, secret, skipChecks, txOptions) {
401
+ if (!signer.getPublicKey().equals(swapData.claimer))
402
+ throw new Error("Invalid signer provided!");
403
+ const txsCommit = await this.txsInit(signer.getAddress(), swapData, signature, skipChecks, txOptions?.feeRate);
404
+ const txsClaim = await this.Claim.txsClaimWithSecret(signer.getPublicKey(), swapData, secret, true, false, txOptions?.feeRate, true);
405
+ return await this.Chain.sendAndConfirm(signer, txsCommit.concat(txsClaim), txOptions?.waitForConfirmation, txOptions?.abortSignal);
406
+ }
407
+ async withdraw(signer, token, amount, txOptions) {
408
+ const txs = await this.LpVault.txsWithdraw(signer.getPublicKey(), new web3_js_1.PublicKey(token), amount, txOptions?.feeRate);
409
+ const [txId] = await this.Chain.sendAndConfirm(signer, txs, txOptions?.waitForConfirmation, txOptions?.abortSignal, false);
410
+ return txId;
411
+ }
412
+ async deposit(signer, token, amount, txOptions) {
413
+ const txs = await this.LpVault.txsDeposit(signer.getPublicKey(), new web3_js_1.PublicKey(token), amount, txOptions?.feeRate);
414
+ const [txId] = await this.Chain.sendAndConfirm(signer, txs, txOptions?.waitForConfirmation, txOptions?.abortSignal, false);
415
+ return txId;
416
+ }
417
+ ////////////////////////////////////////////
418
+ //// Fees
419
+ getInitPayInFeeRate(offerer, claimer, token, claimHash) {
420
+ const paymentHash = claimHash == null ? null : (0, Utils_1.fromClaimHash)(claimHash).paymentHash;
421
+ return this.Init.getInitPayInFeeRate(toPublicKeyOrNull(offerer), toPublicKeyOrNull(claimer), toPublicKeyOrNull(token), paymentHash);
422
+ }
423
+ getInitFeeRate(offerer, claimer, token, claimHash) {
424
+ const paymentHash = claimHash == null ? null : (0, Utils_1.fromClaimHash)(claimHash).paymentHash;
425
+ return this.Init.getInitFeeRate(toPublicKeyOrNull(offerer), toPublicKeyOrNull(claimer), toPublicKeyOrNull(token), paymentHash);
426
+ }
427
+ getRefundFeeRate(swapData) {
428
+ return this.Refund.getRefundFeeRate(swapData);
429
+ }
430
+ getClaimFeeRate(signer, swapData) {
431
+ return this.Claim.getClaimFeeRate(new web3_js_1.PublicKey(signer), swapData);
432
+ }
433
+ getClaimFee(signer, swapData, feeRate) {
434
+ return this.Claim.getClaimFee(new web3_js_1.PublicKey(signer), swapData, feeRate);
435
+ }
436
+ getRawClaimFee(signer, swapData, feeRate) {
437
+ return this.Claim.getRawClaimFee(new web3_js_1.PublicKey(signer), swapData, feeRate);
438
+ }
439
+ /**
440
+ * Get the estimated solana fee of the commit transaction
441
+ */
442
+ getCommitFee(swapData, feeRate) {
443
+ return this.Init.getInitFee(swapData, feeRate);
444
+ }
445
+ /**
446
+ * Get the estimated solana fee of the commit transaction, without any deposits
447
+ */
448
+ getRawCommitFee(swapData, feeRate) {
449
+ return this.Init.getRawInitFee(swapData, feeRate);
450
+ }
451
+ /**
452
+ * Get the estimated solana transaction fee of the refund transaction
453
+ */
454
+ getRefundFee(swapData, feeRate) {
455
+ return this.Refund.getRefundFee(swapData, feeRate);
456
+ }
457
+ /**
458
+ * Get the estimated solana transaction fee of the refund transaction
459
+ */
460
+ getRawRefundFee(swapData, feeRate) {
461
+ return this.Refund.getRawRefundFee(swapData, feeRate);
462
+ }
463
+ getExtraData(outputScript, amount, confirmations, nonce) {
464
+ return buffer_1.Buffer.from((0, sha2_1.sha256)(buffer_1.Buffer.concat([
465
+ base_1.BigIntBufferUtils.toBuffer(amount, "le", 8),
466
+ outputScript
467
+ ])));
468
+ }
469
+ }
470
+ exports.SolanaSwapProgram = SolanaSwapProgram;