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