@atomiqlabs/lp-lib 16.1.0 → 16.1.1

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 (167) hide show
  1. package/LICENSE +201 -201
  2. package/dist/fees/IBtcFeeEstimator.d.ts +3 -3
  3. package/dist/fees/IBtcFeeEstimator.js +2 -2
  4. package/dist/index.d.ts +42 -42
  5. package/dist/index.js +58 -58
  6. package/dist/info/InfoHandler.d.ts +17 -17
  7. package/dist/info/InfoHandler.js +60 -60
  8. package/dist/plugins/IPlugin.d.ts +144 -144
  9. package/dist/plugins/IPlugin.js +34 -34
  10. package/dist/plugins/PluginManager.d.ts +113 -113
  11. package/dist/plugins/PluginManager.js +274 -274
  12. package/dist/prices/BinanceSwapPrice.d.ts +29 -29
  13. package/dist/prices/BinanceSwapPrice.js +79 -79
  14. package/dist/prices/CoinGeckoSwapPrice.d.ts +33 -33
  15. package/dist/prices/CoinGeckoSwapPrice.js +51 -51
  16. package/dist/prices/ISwapPrice.d.ts +43 -43
  17. package/dist/prices/ISwapPrice.js +55 -55
  18. package/dist/prices/OKXSwapPrice.d.ts +29 -29
  19. package/dist/prices/OKXSwapPrice.js +79 -79
  20. package/dist/storage/IIntermediaryStorage.d.ts +18 -18
  21. package/dist/storage/IIntermediaryStorage.js +2 -2
  22. package/dist/storagemanager/IntermediaryStorageManager.d.ts +19 -19
  23. package/dist/storagemanager/IntermediaryStorageManager.js +111 -111
  24. package/dist/storagemanager/StorageManager.d.ts +13 -13
  25. package/dist/storagemanager/StorageManager.js +64 -64
  26. package/dist/swaps/SwapHandler.d.ts +171 -171
  27. package/dist/swaps/SwapHandler.js +217 -217
  28. package/dist/swaps/SwapHandlerSwap.d.ts +79 -79
  29. package/dist/swaps/SwapHandlerSwap.js +78 -78
  30. package/dist/swaps/assertions/AmountAssertions.d.ts +28 -28
  31. package/dist/swaps/assertions/AmountAssertions.js +74 -74
  32. package/dist/swaps/assertions/FromBtcAmountAssertions.d.ts +76 -76
  33. package/dist/swaps/assertions/FromBtcAmountAssertions.js +185 -185
  34. package/dist/swaps/assertions/LightningAssertions.d.ts +44 -44
  35. package/dist/swaps/assertions/LightningAssertions.js +86 -86
  36. package/dist/swaps/assertions/ToBtcAmountAssertions.d.ts +53 -53
  37. package/dist/swaps/assertions/ToBtcAmountAssertions.js +150 -150
  38. package/dist/swaps/escrow/EscrowHandler.d.ts +50 -50
  39. package/dist/swaps/escrow/EscrowHandler.js +151 -151
  40. package/dist/swaps/escrow/EscrowHandlerSwap.d.ts +35 -35
  41. package/dist/swaps/escrow/EscrowHandlerSwap.js +69 -69
  42. package/dist/swaps/escrow/FromBtcBaseSwap.d.ts +14 -14
  43. package/dist/swaps/escrow/FromBtcBaseSwap.js +32 -32
  44. package/dist/swaps/escrow/FromBtcBaseSwapHandler.d.ts +102 -102
  45. package/dist/swaps/escrow/FromBtcBaseSwapHandler.js +210 -210
  46. package/dist/swaps/escrow/ToBtcBaseSwap.d.ts +36 -36
  47. package/dist/swaps/escrow/ToBtcBaseSwap.js +67 -67
  48. package/dist/swaps/escrow/ToBtcBaseSwapHandler.d.ts +53 -53
  49. package/dist/swaps/escrow/ToBtcBaseSwapHandler.js +81 -81
  50. package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.d.ts +84 -84
  51. package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.js +322 -322
  52. package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.d.ts +21 -21
  53. package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.js +50 -50
  54. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.d.ts +108 -108
  55. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.js +695 -695
  56. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +33 -33
  57. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.js +91 -91
  58. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.d.ts +112 -112
  59. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.js +708 -708
  60. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.d.ts +55 -55
  61. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.js +120 -120
  62. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.d.ts +170 -170
  63. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.js +745 -745
  64. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.d.ts +28 -28
  65. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.js +64 -64
  66. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.d.ts +178 -178
  67. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.js +899 -899
  68. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +24 -24
  69. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.js +58 -58
  70. package/dist/swaps/spv_vault_swap/SpvVault.d.ts +44 -44
  71. package/dist/swaps/spv_vault_swap/SpvVault.js +145 -145
  72. package/dist/swaps/spv_vault_swap/SpvVaultSwap.d.ts +68 -68
  73. package/dist/swaps/spv_vault_swap/SpvVaultSwap.js +158 -158
  74. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.d.ts +68 -68
  75. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.js +561 -561
  76. package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +63 -63
  77. package/dist/swaps/spv_vault_swap/SpvVaults.js +491 -491
  78. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.d.ts +52 -52
  79. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.js +662 -662
  80. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.d.ts +52 -52
  81. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.js +118 -118
  82. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.d.ts +77 -77
  83. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.js +504 -504
  84. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.d.ts +34 -34
  85. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.js +81 -81
  86. package/dist/utils/BitcoinUtils.d.ts +4 -4
  87. package/dist/utils/BitcoinUtils.js +61 -61
  88. package/dist/utils/Utils.d.ts +29 -29
  89. package/dist/utils/Utils.js +89 -89
  90. package/dist/utils/paramcoders/IParamReader.d.ts +5 -5
  91. package/dist/utils/paramcoders/IParamReader.js +2 -2
  92. package/dist/utils/paramcoders/IParamWriter.d.ts +4 -4
  93. package/dist/utils/paramcoders/IParamWriter.js +2 -2
  94. package/dist/utils/paramcoders/LegacyParamEncoder.d.ts +10 -10
  95. package/dist/utils/paramcoders/LegacyParamEncoder.js +22 -22
  96. package/dist/utils/paramcoders/ParamDecoder.d.ts +25 -25
  97. package/dist/utils/paramcoders/ParamDecoder.js +222 -222
  98. package/dist/utils/paramcoders/ParamEncoder.d.ts +9 -9
  99. package/dist/utils/paramcoders/ParamEncoder.js +22 -22
  100. package/dist/utils/paramcoders/SchemaVerifier.d.ts +21 -21
  101. package/dist/utils/paramcoders/SchemaVerifier.js +84 -84
  102. package/dist/utils/paramcoders/server/ServerParamDecoder.d.ts +8 -8
  103. package/dist/utils/paramcoders/server/ServerParamDecoder.js +107 -107
  104. package/dist/utils/paramcoders/server/ServerParamEncoder.d.ts +11 -11
  105. package/dist/utils/paramcoders/server/ServerParamEncoder.js +65 -65
  106. package/dist/wallets/IBitcoinWallet.d.ts +74 -74
  107. package/dist/wallets/IBitcoinWallet.js +2 -2
  108. package/dist/wallets/ILightningWallet.d.ts +117 -117
  109. package/dist/wallets/ILightningWallet.js +37 -37
  110. package/dist/wallets/ISpvVaultSigner.d.ts +7 -7
  111. package/dist/wallets/ISpvVaultSigner.js +2 -2
  112. package/package.json +36 -36
  113. package/src/fees/IBtcFeeEstimator.ts +6 -6
  114. package/src/index.ts +53 -53
  115. package/src/info/InfoHandler.ts +103 -103
  116. package/src/plugins/IPlugin.ts +174 -174
  117. package/src/plugins/PluginManager.ts +354 -354
  118. package/src/prices/BinanceSwapPrice.ts +101 -101
  119. package/src/prices/CoinGeckoSwapPrice.ts +75 -75
  120. package/src/prices/ISwapPrice.ts +88 -88
  121. package/src/prices/OKXSwapPrice.ts +101 -101
  122. package/src/storage/IIntermediaryStorage.ts +19 -19
  123. package/src/storagemanager/IntermediaryStorageManager.ts +118 -118
  124. package/src/storagemanager/StorageManager.ts +78 -78
  125. package/src/swaps/SwapHandler.ts +323 -323
  126. package/src/swaps/SwapHandlerSwap.ts +141 -141
  127. package/src/swaps/assertions/AmountAssertions.ts +77 -77
  128. package/src/swaps/assertions/FromBtcAmountAssertions.ts +251 -251
  129. package/src/swaps/assertions/LightningAssertions.ts +103 -103
  130. package/src/swaps/assertions/ToBtcAmountAssertions.ts +203 -203
  131. package/src/swaps/escrow/EscrowHandler.ts +172 -172
  132. package/src/swaps/escrow/EscrowHandlerSwap.ts +86 -86
  133. package/src/swaps/escrow/FromBtcBaseSwap.ts +38 -38
  134. package/src/swaps/escrow/FromBtcBaseSwapHandler.ts +286 -286
  135. package/src/swaps/escrow/ToBtcBaseSwap.ts +85 -85
  136. package/src/swaps/escrow/ToBtcBaseSwapHandler.ts +129 -129
  137. package/src/swaps/escrow/frombtc_abstract/FromBtcAbs.ts +457 -457
  138. package/src/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.ts +61 -61
  139. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.ts +873 -873
  140. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +141 -141
  141. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.ts +866 -866
  142. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.ts +196 -196
  143. package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +920 -920
  144. package/src/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.ts +108 -108
  145. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +1149 -1149
  146. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.ts +80 -80
  147. package/src/swaps/spv_vault_swap/SpvVault.ts +178 -178
  148. package/src/swaps/spv_vault_swap/SpvVaultSwap.ts +228 -228
  149. package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +712 -712
  150. package/src/swaps/spv_vault_swap/SpvVaults.ts +567 -567
  151. package/src/swaps/trusted/frombtc_trusted/FromBtcTrusted.ts +762 -762
  152. package/src/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.ts +185 -185
  153. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +603 -603
  154. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.ts +121 -121
  155. package/src/utils/BitcoinUtils.ts +59 -59
  156. package/src/utils/Utils.ts +104 -104
  157. package/src/utils/paramcoders/IParamReader.ts +7 -7
  158. package/src/utils/paramcoders/IParamWriter.ts +8 -8
  159. package/src/utils/paramcoders/LegacyParamEncoder.ts +27 -27
  160. package/src/utils/paramcoders/ParamDecoder.ts +218 -218
  161. package/src/utils/paramcoders/ParamEncoder.ts +29 -29
  162. package/src/utils/paramcoders/SchemaVerifier.ts +96 -96
  163. package/src/utils/paramcoders/server/ServerParamDecoder.ts +118 -118
  164. package/src/utils/paramcoders/server/ServerParamEncoder.ts +75 -75
  165. package/src/wallets/IBitcoinWallet.ts +76 -76
  166. package/src/wallets/ILightningWallet.ts +200 -178
  167. package/src/wallets/ISpvVaultSigner.ts +10 -10
@@ -1,662 +1,662 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FromBtcTrusted = void 0;
4
- const FromBtcTrustedSwap_1 = require("./FromBtcTrustedSwap");
5
- const SwapHandler_1 = require("../../SwapHandler");
6
- const PluginManager_1 = require("../../../plugins/PluginManager");
7
- const Utils_1 = require("../../../utils/Utils");
8
- const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
9
- const FromBtcAmountAssertions_1 = require("../../assertions/FromBtcAmountAssertions");
10
- class FromBtcTrusted extends SwapHandler_1.SwapHandler {
11
- constructor(storageDirectory, path, chains, bitcoin, swapPricing, bitcoinRpc, config) {
12
- var _a;
13
- super(storageDirectory, path, chains, swapPricing);
14
- this.type = SwapHandler_1.SwapHandlerType.FROM_BTC_TRUSTED;
15
- this.inflightSwapStates = new Set([FromBtcTrustedSwap_1.FromBtcTrustedSwapState.RECEIVED, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.SENT, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CONFIRMED]);
16
- this.subscriptions = new Map();
17
- this.doubleSpendWatchdogSwaps = new Set();
18
- this.refundedSwaps = new Map();
19
- this.doubleSpentSwaps = new Map();
20
- this.processedTxIds = new Map();
21
- this.AmountAssertions = new FromBtcAmountAssertions_1.FromBtcAmountAssertions(config, swapPricing);
22
- this.config = config;
23
- (_a = this.config).recommendFeeMultiplier ?? (_a.recommendFeeMultiplier = 1.25);
24
- this.bitcoin = bitcoin;
25
- this.bitcoinRpc = bitcoinRpc;
26
- }
27
- getAllAncestors(tx) {
28
- return Promise.all(tx.ins.map(input => this.bitcoinRpc.getTransaction(input.txid).then(tx => {
29
- return { tx, vout: input.vout };
30
- })));
31
- }
32
- async refundSwap(swap) {
33
- if (swap.refundAddress == null) {
34
- if (swap.state !== FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDABLE) {
35
- await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDABLE);
36
- await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
37
- }
38
- return;
39
- }
40
- let unlock = swap.lock(30 * 1000);
41
- if (unlock == null)
42
- return;
43
- const feeRate = await this.bitcoin.getFeeRate();
44
- const ourOutput = swap.btcTx.outs[swap.vout];
45
- const resp = await this.bitcoin.drainAll(swap.refundAddress, [{
46
- type: this.bitcoin.getAddressType(),
47
- confirmations: swap.btcTx.confirmations,
48
- outputScript: Buffer.from(ourOutput.scriptPubKey.hex, "hex"),
49
- value: ourOutput.value,
50
- txId: swap.btcTx.txid,
51
- vout: swap.vout
52
- }], feeRate);
53
- if (resp == null) {
54
- this.swapLogger.error(swap, "refundSwap(): cannot refund swap because of dust limit, txId: " + swap.txId);
55
- unlock();
56
- return;
57
- }
58
- if (swap.metadata != null)
59
- swap.metadata.times.refundSignPSBT = Date.now();
60
- this.swapLogger.debug(swap, "refundSwap(): signed raw transaction: " + resp.raw);
61
- const refundTxId = resp.txId;
62
- swap.refundTxId = refundTxId;
63
- //Send the refund TX
64
- await this.bitcoin.sendRawTransaction(resp.raw);
65
- this.swapLogger.debug(swap, "refundSwap(): sent refund transaction: " + refundTxId);
66
- this.refundedSwaps.set(swap.getIdentifierHash(), refundTxId);
67
- await this.removeSwapData(swap, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDED);
68
- unlock();
69
- }
70
- async burn(swap) {
71
- const ourOutput = swap.btcTx.outs[swap.vout];
72
- //Check if we can even increase the feeRate by burning
73
- const txSize = 110;
74
- const burnTxFeeRate = Math.floor(ourOutput.value / txSize);
75
- const initialTxFeeRate = Math.ceil(swap.txFee / swap.txSize);
76
- if (burnTxFeeRate < initialTxFeeRate) {
77
- this.swapLogger.warn(swap, "burn(): cannot send burn transaction, pays too little fee, " +
78
- "initialTxId: " + swap.txId + " initialTxFeeRate: " + initialTxFeeRate + " burnTxFeeRate: " + burnTxFeeRate);
79
- this.doubleSpentSwaps.set(swap.getIdentifierHash(), null);
80
- await this.removeSwapData(swap, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.DOUBLE_SPENT);
81
- return;
82
- }
83
- //Construct PSBT
84
- const resp = await this.bitcoin.burnAll([{
85
- type: this.bitcoin.getAddressType(),
86
- confirmations: swap.btcTx.confirmations,
87
- outputScript: Buffer.from(ourOutput.scriptPubKey.hex, "hex"),
88
- value: ourOutput.value,
89
- txId: swap.btcTx.txid,
90
- vout: swap.vout
91
- }]);
92
- if (swap.metadata != null)
93
- swap.metadata.times.burnSignPSBT = Date.now();
94
- this.swapLogger.debug(swap, "burn(): signed raw transaction: " + resp.raw);
95
- const burnTxId = resp.txId;
96
- swap.burnTxId = burnTxId;
97
- //Send the original TX + our burn TX as a package
98
- const sendTxns = [swap.btcTx.raw, resp.raw];
99
- //TODO: We should handle this in a better way
100
- try {
101
- await this.bitcoinRpc.sendRawPackage(sendTxns);
102
- this.swapLogger.debug(swap, "burn(): sent burn transaction: " + burnTxId);
103
- }
104
- catch (e) {
105
- this.swapLogger.error(swap, "burn(): error sending burn package: ", e);
106
- }
107
- this.doubleSpentSwaps.set(swap.getIdentifierHash(), burnTxId);
108
- await this.removeSwapData(swap, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.DOUBLE_SPENT);
109
- }
110
- async processPastSwap(swap, tx, vout) {
111
- const foundVout = tx.outs[vout];
112
- const { chainInterface, signer } = this.getChain(swap.chainIdentifier);
113
- const outputScript = this.bitcoin.toOutputScript(swap.btcAddress).toString("hex");
114
- if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CREATED) {
115
- this.subscriptions.set(outputScript, swap);
116
- if (foundVout == null) {
117
- //Check expiry
118
- if (swap.expiresAt < Date.now()) {
119
- this.subscriptions.delete(outputScript);
120
- await this.bitcoin.addUnusedAddress(swap.btcAddress);
121
- await this.removeSwapData(swap, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.EXPIRED);
122
- return;
123
- }
124
- return;
125
- }
126
- const sentSats = BigInt(foundVout.value);
127
- if (sentSats === swap.amount) {
128
- swap.adjustedInput = swap.amount;
129
- swap.adjustedOutput = swap.outputTokens;
130
- }
131
- else {
132
- //If lower than minimum then ignore
133
- if (sentSats < this.config.min)
134
- return;
135
- if (sentSats > this.config.max) {
136
- swap.adjustedInput = sentSats;
137
- swap.btcTx = tx;
138
- swap.txId = tx.txid;
139
- swap.vout = vout;
140
- this.subscriptions.delete(outputScript);
141
- await this.refundSwap(swap);
142
- return;
143
- }
144
- //Adjust the amount
145
- swap.adjustedInput = sentSats;
146
- swap.adjustedOutput = swap.outputTokens * sentSats / swap.amount;
147
- }
148
- swap.btcTx = tx;
149
- swap.txId = tx.txid;
150
- swap.vout = vout;
151
- this.subscriptions.delete(outputScript);
152
- try {
153
- this.checkTooManyInflightSwaps();
154
- }
155
- catch (e) {
156
- await this.refundSwap(swap);
157
- return;
158
- }
159
- await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.RECEIVED);
160
- await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
161
- }
162
- if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.RECEIVED) {
163
- //Check if transaction still exists
164
- if (tx == null || foundVout == null || tx.txid !== swap.txId) {
165
- await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CREATED);
166
- await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
167
- return;
168
- }
169
- //Check if it is confirmed
170
- if (tx.confirmations > 0) {
171
- await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED);
172
- await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
173
- }
174
- else {
175
- //Check if it pays high enough fee AND has confirmed ancestors
176
- const ancestors = await this.getAllAncestors(tx);
177
- const allAncestorsConfirmed = ancestors.reduce((prev, curr) => prev && curr.tx.confirmations > 0, true);
178
- const totalInput = ancestors.reduce((prev, curr) => prev + curr.tx.outs[curr.vout].value, 0);
179
- const totalOutput = tx.outs.reduce((prev, curr) => prev + curr.value, 0);
180
- const fee = totalInput - totalOutput;
181
- const feePerVbyte = Math.ceil(fee / tx.vsize);
182
- if (allAncestorsConfirmed &&
183
- (feePerVbyte >= swap.recommendedFee || feePerVbyte >= await this.bitcoin.getFeeRate())) {
184
- if (swap.state !== FromBtcTrustedSwap_1.FromBtcTrustedSwapState.RECEIVED)
185
- return;
186
- swap.txSize = tx.vsize;
187
- swap.txFee = fee;
188
- await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED);
189
- await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
190
- }
191
- else {
192
- return;
193
- }
194
- }
195
- }
196
- if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDABLE) {
197
- if (swap.refundAddress != null) {
198
- await this.refundSwap(swap);
199
- return;
200
- }
201
- }
202
- if (swap.doubleSpent || tx == null || foundVout == null || tx.txid !== swap.txId) {
203
- if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDABLE) {
204
- await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CREATED);
205
- return;
206
- }
207
- if (!swap.doubleSpent) {
208
- swap.doubleSpent = true;
209
- try {
210
- await this.burn(swap);
211
- this.doubleSpendWatchdogSwaps.delete(swap);
212
- }
213
- catch (e) {
214
- this.swapLogger.error(swap, "processPastSwap(): Error burning swap: ", e);
215
- swap.doubleSpent = false;
216
- }
217
- }
218
- return;
219
- }
220
- else {
221
- if (tx.confirmations <= 0 && !this.doubleSpendWatchdogSwaps.has(swap)) {
222
- this.swapLogger.debug(swap, "processPastSwap(): Adding swap transaction to double spend watchdog list: ", swap.txId);
223
- this.doubleSpendWatchdogSwaps.add(swap);
224
- }
225
- }
226
- if (tx.confirmations > 0 && this.doubleSpendWatchdogSwaps.delete(swap)) {
227
- this.swapLogger.debug(swap, "processPastSwap(): Removing confirmed swap transaction from double spend watchdog list: ", swap.txId);
228
- }
229
- if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED) {
230
- //Send gas token
231
- const balance = chainInterface.getBalance(signer.getAddress(), swap.token);
232
- try {
233
- await this.checkBalance(swap.adjustedOutput, balance, null);
234
- if (swap.metadata != null)
235
- swap.metadata.times.receivedBalanceChecked = Date.now();
236
- }
237
- catch (e) {
238
- this.swapLogger.error(swap, "processPastSwap(): Error not enough balance: ", e);
239
- await this.refundSwap(swap);
240
- return;
241
- }
242
- if (swap.state !== FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED)
243
- return;
244
- let unlock = swap.lock(30 * 1000);
245
- if (unlock == null)
246
- return;
247
- const txns = await chainInterface.txsTransfer(signer.getAddress(), swap.token, swap.adjustedOutput, swap.dstAddress);
248
- await chainInterface.sendAndConfirm(signer, txns, true, null, false, async (txId, rawTx) => {
249
- swap.txIds = { init: txId };
250
- swap.scRawTx = rawTx;
251
- if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED) {
252
- await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.SENT);
253
- await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
254
- }
255
- if (unlock != null)
256
- unlock();
257
- unlock = null;
258
- });
259
- }
260
- if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.SENT) {
261
- const txStatus = await chainInterface.getTxStatus(swap.scRawTx);
262
- switch (txStatus) {
263
- case "not_found":
264
- //Retry
265
- swap.txIds = { init: null };
266
- swap.scRawTx = null;
267
- await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.RECEIVED);
268
- await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
269
- break;
270
- case "reverted":
271
- //Cancel invoice
272
- await this.refundSwap(swap);
273
- this.swapLogger.info(swap, "processPastSwap(): transaction reverted, refunding btc on-chain: ", swap.btcAddress);
274
- break;
275
- case "success":
276
- await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CONFIRMED);
277
- await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
278
- break;
279
- }
280
- }
281
- if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CONFIRMED) {
282
- this.processedTxIds.set(swap.getIdentifierHash(), {
283
- txId: swap.txId,
284
- scTxId: swap.txIds.init,
285
- adjustedAmount: swap.adjustedInput,
286
- adjustedTotal: swap.adjustedOutput
287
- });
288
- if (tx.confirmations > 0)
289
- await this.removeSwapData(swap, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.FINISHED);
290
- }
291
- }
292
- async processPastSwaps() {
293
- const queriedData = await this.storageManager.query([
294
- {
295
- key: "state",
296
- value: [
297
- FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDABLE,
298
- FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CREATED,
299
- FromBtcTrustedSwap_1.FromBtcTrustedSwapState.RECEIVED,
300
- FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED,
301
- FromBtcTrustedSwap_1.FromBtcTrustedSwapState.SENT,
302
- FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CONFIRMED
303
- ]
304
- }
305
- ]);
306
- const startingBlockheight = queriedData.reduce((prev, { obj: swap }) => Math.min(prev, swap.createdHeight), Infinity);
307
- if (startingBlockheight === Infinity)
308
- return;
309
- const transactions = await this.bitcoin.getWalletTransactions(startingBlockheight);
310
- const map = new Map();
311
- transactions.forEach(tx => {
312
- tx.outs.forEach((out, vout) => {
313
- const existing = map.get(out.scriptPubKey.hex);
314
- if (existing == null) {
315
- map.set(out.scriptPubKey.hex, [{ tx, vout }]);
316
- }
317
- else {
318
- existing.push({ tx, vout });
319
- }
320
- });
321
- });
322
- for (let { obj: swap } of queriedData) {
323
- const outputScript = this.bitcoin.toOutputScript(swap.btcAddress).toString("hex");
324
- const txs = map.get(outputScript) ?? [];
325
- try {
326
- await this.processPastSwap(swap, txs[0]?.tx, txs[0]?.vout);
327
- }
328
- catch (e) {
329
- this.swapLogger.error(swap, "processPastSwaps(): Error ocurred while processing swap: ", e);
330
- }
331
- }
332
- }
333
- isValidBitcoinAddress(address) {
334
- try {
335
- this.bitcoin.toOutputScript(address);
336
- return true;
337
- }
338
- catch (e) { }
339
- return false;
340
- }
341
- startRestServer(restServer) {
342
- const getAddress = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
343
- var _a;
344
- const metadata = { request: {}, times: {} };
345
- const chainIdentifier = req.query.chain;
346
- const { chainInterface, signer } = this.getChain(chainIdentifier);
347
- metadata.times.requestReceived = Date.now();
348
- /**
349
- * address: string solana address of the recipient
350
- * refundAddress?: string bitcoin address to use in case of refund
351
- * amount: string amount (in lamports/smart chain base units) of the invoice
352
- * exactOut: boolean whether to create and exact output swap
353
- */
354
- (_a = req.query).token ?? (_a.token = chainInterface.getNativeCurrencyAddress());
355
- const parsedBody = (0, SchemaVerifier_1.verifySchema)(req.query, {
356
- address: (val) => val != null &&
357
- typeof (val) === "string" &&
358
- chainInterface.isValidAddress(val, true) ? val : null,
359
- refundAddress: (val) => val == null ? "" :
360
- typeof (val) === "string" &&
361
- this.isValidBitcoinAddress(val) ? val : null,
362
- token: (val) => val != null &&
363
- typeof (val) === "string" &&
364
- this.isTokenSupported(chainIdentifier, val) ? val : null,
365
- amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
366
- exactIn: (val) => val === "true" ? true :
367
- (val === "false" || val === undefined) ? false : null
368
- });
369
- if (parsedBody == null)
370
- throw {
371
- code: 20100,
372
- msg: "Invalid request body"
373
- };
374
- metadata.request = parsedBody;
375
- const refundAddress = parsedBody.refundAddress === "" ? null : parsedBody.refundAddress;
376
- const requestedAmount = { input: parsedBody.exactIn, amount: parsedBody.amount, token: parsedBody.token };
377
- const request = {
378
- chainIdentifier,
379
- raw: req,
380
- parsed: parsedBody,
381
- metadata
382
- };
383
- const useToken = parsedBody.token;
384
- this.checkTooManyInflightSwaps();
385
- //Check request params
386
- const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount);
387
- metadata.times.requestChecked = Date.now();
388
- //Create abortController for parallel prefetches
389
- const responseStream = res.responseStream;
390
- const abortController = (0, Utils_1.getAbortController)(responseStream);
391
- //Pre-fetch data
392
- const pricePrefetchPromise = this.swapPricing.preFetchPrice(useToken, chainIdentifier).catch(e => {
393
- this.logger.error("pricePrefetchPromise(): pricePrefetch error: ", e);
394
- abortController.abort(e);
395
- return null;
396
- });
397
- const balancePrefetch = chainInterface.getBalance(signer.getAddress(), useToken).catch(e => {
398
- this.logger.error("getBalancePrefetch(): balancePrefetch error: ", e);
399
- abortController.abort(e);
400
- return null;
401
- });
402
- const nativeBalancePrefetch = useToken === chainInterface.getNativeCurrencyAddress() ?
403
- balancePrefetch : this.prefetchNativeBalanceIfNeeded(chainIdentifier, abortController);
404
- await this.checkNativeBalance(chainIdentifier, nativeBalancePrefetch, abortController.signal);
405
- //Check valid amount specified (min/max)
406
- const { amountBD, swapFee, swapFeeInToken, totalInToken } = await this.AmountAssertions.checkFromBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, abortController.signal);
407
- metadata.times.priceCalculated = Date.now();
408
- //Make sure we have MORE THAN ENOUGH to honor the swap request
409
- await this.checkBalance(totalInToken * 4n, balancePrefetch, abortController.signal);
410
- metadata.times.balanceChecked = Date.now();
411
- const blockHeight = await this.bitcoin.getBlockheight();
412
- const feeRate = await this.bitcoin.getFeeRate();
413
- const recommendedFee = Math.ceil(feeRate * this.config.recommendFeeMultiplier);
414
- if (recommendedFee === 0)
415
- throw {
416
- _httpStatus: 500,
417
- code: 21100,
418
- msg: "Cannot estimate bitcoin fee!"
419
- };
420
- metadata.times.feeEstimated = Date.now();
421
- const receiveAddress = await this.bitcoin.getAddress();
422
- const outputScript = this.bitcoin.toOutputScript(receiveAddress).toString("hex");
423
- abortController.signal.throwIfAborted();
424
- metadata.times.addressCreated = Date.now();
425
- const createdSwap = new FromBtcTrustedSwap_1.FromBtcTrustedSwap(chainIdentifier, swapFee, swapFeeInToken, receiveAddress, amountBD, parsedBody.address, totalInToken, blockHeight, Date.now() + (this.config.swapAddressExpiry * 1000), recommendedFee, refundAddress, useToken);
426
- metadata.times.swapCreated = Date.now();
427
- createdSwap.metadata = metadata;
428
- await PluginManager_1.PluginManager.swapCreate(createdSwap);
429
- await this.storageManager.saveData(createdSwap.getIdentifierHash(), createdSwap.getSequence(), createdSwap);
430
- this.subscriptions.set(outputScript, createdSwap);
431
- this.swapLogger.info(createdSwap, "REST: /getAddress: Created swap address: " + createdSwap.btcAddress + " amount: " + amountBD.toString(10));
432
- res.status(200).json({
433
- code: 10000,
434
- msg: "Success",
435
- data: {
436
- paymentHash: createdSwap.getIdentifierHash(),
437
- sequence: createdSwap.getSequence().toString(10),
438
- btcAddress: receiveAddress,
439
- amountSats: amountBD.toString(10),
440
- swapFeeSats: swapFee.toString(10),
441
- swapFee: swapFeeInToken.toString(10),
442
- total: totalInToken.toString(10),
443
- intermediaryKey: signer.getAddress(),
444
- recommendedFee,
445
- expiresAt: createdSwap.expiresAt
446
- }
447
- });
448
- });
449
- restServer.get(this.path + "/getAddress", getAddress);
450
- const getInvoiceStatus = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
451
- /**
452
- * paymentHash: string payment hash of the invoice
453
- * sequence: BN secret sequence for the swap,
454
- */
455
- const parsedBody = (0, SchemaVerifier_1.verifySchema)(req.query, {
456
- paymentHash: (val) => val != null &&
457
- typeof (val) === "string" &&
458
- val.length === 64 &&
459
- Utils_1.HEX_REGEX.test(val) ? val : null,
460
- sequence: SchemaVerifier_1.FieldTypeEnum.BigInt,
461
- });
462
- if (parsedBody == null)
463
- throw {
464
- code: 20100,
465
- msg: "Invalid request"
466
- };
467
- const processedTxData = this.processedTxIds.get(parsedBody.paymentHash);
468
- if (processedTxData != null)
469
- throw {
470
- _httpStatus: 200,
471
- code: 10000,
472
- msg: "Success, tx confirmed",
473
- data: {
474
- adjustedAmount: processedTxData.adjustedAmount.toString(10),
475
- adjustedTotal: processedTxData.adjustedTotal.toString(10),
476
- txId: processedTxData.txId,
477
- scTxId: processedTxData.scTxId
478
- }
479
- };
480
- const refundTxId = this.refundedSwaps.get(parsedBody.paymentHash);
481
- if (refundTxId != null)
482
- throw {
483
- _httpStatus: 200,
484
- code: 10014,
485
- msg: "Refunded",
486
- data: {
487
- txId: refundTxId
488
- }
489
- };
490
- const doubleSpendTxId = this.doubleSpentSwaps.get(parsedBody.paymentHash);
491
- if (doubleSpendTxId != null)
492
- throw {
493
- _httpStatus: 200,
494
- code: 10015,
495
- msg: "Double spend detected, deposit burned",
496
- data: {
497
- txId: doubleSpendTxId
498
- }
499
- };
500
- const invoiceData = await this.storageManager.getData(parsedBody.paymentHash, parsedBody.sequence);
501
- if (invoiceData == null)
502
- throw {
503
- _httpStatus: 200,
504
- code: 10001,
505
- msg: "Swap expired/canceled"
506
- };
507
- if (invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CREATED)
508
- throw {
509
- _httpStatus: 200,
510
- code: 10010,
511
- msg: "Bitcoin yet unpaid"
512
- };
513
- if (invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.RECEIVED)
514
- throw {
515
- _httpStatus: 200,
516
- code: 10011,
517
- msg: "Bitcoin received, payment processing",
518
- data: {
519
- adjustedAmount: invoiceData.adjustedInput.toString(10),
520
- adjustedTotal: invoiceData.adjustedOutput.toString(10),
521
- txId: invoiceData.txId
522
- }
523
- };
524
- if (invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED)
525
- throw {
526
- _httpStatus: 200,
527
- code: 10013,
528
- msg: "Bitcoin accepted, payment processing",
529
- data: {
530
- adjustedAmount: invoiceData.adjustedInput.toString(10),
531
- adjustedTotal: invoiceData.adjustedOutput.toString(10),
532
- txId: invoiceData.txId
533
- }
534
- };
535
- if (invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.SENT)
536
- throw {
537
- _httpStatus: 200,
538
- code: 10012,
539
- msg: "Tx sent",
540
- data: {
541
- adjustedAmount: invoiceData.adjustedInput.toString(10),
542
- adjustedTotal: invoiceData.adjustedOutput.toString(10),
543
- txId: invoiceData.txId,
544
- scTxId: invoiceData.txIds.init
545
- }
546
- };
547
- if (invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CONFIRMED || invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.FINISHED)
548
- throw {
549
- _httpStatus: 200,
550
- code: 10000,
551
- msg: "Success, tx confirmed",
552
- data: {
553
- adjustedAmount: invoiceData.adjustedInput.toString(10),
554
- adjustedTotal: invoiceData.adjustedOutput.toString(10),
555
- txId: invoiceData.txId,
556
- scTxId: invoiceData.txIds.init
557
- }
558
- };
559
- if (invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDABLE)
560
- throw {
561
- _httpStatus: 200,
562
- code: 10016,
563
- msg: "Refundable",
564
- data: {
565
- adjustedAmount: invoiceData.adjustedInput.toString(10)
566
- }
567
- };
568
- });
569
- restServer.get(this.path + "/getAddressStatus", getInvoiceStatus);
570
- const setRefundAddress = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
571
- /**
572
- * paymentHash: string payment hash of the invoice
573
- * sequence: BN secret sequence for the swap,
574
- * refundAddress: string valid bitcoin address to be used for refunds
575
- */
576
- const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
577
- paymentHash: (val) => val != null &&
578
- typeof (val) === "string" &&
579
- val.length === 64 &&
580
- Utils_1.HEX_REGEX.test(val) ? val : null,
581
- sequence: SchemaVerifier_1.FieldTypeEnum.BigInt,
582
- refundAddress: (val) => val != null &&
583
- typeof (val) === "string" &&
584
- this.isValidBitcoinAddress(val) ? val : null
585
- });
586
- if (parsedBody == null)
587
- throw {
588
- code: 20100,
589
- msg: "Invalid request"
590
- };
591
- const invoiceData = await this.storageManager.getData(parsedBody.paymentHash, null);
592
- if (invoiceData == null || invoiceData.getSequence() !== parsedBody.sequence)
593
- throw {
594
- code: 10001,
595
- msg: "Swap not found"
596
- };
597
- if (invoiceData.refundAddress != null)
598
- throw {
599
- code: 10080,
600
- msg: "Refund address already set!",
601
- data: {
602
- refundAddress: invoiceData.refundAddress
603
- }
604
- };
605
- invoiceData.refundAddress = parsedBody.refundAddress;
606
- if (invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDABLE) {
607
- this.refundSwap(invoiceData).catch(e => {
608
- this.swapLogger.error(invoiceData, "/setRefundAddress: Failed to refund!");
609
- });
610
- }
611
- throw {
612
- _httpStatus: 200,
613
- code: 10000,
614
- msg: "Refund address set"
615
- };
616
- });
617
- restServer.get(this.path + "/setRefundAddress", setRefundAddress);
618
- restServer.post(this.path + "/setRefundAddress", setRefundAddress);
619
- this.logger.info("started at path: ", this.path);
620
- }
621
- async checkDoubleSpends() {
622
- for (let swap of this.doubleSpendWatchdogSwaps.keys()) {
623
- const tx = await this.bitcoinRpc.getTransaction(swap.txId);
624
- if (tx == null) {
625
- this.swapLogger.debug(swap, "checkDoubleSpends(): Swap was double spent, burning... - original txId: " + swap.txId);
626
- this.processPastSwap(swap, null, null);
627
- }
628
- }
629
- }
630
- async startDoubleSpendWatchdog() {
631
- let rerun;
632
- rerun = async () => {
633
- await this.checkDoubleSpends().catch(e => this.logger.error("startDoubleSpendWatchdog(): Error when checking double spends: ", e));
634
- setTimeout(rerun, this.config.doubleSpendCheckInterval);
635
- };
636
- await rerun();
637
- }
638
- listenToTxns() {
639
- this.bitcoin.subscribeToWalletTransactions((btcTx) => {
640
- for (let out of btcTx.outs) {
641
- const savedSwap = this.subscriptions.get(out.scriptPubKey.hex);
642
- if (savedSwap == null)
643
- continue;
644
- this.processPastSwap(savedSwap, btcTx, out.n);
645
- return;
646
- }
647
- });
648
- }
649
- async startWatchdog() {
650
- await super.startWatchdog();
651
- await this.startDoubleSpendWatchdog();
652
- }
653
- async init() {
654
- await this.storageManager.loadData(FromBtcTrustedSwap_1.FromBtcTrustedSwap);
655
- this.listenToTxns();
656
- await PluginManager_1.PluginManager.serviceInitialize(this);
657
- }
658
- getInfoData() {
659
- return {};
660
- }
661
- }
662
- exports.FromBtcTrusted = FromBtcTrusted;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FromBtcTrusted = void 0;
4
+ const FromBtcTrustedSwap_1 = require("./FromBtcTrustedSwap");
5
+ const SwapHandler_1 = require("../../SwapHandler");
6
+ const PluginManager_1 = require("../../../plugins/PluginManager");
7
+ const Utils_1 = require("../../../utils/Utils");
8
+ const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
9
+ const FromBtcAmountAssertions_1 = require("../../assertions/FromBtcAmountAssertions");
10
+ class FromBtcTrusted extends SwapHandler_1.SwapHandler {
11
+ constructor(storageDirectory, path, chains, bitcoin, swapPricing, bitcoinRpc, config) {
12
+ var _a;
13
+ super(storageDirectory, path, chains, swapPricing);
14
+ this.type = SwapHandler_1.SwapHandlerType.FROM_BTC_TRUSTED;
15
+ this.inflightSwapStates = new Set([FromBtcTrustedSwap_1.FromBtcTrustedSwapState.RECEIVED, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.SENT, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CONFIRMED]);
16
+ this.subscriptions = new Map();
17
+ this.doubleSpendWatchdogSwaps = new Set();
18
+ this.refundedSwaps = new Map();
19
+ this.doubleSpentSwaps = new Map();
20
+ this.processedTxIds = new Map();
21
+ this.AmountAssertions = new FromBtcAmountAssertions_1.FromBtcAmountAssertions(config, swapPricing);
22
+ this.config = config;
23
+ (_a = this.config).recommendFeeMultiplier ?? (_a.recommendFeeMultiplier = 1.25);
24
+ this.bitcoin = bitcoin;
25
+ this.bitcoinRpc = bitcoinRpc;
26
+ }
27
+ getAllAncestors(tx) {
28
+ return Promise.all(tx.ins.map(input => this.bitcoinRpc.getTransaction(input.txid).then(tx => {
29
+ return { tx, vout: input.vout };
30
+ })));
31
+ }
32
+ async refundSwap(swap) {
33
+ if (swap.refundAddress == null) {
34
+ if (swap.state !== FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDABLE) {
35
+ await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDABLE);
36
+ await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
37
+ }
38
+ return;
39
+ }
40
+ let unlock = swap.lock(30 * 1000);
41
+ if (unlock == null)
42
+ return;
43
+ const feeRate = await this.bitcoin.getFeeRate();
44
+ const ourOutput = swap.btcTx.outs[swap.vout];
45
+ const resp = await this.bitcoin.drainAll(swap.refundAddress, [{
46
+ type: this.bitcoin.getAddressType(),
47
+ confirmations: swap.btcTx.confirmations,
48
+ outputScript: Buffer.from(ourOutput.scriptPubKey.hex, "hex"),
49
+ value: ourOutput.value,
50
+ txId: swap.btcTx.txid,
51
+ vout: swap.vout
52
+ }], feeRate);
53
+ if (resp == null) {
54
+ this.swapLogger.error(swap, "refundSwap(): cannot refund swap because of dust limit, txId: " + swap.txId);
55
+ unlock();
56
+ return;
57
+ }
58
+ if (swap.metadata != null)
59
+ swap.metadata.times.refundSignPSBT = Date.now();
60
+ this.swapLogger.debug(swap, "refundSwap(): signed raw transaction: " + resp.raw);
61
+ const refundTxId = resp.txId;
62
+ swap.refundTxId = refundTxId;
63
+ //Send the refund TX
64
+ await this.bitcoin.sendRawTransaction(resp.raw);
65
+ this.swapLogger.debug(swap, "refundSwap(): sent refund transaction: " + refundTxId);
66
+ this.refundedSwaps.set(swap.getIdentifierHash(), refundTxId);
67
+ await this.removeSwapData(swap, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDED);
68
+ unlock();
69
+ }
70
+ async burn(swap) {
71
+ const ourOutput = swap.btcTx.outs[swap.vout];
72
+ //Check if we can even increase the feeRate by burning
73
+ const txSize = 110;
74
+ const burnTxFeeRate = Math.floor(ourOutput.value / txSize);
75
+ const initialTxFeeRate = Math.ceil(swap.txFee / swap.txSize);
76
+ if (burnTxFeeRate < initialTxFeeRate) {
77
+ this.swapLogger.warn(swap, "burn(): cannot send burn transaction, pays too little fee, " +
78
+ "initialTxId: " + swap.txId + " initialTxFeeRate: " + initialTxFeeRate + " burnTxFeeRate: " + burnTxFeeRate);
79
+ this.doubleSpentSwaps.set(swap.getIdentifierHash(), null);
80
+ await this.removeSwapData(swap, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.DOUBLE_SPENT);
81
+ return;
82
+ }
83
+ //Construct PSBT
84
+ const resp = await this.bitcoin.burnAll([{
85
+ type: this.bitcoin.getAddressType(),
86
+ confirmations: swap.btcTx.confirmations,
87
+ outputScript: Buffer.from(ourOutput.scriptPubKey.hex, "hex"),
88
+ value: ourOutput.value,
89
+ txId: swap.btcTx.txid,
90
+ vout: swap.vout
91
+ }]);
92
+ if (swap.metadata != null)
93
+ swap.metadata.times.burnSignPSBT = Date.now();
94
+ this.swapLogger.debug(swap, "burn(): signed raw transaction: " + resp.raw);
95
+ const burnTxId = resp.txId;
96
+ swap.burnTxId = burnTxId;
97
+ //Send the original TX + our burn TX as a package
98
+ const sendTxns = [swap.btcTx.raw, resp.raw];
99
+ //TODO: We should handle this in a better way
100
+ try {
101
+ await this.bitcoinRpc.sendRawPackage(sendTxns);
102
+ this.swapLogger.debug(swap, "burn(): sent burn transaction: " + burnTxId);
103
+ }
104
+ catch (e) {
105
+ this.swapLogger.error(swap, "burn(): error sending burn package: ", e);
106
+ }
107
+ this.doubleSpentSwaps.set(swap.getIdentifierHash(), burnTxId);
108
+ await this.removeSwapData(swap, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.DOUBLE_SPENT);
109
+ }
110
+ async processPastSwap(swap, tx, vout) {
111
+ const foundVout = tx.outs[vout];
112
+ const { chainInterface, signer } = this.getChain(swap.chainIdentifier);
113
+ const outputScript = this.bitcoin.toOutputScript(swap.btcAddress).toString("hex");
114
+ if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CREATED) {
115
+ this.subscriptions.set(outputScript, swap);
116
+ if (foundVout == null) {
117
+ //Check expiry
118
+ if (swap.expiresAt < Date.now()) {
119
+ this.subscriptions.delete(outputScript);
120
+ await this.bitcoin.addUnusedAddress(swap.btcAddress);
121
+ await this.removeSwapData(swap, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.EXPIRED);
122
+ return;
123
+ }
124
+ return;
125
+ }
126
+ const sentSats = BigInt(foundVout.value);
127
+ if (sentSats === swap.amount) {
128
+ swap.adjustedInput = swap.amount;
129
+ swap.adjustedOutput = swap.outputTokens;
130
+ }
131
+ else {
132
+ //If lower than minimum then ignore
133
+ if (sentSats < this.config.min)
134
+ return;
135
+ if (sentSats > this.config.max) {
136
+ swap.adjustedInput = sentSats;
137
+ swap.btcTx = tx;
138
+ swap.txId = tx.txid;
139
+ swap.vout = vout;
140
+ this.subscriptions.delete(outputScript);
141
+ await this.refundSwap(swap);
142
+ return;
143
+ }
144
+ //Adjust the amount
145
+ swap.adjustedInput = sentSats;
146
+ swap.adjustedOutput = swap.outputTokens * sentSats / swap.amount;
147
+ }
148
+ swap.btcTx = tx;
149
+ swap.txId = tx.txid;
150
+ swap.vout = vout;
151
+ this.subscriptions.delete(outputScript);
152
+ try {
153
+ this.checkTooManyInflightSwaps();
154
+ }
155
+ catch (e) {
156
+ await this.refundSwap(swap);
157
+ return;
158
+ }
159
+ await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.RECEIVED);
160
+ await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
161
+ }
162
+ if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.RECEIVED) {
163
+ //Check if transaction still exists
164
+ if (tx == null || foundVout == null || tx.txid !== swap.txId) {
165
+ await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CREATED);
166
+ await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
167
+ return;
168
+ }
169
+ //Check if it is confirmed
170
+ if (tx.confirmations > 0) {
171
+ await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED);
172
+ await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
173
+ }
174
+ else {
175
+ //Check if it pays high enough fee AND has confirmed ancestors
176
+ const ancestors = await this.getAllAncestors(tx);
177
+ const allAncestorsConfirmed = ancestors.reduce((prev, curr) => prev && curr.tx.confirmations > 0, true);
178
+ const totalInput = ancestors.reduce((prev, curr) => prev + curr.tx.outs[curr.vout].value, 0);
179
+ const totalOutput = tx.outs.reduce((prev, curr) => prev + curr.value, 0);
180
+ const fee = totalInput - totalOutput;
181
+ const feePerVbyte = Math.ceil(fee / tx.vsize);
182
+ if (allAncestorsConfirmed &&
183
+ (feePerVbyte >= swap.recommendedFee || feePerVbyte >= await this.bitcoin.getFeeRate())) {
184
+ if (swap.state !== FromBtcTrustedSwap_1.FromBtcTrustedSwapState.RECEIVED)
185
+ return;
186
+ swap.txSize = tx.vsize;
187
+ swap.txFee = fee;
188
+ await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED);
189
+ await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
190
+ }
191
+ else {
192
+ return;
193
+ }
194
+ }
195
+ }
196
+ if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDABLE) {
197
+ if (swap.refundAddress != null) {
198
+ await this.refundSwap(swap);
199
+ return;
200
+ }
201
+ }
202
+ if (swap.doubleSpent || tx == null || foundVout == null || tx.txid !== swap.txId) {
203
+ if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDABLE) {
204
+ await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CREATED);
205
+ return;
206
+ }
207
+ if (!swap.doubleSpent) {
208
+ swap.doubleSpent = true;
209
+ try {
210
+ await this.burn(swap);
211
+ this.doubleSpendWatchdogSwaps.delete(swap);
212
+ }
213
+ catch (e) {
214
+ this.swapLogger.error(swap, "processPastSwap(): Error burning swap: ", e);
215
+ swap.doubleSpent = false;
216
+ }
217
+ }
218
+ return;
219
+ }
220
+ else {
221
+ if (tx.confirmations <= 0 && !this.doubleSpendWatchdogSwaps.has(swap)) {
222
+ this.swapLogger.debug(swap, "processPastSwap(): Adding swap transaction to double spend watchdog list: ", swap.txId);
223
+ this.doubleSpendWatchdogSwaps.add(swap);
224
+ }
225
+ }
226
+ if (tx.confirmations > 0 && this.doubleSpendWatchdogSwaps.delete(swap)) {
227
+ this.swapLogger.debug(swap, "processPastSwap(): Removing confirmed swap transaction from double spend watchdog list: ", swap.txId);
228
+ }
229
+ if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED) {
230
+ //Send gas token
231
+ const balance = chainInterface.getBalance(signer.getAddress(), swap.token);
232
+ try {
233
+ await this.checkBalance(swap.adjustedOutput, balance, null);
234
+ if (swap.metadata != null)
235
+ swap.metadata.times.receivedBalanceChecked = Date.now();
236
+ }
237
+ catch (e) {
238
+ this.swapLogger.error(swap, "processPastSwap(): Error not enough balance: ", e);
239
+ await this.refundSwap(swap);
240
+ return;
241
+ }
242
+ if (swap.state !== FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED)
243
+ return;
244
+ let unlock = swap.lock(30 * 1000);
245
+ if (unlock == null)
246
+ return;
247
+ const txns = await chainInterface.txsTransfer(signer.getAddress(), swap.token, swap.adjustedOutput, swap.dstAddress);
248
+ await chainInterface.sendAndConfirm(signer, txns, true, null, false, async (txId, rawTx) => {
249
+ swap.txIds = { init: txId };
250
+ swap.scRawTx = rawTx;
251
+ if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED) {
252
+ await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.SENT);
253
+ await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
254
+ }
255
+ if (unlock != null)
256
+ unlock();
257
+ unlock = null;
258
+ });
259
+ }
260
+ if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.SENT) {
261
+ const txStatus = await chainInterface.getTxStatus(swap.scRawTx);
262
+ switch (txStatus) {
263
+ case "not_found":
264
+ //Retry
265
+ swap.txIds = { init: null };
266
+ swap.scRawTx = null;
267
+ await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.RECEIVED);
268
+ await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
269
+ break;
270
+ case "reverted":
271
+ //Cancel invoice
272
+ await this.refundSwap(swap);
273
+ this.swapLogger.info(swap, "processPastSwap(): transaction reverted, refunding btc on-chain: ", swap.btcAddress);
274
+ break;
275
+ case "success":
276
+ await swap.setState(FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CONFIRMED);
277
+ await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
278
+ break;
279
+ }
280
+ }
281
+ if (swap.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CONFIRMED) {
282
+ this.processedTxIds.set(swap.getIdentifierHash(), {
283
+ txId: swap.txId,
284
+ scTxId: swap.txIds.init,
285
+ adjustedAmount: swap.adjustedInput,
286
+ adjustedTotal: swap.adjustedOutput
287
+ });
288
+ if (tx.confirmations > 0)
289
+ await this.removeSwapData(swap, FromBtcTrustedSwap_1.FromBtcTrustedSwapState.FINISHED);
290
+ }
291
+ }
292
+ async processPastSwaps() {
293
+ const queriedData = await this.storageManager.query([
294
+ {
295
+ key: "state",
296
+ value: [
297
+ FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDABLE,
298
+ FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CREATED,
299
+ FromBtcTrustedSwap_1.FromBtcTrustedSwapState.RECEIVED,
300
+ FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED,
301
+ FromBtcTrustedSwap_1.FromBtcTrustedSwapState.SENT,
302
+ FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CONFIRMED
303
+ ]
304
+ }
305
+ ]);
306
+ const startingBlockheight = queriedData.reduce((prev, { obj: swap }) => Math.min(prev, swap.createdHeight), Infinity);
307
+ if (startingBlockheight === Infinity)
308
+ return;
309
+ const transactions = await this.bitcoin.getWalletTransactions(startingBlockheight);
310
+ const map = new Map();
311
+ transactions.forEach(tx => {
312
+ tx.outs.forEach((out, vout) => {
313
+ const existing = map.get(out.scriptPubKey.hex);
314
+ if (existing == null) {
315
+ map.set(out.scriptPubKey.hex, [{ tx, vout }]);
316
+ }
317
+ else {
318
+ existing.push({ tx, vout });
319
+ }
320
+ });
321
+ });
322
+ for (let { obj: swap } of queriedData) {
323
+ const outputScript = this.bitcoin.toOutputScript(swap.btcAddress).toString("hex");
324
+ const txs = map.get(outputScript) ?? [];
325
+ try {
326
+ await this.processPastSwap(swap, txs[0]?.tx, txs[0]?.vout);
327
+ }
328
+ catch (e) {
329
+ this.swapLogger.error(swap, "processPastSwaps(): Error ocurred while processing swap: ", e);
330
+ }
331
+ }
332
+ }
333
+ isValidBitcoinAddress(address) {
334
+ try {
335
+ this.bitcoin.toOutputScript(address);
336
+ return true;
337
+ }
338
+ catch (e) { }
339
+ return false;
340
+ }
341
+ startRestServer(restServer) {
342
+ const getAddress = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
343
+ var _a;
344
+ const metadata = { request: {}, times: {} };
345
+ const chainIdentifier = req.query.chain;
346
+ const { chainInterface, signer } = this.getChain(chainIdentifier);
347
+ metadata.times.requestReceived = Date.now();
348
+ /**
349
+ * address: string solana address of the recipient
350
+ * refundAddress?: string bitcoin address to use in case of refund
351
+ * amount: string amount (in lamports/smart chain base units) of the invoice
352
+ * exactOut: boolean whether to create and exact output swap
353
+ */
354
+ (_a = req.query).token ?? (_a.token = chainInterface.getNativeCurrencyAddress());
355
+ const parsedBody = (0, SchemaVerifier_1.verifySchema)(req.query, {
356
+ address: (val) => val != null &&
357
+ typeof (val) === "string" &&
358
+ chainInterface.isValidAddress(val, true) ? val : null,
359
+ refundAddress: (val) => val == null ? "" :
360
+ typeof (val) === "string" &&
361
+ this.isValidBitcoinAddress(val) ? val : null,
362
+ token: (val) => val != null &&
363
+ typeof (val) === "string" &&
364
+ this.isTokenSupported(chainIdentifier, val) ? val : null,
365
+ amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
366
+ exactIn: (val) => val === "true" ? true :
367
+ (val === "false" || val === undefined) ? false : null
368
+ });
369
+ if (parsedBody == null)
370
+ throw {
371
+ code: 20100,
372
+ msg: "Invalid request body"
373
+ };
374
+ metadata.request = parsedBody;
375
+ const refundAddress = parsedBody.refundAddress === "" ? null : parsedBody.refundAddress;
376
+ const requestedAmount = { input: parsedBody.exactIn, amount: parsedBody.amount, token: parsedBody.token };
377
+ const request = {
378
+ chainIdentifier,
379
+ raw: req,
380
+ parsed: parsedBody,
381
+ metadata
382
+ };
383
+ const useToken = parsedBody.token;
384
+ this.checkTooManyInflightSwaps();
385
+ //Check request params
386
+ const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount);
387
+ metadata.times.requestChecked = Date.now();
388
+ //Create abortController for parallel prefetches
389
+ const responseStream = res.responseStream;
390
+ const abortController = (0, Utils_1.getAbortController)(responseStream);
391
+ //Pre-fetch data
392
+ const pricePrefetchPromise = this.swapPricing.preFetchPrice(useToken, chainIdentifier).catch(e => {
393
+ this.logger.error("pricePrefetchPromise(): pricePrefetch error: ", e);
394
+ abortController.abort(e);
395
+ return null;
396
+ });
397
+ const balancePrefetch = chainInterface.getBalance(signer.getAddress(), useToken).catch(e => {
398
+ this.logger.error("getBalancePrefetch(): balancePrefetch error: ", e);
399
+ abortController.abort(e);
400
+ return null;
401
+ });
402
+ const nativeBalancePrefetch = useToken === chainInterface.getNativeCurrencyAddress() ?
403
+ balancePrefetch : this.prefetchNativeBalanceIfNeeded(chainIdentifier, abortController);
404
+ await this.checkNativeBalance(chainIdentifier, nativeBalancePrefetch, abortController.signal);
405
+ //Check valid amount specified (min/max)
406
+ const { amountBD, swapFee, swapFeeInToken, totalInToken } = await this.AmountAssertions.checkFromBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, abortController.signal);
407
+ metadata.times.priceCalculated = Date.now();
408
+ //Make sure we have MORE THAN ENOUGH to honor the swap request
409
+ await this.checkBalance(totalInToken * 4n, balancePrefetch, abortController.signal);
410
+ metadata.times.balanceChecked = Date.now();
411
+ const blockHeight = await this.bitcoin.getBlockheight();
412
+ const feeRate = await this.bitcoin.getFeeRate();
413
+ const recommendedFee = Math.ceil(feeRate * this.config.recommendFeeMultiplier);
414
+ if (recommendedFee === 0)
415
+ throw {
416
+ _httpStatus: 500,
417
+ code: 21100,
418
+ msg: "Cannot estimate bitcoin fee!"
419
+ };
420
+ metadata.times.feeEstimated = Date.now();
421
+ const receiveAddress = await this.bitcoin.getAddress();
422
+ const outputScript = this.bitcoin.toOutputScript(receiveAddress).toString("hex");
423
+ abortController.signal.throwIfAborted();
424
+ metadata.times.addressCreated = Date.now();
425
+ const createdSwap = new FromBtcTrustedSwap_1.FromBtcTrustedSwap(chainIdentifier, swapFee, swapFeeInToken, receiveAddress, amountBD, parsedBody.address, totalInToken, blockHeight, Date.now() + (this.config.swapAddressExpiry * 1000), recommendedFee, refundAddress, useToken);
426
+ metadata.times.swapCreated = Date.now();
427
+ createdSwap.metadata = metadata;
428
+ await PluginManager_1.PluginManager.swapCreate(createdSwap);
429
+ await this.storageManager.saveData(createdSwap.getIdentifierHash(), createdSwap.getSequence(), createdSwap);
430
+ this.subscriptions.set(outputScript, createdSwap);
431
+ this.swapLogger.info(createdSwap, "REST: /getAddress: Created swap address: " + createdSwap.btcAddress + " amount: " + amountBD.toString(10));
432
+ res.status(200).json({
433
+ code: 10000,
434
+ msg: "Success",
435
+ data: {
436
+ paymentHash: createdSwap.getIdentifierHash(),
437
+ sequence: createdSwap.getSequence().toString(10),
438
+ btcAddress: receiveAddress,
439
+ amountSats: amountBD.toString(10),
440
+ swapFeeSats: swapFee.toString(10),
441
+ swapFee: swapFeeInToken.toString(10),
442
+ total: totalInToken.toString(10),
443
+ intermediaryKey: signer.getAddress(),
444
+ recommendedFee,
445
+ expiresAt: createdSwap.expiresAt
446
+ }
447
+ });
448
+ });
449
+ restServer.get(this.path + "/getAddress", getAddress);
450
+ const getInvoiceStatus = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
451
+ /**
452
+ * paymentHash: string payment hash of the invoice
453
+ * sequence: BN secret sequence for the swap,
454
+ */
455
+ const parsedBody = (0, SchemaVerifier_1.verifySchema)(req.query, {
456
+ paymentHash: (val) => val != null &&
457
+ typeof (val) === "string" &&
458
+ val.length === 64 &&
459
+ Utils_1.HEX_REGEX.test(val) ? val : null,
460
+ sequence: SchemaVerifier_1.FieldTypeEnum.BigInt,
461
+ });
462
+ if (parsedBody == null)
463
+ throw {
464
+ code: 20100,
465
+ msg: "Invalid request"
466
+ };
467
+ const processedTxData = this.processedTxIds.get(parsedBody.paymentHash);
468
+ if (processedTxData != null)
469
+ throw {
470
+ _httpStatus: 200,
471
+ code: 10000,
472
+ msg: "Success, tx confirmed",
473
+ data: {
474
+ adjustedAmount: processedTxData.adjustedAmount.toString(10),
475
+ adjustedTotal: processedTxData.adjustedTotal.toString(10),
476
+ txId: processedTxData.txId,
477
+ scTxId: processedTxData.scTxId
478
+ }
479
+ };
480
+ const refundTxId = this.refundedSwaps.get(parsedBody.paymentHash);
481
+ if (refundTxId != null)
482
+ throw {
483
+ _httpStatus: 200,
484
+ code: 10014,
485
+ msg: "Refunded",
486
+ data: {
487
+ txId: refundTxId
488
+ }
489
+ };
490
+ const doubleSpendTxId = this.doubleSpentSwaps.get(parsedBody.paymentHash);
491
+ if (doubleSpendTxId != null)
492
+ throw {
493
+ _httpStatus: 200,
494
+ code: 10015,
495
+ msg: "Double spend detected, deposit burned",
496
+ data: {
497
+ txId: doubleSpendTxId
498
+ }
499
+ };
500
+ const invoiceData = await this.storageManager.getData(parsedBody.paymentHash, parsedBody.sequence);
501
+ if (invoiceData == null)
502
+ throw {
503
+ _httpStatus: 200,
504
+ code: 10001,
505
+ msg: "Swap expired/canceled"
506
+ };
507
+ if (invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CREATED)
508
+ throw {
509
+ _httpStatus: 200,
510
+ code: 10010,
511
+ msg: "Bitcoin yet unpaid"
512
+ };
513
+ if (invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.RECEIVED)
514
+ throw {
515
+ _httpStatus: 200,
516
+ code: 10011,
517
+ msg: "Bitcoin received, payment processing",
518
+ data: {
519
+ adjustedAmount: invoiceData.adjustedInput.toString(10),
520
+ adjustedTotal: invoiceData.adjustedOutput.toString(10),
521
+ txId: invoiceData.txId
522
+ }
523
+ };
524
+ if (invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.BTC_CONFIRMED)
525
+ throw {
526
+ _httpStatus: 200,
527
+ code: 10013,
528
+ msg: "Bitcoin accepted, payment processing",
529
+ data: {
530
+ adjustedAmount: invoiceData.adjustedInput.toString(10),
531
+ adjustedTotal: invoiceData.adjustedOutput.toString(10),
532
+ txId: invoiceData.txId
533
+ }
534
+ };
535
+ if (invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.SENT)
536
+ throw {
537
+ _httpStatus: 200,
538
+ code: 10012,
539
+ msg: "Tx sent",
540
+ data: {
541
+ adjustedAmount: invoiceData.adjustedInput.toString(10),
542
+ adjustedTotal: invoiceData.adjustedOutput.toString(10),
543
+ txId: invoiceData.txId,
544
+ scTxId: invoiceData.txIds.init
545
+ }
546
+ };
547
+ if (invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.CONFIRMED || invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.FINISHED)
548
+ throw {
549
+ _httpStatus: 200,
550
+ code: 10000,
551
+ msg: "Success, tx confirmed",
552
+ data: {
553
+ adjustedAmount: invoiceData.adjustedInput.toString(10),
554
+ adjustedTotal: invoiceData.adjustedOutput.toString(10),
555
+ txId: invoiceData.txId,
556
+ scTxId: invoiceData.txIds.init
557
+ }
558
+ };
559
+ if (invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDABLE)
560
+ throw {
561
+ _httpStatus: 200,
562
+ code: 10016,
563
+ msg: "Refundable",
564
+ data: {
565
+ adjustedAmount: invoiceData.adjustedInput.toString(10)
566
+ }
567
+ };
568
+ });
569
+ restServer.get(this.path + "/getAddressStatus", getInvoiceStatus);
570
+ const setRefundAddress = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
571
+ /**
572
+ * paymentHash: string payment hash of the invoice
573
+ * sequence: BN secret sequence for the swap,
574
+ * refundAddress: string valid bitcoin address to be used for refunds
575
+ */
576
+ const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
577
+ paymentHash: (val) => val != null &&
578
+ typeof (val) === "string" &&
579
+ val.length === 64 &&
580
+ Utils_1.HEX_REGEX.test(val) ? val : null,
581
+ sequence: SchemaVerifier_1.FieldTypeEnum.BigInt,
582
+ refundAddress: (val) => val != null &&
583
+ typeof (val) === "string" &&
584
+ this.isValidBitcoinAddress(val) ? val : null
585
+ });
586
+ if (parsedBody == null)
587
+ throw {
588
+ code: 20100,
589
+ msg: "Invalid request"
590
+ };
591
+ const invoiceData = await this.storageManager.getData(parsedBody.paymentHash, null);
592
+ if (invoiceData == null || invoiceData.getSequence() !== parsedBody.sequence)
593
+ throw {
594
+ code: 10001,
595
+ msg: "Swap not found"
596
+ };
597
+ if (invoiceData.refundAddress != null)
598
+ throw {
599
+ code: 10080,
600
+ msg: "Refund address already set!",
601
+ data: {
602
+ refundAddress: invoiceData.refundAddress
603
+ }
604
+ };
605
+ invoiceData.refundAddress = parsedBody.refundAddress;
606
+ if (invoiceData.state === FromBtcTrustedSwap_1.FromBtcTrustedSwapState.REFUNDABLE) {
607
+ this.refundSwap(invoiceData).catch(e => {
608
+ this.swapLogger.error(invoiceData, "/setRefundAddress: Failed to refund!");
609
+ });
610
+ }
611
+ throw {
612
+ _httpStatus: 200,
613
+ code: 10000,
614
+ msg: "Refund address set"
615
+ };
616
+ });
617
+ restServer.get(this.path + "/setRefundAddress", setRefundAddress);
618
+ restServer.post(this.path + "/setRefundAddress", setRefundAddress);
619
+ this.logger.info("started at path: ", this.path);
620
+ }
621
+ async checkDoubleSpends() {
622
+ for (let swap of this.doubleSpendWatchdogSwaps.keys()) {
623
+ const tx = await this.bitcoinRpc.getTransaction(swap.txId);
624
+ if (tx == null) {
625
+ this.swapLogger.debug(swap, "checkDoubleSpends(): Swap was double spent, burning... - original txId: " + swap.txId);
626
+ this.processPastSwap(swap, null, null);
627
+ }
628
+ }
629
+ }
630
+ async startDoubleSpendWatchdog() {
631
+ let rerun;
632
+ rerun = async () => {
633
+ await this.checkDoubleSpends().catch(e => this.logger.error("startDoubleSpendWatchdog(): Error when checking double spends: ", e));
634
+ setTimeout(rerun, this.config.doubleSpendCheckInterval);
635
+ };
636
+ await rerun();
637
+ }
638
+ listenToTxns() {
639
+ this.bitcoin.subscribeToWalletTransactions((btcTx) => {
640
+ for (let out of btcTx.outs) {
641
+ const savedSwap = this.subscriptions.get(out.scriptPubKey.hex);
642
+ if (savedSwap == null)
643
+ continue;
644
+ this.processPastSwap(savedSwap, btcTx, out.n);
645
+ return;
646
+ }
647
+ });
648
+ }
649
+ async startWatchdog() {
650
+ await super.startWatchdog();
651
+ await this.startDoubleSpendWatchdog();
652
+ }
653
+ async init() {
654
+ await this.storageManager.loadData(FromBtcTrustedSwap_1.FromBtcTrustedSwap);
655
+ this.listenToTxns();
656
+ await PluginManager_1.PluginManager.serviceInitialize(this);
657
+ }
658
+ getInfoData() {
659
+ return {};
660
+ }
661
+ }
662
+ exports.FromBtcTrusted = FromBtcTrusted;