@atomiqlabs/lp-lib 17.5.1 → 17.5.2

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 +329 -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 +719 -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 +730 -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 +769 -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 +912 -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 +710 -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 +518 -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 +32 -32
  91. package/dist/utils/Utils.js +130 -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 +468 -468
  140. package/src/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.ts +65 -65
  141. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.ts +900 -900
  142. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +145 -145
  143. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.ts +892 -892
  144. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.ts +200 -200
  145. package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +947 -947
  146. package/src/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.ts +112 -112
  147. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +1167 -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 +897 -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 +782 -782
  155. package/src/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.ts +189 -189
  156. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +622 -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 +152 -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,783 @@
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
+ 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
+
783
783
  }