@atomiqlabs/lp-lib 17.5.2 → 17.6.0

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