@atomiqlabs/lp-lib 16.0.11 → 16.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/LICENSE +201 -201
  2. package/dist/fees/IBtcFeeEstimator.d.ts +3 -3
  3. package/dist/fees/IBtcFeeEstimator.js +2 -2
  4. package/dist/index.d.ts +42 -42
  5. package/dist/index.js +58 -58
  6. package/dist/info/InfoHandler.d.ts +17 -17
  7. package/dist/info/InfoHandler.js +60 -60
  8. package/dist/plugins/IPlugin.d.ts +144 -144
  9. package/dist/plugins/IPlugin.js +34 -34
  10. package/dist/plugins/PluginManager.d.ts +113 -113
  11. package/dist/plugins/PluginManager.js +274 -274
  12. package/dist/prices/BinanceSwapPrice.d.ts +29 -26
  13. package/dist/prices/BinanceSwapPrice.js +79 -92
  14. package/dist/prices/CoinGeckoSwapPrice.d.ts +33 -30
  15. package/dist/prices/CoinGeckoSwapPrice.js +51 -64
  16. package/dist/prices/ISwapPrice.d.ts +43 -43
  17. package/dist/prices/ISwapPrice.js +55 -55
  18. package/dist/prices/OKXSwapPrice.d.ts +29 -26
  19. package/dist/prices/OKXSwapPrice.js +79 -92
  20. package/dist/storage/IIntermediaryStorage.d.ts +18 -18
  21. package/dist/storage/IIntermediaryStorage.js +2 -2
  22. package/dist/storagemanager/IntermediaryStorageManager.d.ts +19 -19
  23. package/dist/storagemanager/IntermediaryStorageManager.js +111 -111
  24. package/dist/storagemanager/StorageManager.d.ts +13 -13
  25. package/dist/storagemanager/StorageManager.js +64 -64
  26. package/dist/swaps/SwapHandler.d.ts +171 -171
  27. package/dist/swaps/SwapHandler.js +217 -217
  28. package/dist/swaps/SwapHandlerSwap.d.ts +79 -79
  29. package/dist/swaps/SwapHandlerSwap.js +78 -78
  30. package/dist/swaps/assertions/AmountAssertions.d.ts +28 -28
  31. package/dist/swaps/assertions/AmountAssertions.js +74 -74
  32. package/dist/swaps/assertions/FromBtcAmountAssertions.d.ts +76 -76
  33. package/dist/swaps/assertions/FromBtcAmountAssertions.js +185 -185
  34. package/dist/swaps/assertions/LightningAssertions.d.ts +44 -44
  35. package/dist/swaps/assertions/LightningAssertions.js +86 -86
  36. package/dist/swaps/assertions/ToBtcAmountAssertions.d.ts +53 -53
  37. package/dist/swaps/assertions/ToBtcAmountAssertions.js +150 -150
  38. package/dist/swaps/escrow/EscrowHandler.d.ts +50 -50
  39. package/dist/swaps/escrow/EscrowHandler.js +151 -151
  40. package/dist/swaps/escrow/EscrowHandlerSwap.d.ts +35 -35
  41. package/dist/swaps/escrow/EscrowHandlerSwap.js +69 -69
  42. package/dist/swaps/escrow/FromBtcBaseSwap.d.ts +14 -14
  43. package/dist/swaps/escrow/FromBtcBaseSwap.js +32 -32
  44. package/dist/swaps/escrow/FromBtcBaseSwapHandler.d.ts +102 -102
  45. package/dist/swaps/escrow/FromBtcBaseSwapHandler.js +210 -210
  46. package/dist/swaps/escrow/ToBtcBaseSwap.d.ts +36 -36
  47. package/dist/swaps/escrow/ToBtcBaseSwap.js +67 -67
  48. package/dist/swaps/escrow/ToBtcBaseSwapHandler.d.ts +53 -53
  49. package/dist/swaps/escrow/ToBtcBaseSwapHandler.js +81 -81
  50. package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.d.ts +84 -84
  51. package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.js +322 -322
  52. package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.d.ts +21 -21
  53. package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.js +50 -50
  54. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.d.ts +108 -108
  55. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.js +695 -695
  56. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +33 -33
  57. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.js +91 -91
  58. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.d.ts +112 -112
  59. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.js +708 -708
  60. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.d.ts +55 -55
  61. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.js +120 -120
  62. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.d.ts +170 -170
  63. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.js +745 -745
  64. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.d.ts +28 -28
  65. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.js +64 -64
  66. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.d.ts +178 -178
  67. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.js +899 -899
  68. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +24 -24
  69. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.js +58 -58
  70. package/dist/swaps/spv_vault_swap/SpvVault.d.ts +44 -44
  71. package/dist/swaps/spv_vault_swap/SpvVault.js +145 -145
  72. package/dist/swaps/spv_vault_swap/SpvVaultSwap.d.ts +68 -68
  73. package/dist/swaps/spv_vault_swap/SpvVaultSwap.js +158 -158
  74. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.d.ts +68 -68
  75. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.js +561 -561
  76. package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +63 -63
  77. package/dist/swaps/spv_vault_swap/SpvVaults.js +491 -491
  78. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.d.ts +52 -52
  79. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.js +662 -662
  80. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.d.ts +52 -52
  81. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.js +118 -118
  82. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.d.ts +77 -77
  83. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.js +504 -504
  84. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.d.ts +34 -34
  85. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.js +81 -81
  86. package/dist/utils/BitcoinUtils.d.ts +4 -4
  87. package/dist/utils/BitcoinUtils.js +61 -61
  88. package/dist/utils/Utils.d.ts +29 -29
  89. package/dist/utils/Utils.js +89 -89
  90. package/dist/utils/paramcoders/IParamReader.d.ts +5 -5
  91. package/dist/utils/paramcoders/IParamReader.js +2 -2
  92. package/dist/utils/paramcoders/IParamWriter.d.ts +4 -4
  93. package/dist/utils/paramcoders/IParamWriter.js +2 -2
  94. package/dist/utils/paramcoders/LegacyParamEncoder.d.ts +10 -10
  95. package/dist/utils/paramcoders/LegacyParamEncoder.js +22 -22
  96. package/dist/utils/paramcoders/ParamDecoder.d.ts +25 -25
  97. package/dist/utils/paramcoders/ParamDecoder.js +222 -222
  98. package/dist/utils/paramcoders/ParamEncoder.d.ts +9 -9
  99. package/dist/utils/paramcoders/ParamEncoder.js +22 -22
  100. package/dist/utils/paramcoders/SchemaVerifier.d.ts +21 -21
  101. package/dist/utils/paramcoders/SchemaVerifier.js +84 -84
  102. package/dist/utils/paramcoders/server/ServerParamDecoder.d.ts +8 -8
  103. package/dist/utils/paramcoders/server/ServerParamDecoder.js +107 -107
  104. package/dist/utils/paramcoders/server/ServerParamEncoder.d.ts +11 -11
  105. package/dist/utils/paramcoders/server/ServerParamEncoder.js +65 -65
  106. package/dist/wallets/IBitcoinWallet.d.ts +74 -74
  107. package/dist/wallets/IBitcoinWallet.js +2 -2
  108. package/dist/wallets/ILightningWallet.d.ts +117 -117
  109. package/dist/wallets/ILightningWallet.js +37 -37
  110. package/dist/wallets/ISpvVaultSigner.d.ts +7 -7
  111. package/dist/wallets/ISpvVaultSigner.js +2 -2
  112. package/package.json +36 -36
  113. package/src/fees/IBtcFeeEstimator.ts +6 -6
  114. package/src/index.ts +53 -53
  115. package/src/info/InfoHandler.ts +103 -103
  116. package/src/plugins/IPlugin.ts +174 -174
  117. package/src/plugins/PluginManager.ts +354 -354
  118. package/src/prices/BinanceSwapPrice.ts +101 -113
  119. package/src/prices/CoinGeckoSwapPrice.ts +75 -87
  120. package/src/prices/ISwapPrice.ts +88 -88
  121. package/src/prices/OKXSwapPrice.ts +101 -113
  122. package/src/storage/IIntermediaryStorage.ts +19 -19
  123. package/src/storagemanager/IntermediaryStorageManager.ts +118 -118
  124. package/src/storagemanager/StorageManager.ts +78 -78
  125. package/src/swaps/SwapHandler.ts +323 -323
  126. package/src/swaps/SwapHandlerSwap.ts +141 -141
  127. package/src/swaps/assertions/AmountAssertions.ts +77 -77
  128. package/src/swaps/assertions/FromBtcAmountAssertions.ts +251 -251
  129. package/src/swaps/assertions/LightningAssertions.ts +103 -103
  130. package/src/swaps/assertions/ToBtcAmountAssertions.ts +203 -203
  131. package/src/swaps/escrow/EscrowHandler.ts +172 -172
  132. package/src/swaps/escrow/EscrowHandlerSwap.ts +86 -86
  133. package/src/swaps/escrow/FromBtcBaseSwap.ts +38 -38
  134. package/src/swaps/escrow/FromBtcBaseSwapHandler.ts +286 -286
  135. package/src/swaps/escrow/ToBtcBaseSwap.ts +85 -85
  136. package/src/swaps/escrow/ToBtcBaseSwapHandler.ts +129 -129
  137. package/src/swaps/escrow/frombtc_abstract/FromBtcAbs.ts +457 -457
  138. package/src/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.ts +61 -61
  139. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.ts +873 -873
  140. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +141 -141
  141. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.ts +866 -866
  142. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.ts +196 -196
  143. package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +920 -920
  144. package/src/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.ts +108 -108
  145. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +1149 -1149
  146. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.ts +80 -80
  147. package/src/swaps/spv_vault_swap/SpvVault.ts +178 -178
  148. package/src/swaps/spv_vault_swap/SpvVaultSwap.ts +228 -228
  149. package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +712 -712
  150. package/src/swaps/spv_vault_swap/SpvVaults.ts +567 -567
  151. package/src/swaps/trusted/frombtc_trusted/FromBtcTrusted.ts +762 -762
  152. package/src/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.ts +185 -185
  153. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +603 -603
  154. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.ts +121 -121
  155. package/src/utils/BitcoinUtils.ts +59 -59
  156. package/src/utils/Utils.ts +104 -104
  157. package/src/utils/paramcoders/IParamReader.ts +7 -7
  158. package/src/utils/paramcoders/IParamWriter.ts +8 -8
  159. package/src/utils/paramcoders/LegacyParamEncoder.ts +27 -27
  160. package/src/utils/paramcoders/ParamDecoder.ts +218 -218
  161. package/src/utils/paramcoders/ParamEncoder.ts +29 -29
  162. package/src/utils/paramcoders/SchemaVerifier.ts +96 -96
  163. package/src/utils/paramcoders/server/ServerParamDecoder.ts +118 -118
  164. package/src/utils/paramcoders/server/ServerParamEncoder.ts +75 -75
  165. package/src/wallets/IBitcoinWallet.ts +76 -76
  166. package/src/wallets/ILightningWallet.ts +200 -178
  167. package/src/wallets/ISpvVaultSigner.ts +10 -10
@@ -1,322 +1,322 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FromBtcAbs = void 0;
4
- const FromBtcSwapAbs_1 = require("./FromBtcSwapAbs");
5
- const SwapHandler_1 = require("../../SwapHandler");
6
- const base_1 = require("@atomiqlabs/base");
7
- const crypto_1 = require("crypto");
8
- const Utils_1 = require("../../../utils/Utils");
9
- const PluginManager_1 = require("../../../plugins/PluginManager");
10
- const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
11
- const ServerParamDecoder_1 = require("../../../utils/paramcoders/server/ServerParamDecoder");
12
- const FromBtcBaseSwapHandler_1 = require("../FromBtcBaseSwapHandler");
13
- /**
14
- * Swap handler handling from BTC swaps using PTLCs (proof-time locked contracts) and btc relay (on-chain bitcoin SPV)
15
- */
16
- class FromBtcAbs extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapHandler {
17
- constructor(storageDirectory, path, chains, bitcoin, swapPricing, config) {
18
- super(storageDirectory, path, chains, swapPricing, config);
19
- this.type = SwapHandler_1.SwapHandlerType.FROM_BTC;
20
- this.swapType = base_1.ChainSwapType.CHAIN;
21
- this.inflightSwapStates = new Set([FromBtcSwapAbs_1.FromBtcSwapState.COMMITED]);
22
- this.bitcoin = bitcoin;
23
- this.config = {
24
- ...config,
25
- swapTsCsvDelta: BigInt(config.swapCsvDelta) * (config.bitcoinBlocktime / config.safetyFactor)
26
- };
27
- }
28
- /**
29
- * Returns the payment hash of the swap, takes swap nonce into account. Payment hash is chain-specific.
30
- *
31
- * @param chainIdentifier
32
- * @param address
33
- * @param amount
34
- */
35
- getHash(chainIdentifier, address, amount) {
36
- const parsedOutputScript = this.bitcoin.toOutputScript(address);
37
- const { swapContract } = this.getChain(chainIdentifier);
38
- return swapContract.getHashForOnchain(parsedOutputScript, amount, this.config.confirmations, 0n);
39
- }
40
- /**
41
- * Processes past swap
42
- *
43
- * @param swap
44
- * @protected
45
- * @returns true if the swap should be refunded, false if nothing should be done
46
- */
47
- async processPastSwap(swap) {
48
- const { swapContract, signer } = this.getChain(swap.chainIdentifier);
49
- //Once authorization expires in CREATED state, the user can no more commit it on-chain
50
- if (swap.state === FromBtcSwapAbs_1.FromBtcSwapState.CREATED) {
51
- if (!await swapContract.isInitAuthorizationExpired(swap.data, swap))
52
- return false;
53
- const isCommited = await swapContract.isCommited(swap.data);
54
- if (isCommited) {
55
- this.swapLogger.info(swap, "processPastSwap(state=CREATED): swap was commited, but processed from watchdog, address: " + swap.address);
56
- await swap.setState(FromBtcSwapAbs_1.FromBtcSwapState.COMMITED);
57
- await this.saveSwapData(swap);
58
- return false;
59
- }
60
- this.swapLogger.info(swap, "processPastSwap(state=CREATED): removing past swap due to authorization expiry, address: " + swap.address);
61
- await this.removeSwapData(swap, FromBtcSwapAbs_1.FromBtcSwapState.CANCELED);
62
- await this.bitcoin.addUnusedAddress(swap.address);
63
- return false;
64
- }
65
- //Check if commited swap expired by now
66
- if (swap.state === FromBtcSwapAbs_1.FromBtcSwapState.COMMITED) {
67
- if (!await swapContract.isExpired(signer.getAddress(), swap.data))
68
- return false;
69
- const isCommited = await swapContract.isCommited(swap.data);
70
- if (isCommited) {
71
- this.swapLogger.info(swap, "processPastSwap(state=COMMITED): swap expired, will refund, address: " + swap.address);
72
- return true;
73
- }
74
- this.swapLogger.warn(swap, "processPastSwap(state=COMMITED): commited swap expired and not committed anymore (already refunded?), address: " + swap.address);
75
- await this.removeSwapData(swap, FromBtcSwapAbs_1.FromBtcSwapState.CANCELED);
76
- return false;
77
- }
78
- }
79
- /**
80
- * Checks past swaps, refunds and deletes ones that are already expired.
81
- */
82
- async processPastSwaps() {
83
- const queriedData = await this.storageManager.query([
84
- {
85
- key: "state",
86
- value: [
87
- FromBtcSwapAbs_1.FromBtcSwapState.CREATED,
88
- FromBtcSwapAbs_1.FromBtcSwapState.COMMITED
89
- ]
90
- }
91
- ]);
92
- const refundSwaps = [];
93
- for (let { obj: swap } of queriedData) {
94
- if (await this.processPastSwap(swap))
95
- refundSwaps.push(swap);
96
- }
97
- await this.refundSwaps(refundSwaps);
98
- }
99
- /**
100
- * Refunds all swaps (calls SC on-chain refund function)
101
- *
102
- * @param refundSwaps
103
- * @protected
104
- */
105
- async refundSwaps(refundSwaps) {
106
- for (let refundSwap of refundSwaps) {
107
- const { swapContract, signer } = this.getChain(refundSwap.chainIdentifier);
108
- const unlock = refundSwap.lock(swapContract.refundTimeout);
109
- if (unlock == null)
110
- continue;
111
- this.swapLogger.debug(refundSwap, "refundSwaps(): initiate refund of swap");
112
- await swapContract.refund(signer, refundSwap.data, true, false, { waitForConfirmation: true });
113
- this.swapLogger.info(refundSwap, "refundSwaps(): swap refunded, address: " + refundSwap.address);
114
- //The swap should be removed by the event handler
115
- await refundSwap.setState(FromBtcSwapAbs_1.FromBtcSwapState.REFUNDED);
116
- unlock();
117
- }
118
- }
119
- async processInitializeEvent(chainIdentifier, savedSwap, event) {
120
- this.swapLogger.info(savedSwap, "SC: InitializeEvent: swap initialized by the client, address: " + savedSwap.address);
121
- if (savedSwap.state === FromBtcSwapAbs_1.FromBtcSwapState.CREATED) {
122
- await savedSwap.setState(FromBtcSwapAbs_1.FromBtcSwapState.COMMITED);
123
- await this.saveSwapData(savedSwap);
124
- }
125
- }
126
- async processClaimEvent(chainIdentifier, savedSwap, event) {
127
- savedSwap.txId = Buffer.from(event.result, "hex").reverse().toString("hex");
128
- this.swapLogger.info(savedSwap, "SC: ClaimEvent: swap successfully claimed by the client, address: " + savedSwap.address);
129
- await this.removeSwapData(savedSwap, FromBtcSwapAbs_1.FromBtcSwapState.CLAIMED);
130
- }
131
- async processRefundEvent(chainIdentifier, savedSwap, event) {
132
- savedSwap.txIds.refund = event.meta?.txId;
133
- this.swapLogger.info(event, "SC: RefundEvent: swap refunded, address: " + savedSwap.address);
134
- await this.removeSwapData(savedSwap, FromBtcSwapAbs_1.FromBtcSwapState.REFUNDED);
135
- await this.bitcoin.addUnusedAddress(savedSwap.address);
136
- }
137
- /**
138
- * Calculates the requested claimer bounty, based on client's request
139
- *
140
- * @param req
141
- * @param expiry
142
- * @param signal
143
- * @throws {DefinedRuntimeError} will throw an error if the plugin cancelled the request
144
- * @returns {Promise<BN>} resulting claimer bounty to be used with the swap
145
- */
146
- async getClaimerBounty(req, expiry, signal) {
147
- const parsedClaimerBounty = await req.paramReader.getParams({
148
- claimerBounty: {
149
- feePerBlock: SchemaVerifier_1.FieldTypeEnum.BigInt,
150
- safetyFactor: SchemaVerifier_1.FieldTypeEnum.BigInt,
151
- startTimestamp: SchemaVerifier_1.FieldTypeEnum.BigInt,
152
- addBlock: SchemaVerifier_1.FieldTypeEnum.BigInt,
153
- addFee: SchemaVerifier_1.FieldTypeEnum.BigInt,
154
- },
155
- }).catch(e => null);
156
- signal.throwIfAborted();
157
- if (parsedClaimerBounty == null || parsedClaimerBounty.claimerBounty == null) {
158
- throw {
159
- code: 20043,
160
- msg: "Invalid claimerBounty"
161
- };
162
- }
163
- const tsDelta = expiry - parsedClaimerBounty.claimerBounty.startTimestamp;
164
- const blocksDelta = tsDelta / this.config.bitcoinBlocktime * parsedClaimerBounty.claimerBounty.safetyFactor;
165
- const totalBlock = blocksDelta + parsedClaimerBounty.claimerBounty.addBlock;
166
- return parsedClaimerBounty.claimerBounty.addFee + (totalBlock * parsedClaimerBounty.claimerBounty.feePerBlock);
167
- }
168
- getDummySwapData(chainIdentifier, useToken, address) {
169
- const { swapContract, signer } = this.getChain(chainIdentifier);
170
- const dummyAmount = BigInt(Math.floor(Math.random() * 0x1000000));
171
- return swapContract.createSwapData(base_1.ChainSwapType.CHAIN, signer.getAddress(), address, useToken, dummyAmount, swapContract.getHashForOnchain((0, crypto_1.randomBytes)(32), dummyAmount, 3, null).toString("hex"), base_1.BigIntBufferUtils.fromBuffer((0, crypto_1.randomBytes)(8)), BigInt(Math.floor(Date.now() / 1000)) + this.config.swapTsCsvDelta, false, true, BigInt(Math.floor(Math.random() * 0x10000)), BigInt(Math.floor(Math.random() * 0x10000)));
172
- }
173
- /**
174
- * Sets up required listeners for the REST server
175
- *
176
- * @param restServer
177
- */
178
- startRestServer(restServer) {
179
- restServer.use(this.path + "/getAddress", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
180
- restServer.post(this.path + "/getAddress", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
181
- const metadata = { request: {}, times: {} };
182
- const chainIdentifier = req.query.chain;
183
- const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
184
- const depositToken = req.query.depositToken ?? chainInterface.getNativeCurrencyAddress();
185
- this.checkAllowedDepositToken(chainIdentifier, depositToken);
186
- metadata.times.requestReceived = Date.now();
187
- /**
188
- * address: string solana address of the recipient
189
- * amount: string amount (in sats) of the invoice
190
- * token: string Desired token to use
191
- * exactOut: boolean Whether the swap should be an exact out instead of exact in swap
192
- * sequence: BN Unique sequence number for the swap
193
- *
194
- *Sent later
195
- * claimerBounty: object Data for calculating claimer bounty
196
- * - feePerBlock: string Fee per block to be synchronized with btc relay
197
- * - safetyFactor: number Safety factor to multiply required blocks (when using 10 min block time)
198
- * - startTimestamp: string UNIX seconds used for timestamp delta calc
199
- * - addBlock: number Additional blocks to add to the calculation
200
- * - addFee: string Additional fee to add to the final claimer bounty
201
- * feeRate: string Fee rate to be used for init signature
202
- */
203
- const parsedBody = await req.paramReader.getParams({
204
- address: (val) => val != null &&
205
- typeof (val) === "string" &&
206
- chainInterface.isValidAddress(val, true) ? val : null,
207
- amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
208
- token: (val) => val != null &&
209
- typeof (val) === "string" &&
210
- this.isTokenSupported(chainIdentifier, val) ? val : null,
211
- sequence: SchemaVerifier_1.FieldTypeEnum.BigInt,
212
- exactOut: SchemaVerifier_1.FieldTypeEnum.BooleanOptional
213
- });
214
- if (parsedBody == null)
215
- throw {
216
- code: 20100,
217
- msg: "Invalid request body"
218
- };
219
- metadata.request = parsedBody;
220
- const requestedAmount = { input: !parsedBody.exactOut, amount: parsedBody.amount, token: parsedBody.token };
221
- const request = {
222
- chainIdentifier,
223
- raw: req,
224
- parsed: parsedBody,
225
- metadata
226
- };
227
- const useToken = parsedBody.token;
228
- //Check request params
229
- this.checkTooManyInflightSwaps();
230
- this.checkSequence(parsedBody.sequence);
231
- const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount);
232
- metadata.times.requestChecked = Date.now();
233
- //Create abortController for parallel prefetches
234
- const responseStream = res.responseStream;
235
- const abortController = (0, Utils_1.getAbortController)(responseStream);
236
- //Pre-fetch data
237
- const { pricePrefetchPromise, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise } = this.getFromBtcPricePrefetches(chainIdentifier, useToken, depositToken, abortController);
238
- const balancePrefetch = this.getBalancePrefetch(chainIdentifier, useToken, abortController);
239
- const signDataPrefetchPromise = this.getSignDataPrefetch(chainIdentifier, abortController, responseStream);
240
- const nativeBalancePrefetch = this.prefetchNativeBalanceIfNeeded(chainIdentifier, abortController);
241
- const dummySwapData = await this.getDummySwapData(chainIdentifier, useToken, parsedBody.address);
242
- abortController.signal.throwIfAborted();
243
- const baseSDPromise = this.getBaseSecurityDepositPrefetch(chainIdentifier, dummySwapData, depositToken, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise, abortController);
244
- await this.checkNativeBalance(chainIdentifier, nativeBalancePrefetch, abortController.signal);
245
- //Check valid amount specified (min/max)
246
- const { amountBD, swapFee, swapFeeInToken, totalInToken, securityDepositApyPPM, securityDepositBaseMultiplierPPM } = await this.AmountAssertions.checkFromBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, abortController.signal);
247
- metadata.times.priceCalculated = Date.now();
248
- if (securityDepositApyPPM != null)
249
- fees.securityDepositApyPPM = securityDepositApyPPM;
250
- if (securityDepositBaseMultiplierPPM != null)
251
- fees.securityDepositBaseMultiplierPPM = securityDepositBaseMultiplierPPM;
252
- //Check if we have enough funds to honor the request
253
- await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
254
- metadata.times.balanceChecked = Date.now();
255
- //Create swap receive bitcoin address
256
- const receiveAddress = await this.bitcoin.getAddress();
257
- abortController.signal.throwIfAborted();
258
- metadata.times.addressCreated = Date.now();
259
- const paymentHash = this.getHash(chainIdentifier, receiveAddress, amountBD);
260
- const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
261
- const expiryTimeout = this.config.swapTsCsvDelta;
262
- const expiry = currentTimestamp + expiryTimeout;
263
- //Calculate security deposit
264
- const totalSecurityDeposit = await this.getSecurityDeposit(chainIdentifier, amountBD, swapFee, expiryTimeout, baseSDPromise, depositToken, depositTokenPricePrefetchPromise, fees, abortController.signal, metadata);
265
- metadata.times.securityDepositCalculated = Date.now();
266
- //Calculate claimer bounty
267
- const totalClaimerBounty = await this.getClaimerBounty(req, expiry, abortController.signal);
268
- metadata.times.claimerBountyCalculated = Date.now();
269
- //Create swap data
270
- const data = await swapContract.createSwapData(base_1.ChainSwapType.CHAIN, signer.getAddress(), parsedBody.address, useToken, totalInToken, paymentHash.toString("hex"), parsedBody.sequence, expiry, false, true, totalSecurityDeposit, totalClaimerBounty, depositToken);
271
- data.setExtraData(swapContract.getExtraData(this.bitcoin.toOutputScript(receiveAddress), amountBD, this.config.confirmations).toString("hex"));
272
- abortController.signal.throwIfAborted();
273
- metadata.times.swapCreated = Date.now();
274
- //Sign the swap
275
- const sigData = await this.getFromBtcSignatureData(chainIdentifier, data, req, abortController.signal, signDataPrefetchPromise);
276
- metadata.times.swapSigned = Date.now();
277
- const createdSwap = new FromBtcSwapAbs_1.FromBtcSwapAbs(chainIdentifier, receiveAddress, this.config.confirmations, amountBD, swapFee, swapFeeInToken);
278
- createdSwap.data = data;
279
- createdSwap.metadata = metadata;
280
- createdSwap.prefix = sigData.prefix;
281
- createdSwap.timeout = sigData.timeout;
282
- createdSwap.signature = sigData.signature;
283
- createdSwap.feeRate = sigData.feeRate;
284
- await PluginManager_1.PluginManager.swapCreate(createdSwap);
285
- await this.saveSwapData(createdSwap);
286
- this.swapLogger.info(createdSwap, "REST: /getAddress: Created swap address: " + receiveAddress + " amount: " + amountBD.toString(10));
287
- await responseStream.writeParamsAndEnd({
288
- code: 20000,
289
- msg: "Success",
290
- data: {
291
- amount: amountBD.toString(10),
292
- btcAddress: receiveAddress,
293
- address: signer.getAddress(),
294
- swapFee: swapFeeInToken.toString(10),
295
- total: totalInToken.toString(10),
296
- confirmations: this.config.confirmations,
297
- data: data.serialize(),
298
- prefix: sigData.prefix,
299
- timeout: sigData.timeout,
300
- signature: sigData.signature
301
- }
302
- });
303
- }));
304
- this.logger.info("REST: Started at path: ", this.path);
305
- }
306
- /**
307
- * Initializes swap handler, loads data and subscribes to chain events
308
- */
309
- async init() {
310
- await this.loadData(FromBtcSwapAbs_1.FromBtcSwapAbs);
311
- this.subscribeToEvents();
312
- await PluginManager_1.PluginManager.serviceInitialize(this);
313
- }
314
- getInfoData() {
315
- return {
316
- confirmations: this.config.confirmations,
317
- cltv: this.config.swapCsvDelta,
318
- timestampCltv: Number(this.config.swapTsCsvDelta)
319
- };
320
- }
321
- }
322
- exports.FromBtcAbs = FromBtcAbs;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FromBtcAbs = void 0;
4
+ const FromBtcSwapAbs_1 = require("./FromBtcSwapAbs");
5
+ const SwapHandler_1 = require("../../SwapHandler");
6
+ const base_1 = require("@atomiqlabs/base");
7
+ const crypto_1 = require("crypto");
8
+ const Utils_1 = require("../../../utils/Utils");
9
+ const PluginManager_1 = require("../../../plugins/PluginManager");
10
+ const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
11
+ const ServerParamDecoder_1 = require("../../../utils/paramcoders/server/ServerParamDecoder");
12
+ const FromBtcBaseSwapHandler_1 = require("../FromBtcBaseSwapHandler");
13
+ /**
14
+ * Swap handler handling from BTC swaps using PTLCs (proof-time locked contracts) and btc relay (on-chain bitcoin SPV)
15
+ */
16
+ class FromBtcAbs extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapHandler {
17
+ constructor(storageDirectory, path, chains, bitcoin, swapPricing, config) {
18
+ super(storageDirectory, path, chains, swapPricing, config);
19
+ this.type = SwapHandler_1.SwapHandlerType.FROM_BTC;
20
+ this.swapType = base_1.ChainSwapType.CHAIN;
21
+ this.inflightSwapStates = new Set([FromBtcSwapAbs_1.FromBtcSwapState.COMMITED]);
22
+ this.bitcoin = bitcoin;
23
+ this.config = {
24
+ ...config,
25
+ swapTsCsvDelta: BigInt(config.swapCsvDelta) * (config.bitcoinBlocktime / config.safetyFactor)
26
+ };
27
+ }
28
+ /**
29
+ * Returns the payment hash of the swap, takes swap nonce into account. Payment hash is chain-specific.
30
+ *
31
+ * @param chainIdentifier
32
+ * @param address
33
+ * @param amount
34
+ */
35
+ getHash(chainIdentifier, address, amount) {
36
+ const parsedOutputScript = this.bitcoin.toOutputScript(address);
37
+ const { swapContract } = this.getChain(chainIdentifier);
38
+ return swapContract.getHashForOnchain(parsedOutputScript, amount, this.config.confirmations, 0n);
39
+ }
40
+ /**
41
+ * Processes past swap
42
+ *
43
+ * @param swap
44
+ * @protected
45
+ * @returns true if the swap should be refunded, false if nothing should be done
46
+ */
47
+ async processPastSwap(swap) {
48
+ const { swapContract, signer } = this.getChain(swap.chainIdentifier);
49
+ //Once authorization expires in CREATED state, the user can no more commit it on-chain
50
+ if (swap.state === FromBtcSwapAbs_1.FromBtcSwapState.CREATED) {
51
+ if (!await swapContract.isInitAuthorizationExpired(swap.data, swap))
52
+ return false;
53
+ const isCommited = await swapContract.isCommited(swap.data);
54
+ if (isCommited) {
55
+ this.swapLogger.info(swap, "processPastSwap(state=CREATED): swap was commited, but processed from watchdog, address: " + swap.address);
56
+ await swap.setState(FromBtcSwapAbs_1.FromBtcSwapState.COMMITED);
57
+ await this.saveSwapData(swap);
58
+ return false;
59
+ }
60
+ this.swapLogger.info(swap, "processPastSwap(state=CREATED): removing past swap due to authorization expiry, address: " + swap.address);
61
+ await this.removeSwapData(swap, FromBtcSwapAbs_1.FromBtcSwapState.CANCELED);
62
+ await this.bitcoin.addUnusedAddress(swap.address);
63
+ return false;
64
+ }
65
+ //Check if commited swap expired by now
66
+ if (swap.state === FromBtcSwapAbs_1.FromBtcSwapState.COMMITED) {
67
+ if (!await swapContract.isExpired(signer.getAddress(), swap.data))
68
+ return false;
69
+ const isCommited = await swapContract.isCommited(swap.data);
70
+ if (isCommited) {
71
+ this.swapLogger.info(swap, "processPastSwap(state=COMMITED): swap expired, will refund, address: " + swap.address);
72
+ return true;
73
+ }
74
+ this.swapLogger.warn(swap, "processPastSwap(state=COMMITED): commited swap expired and not committed anymore (already refunded?), address: " + swap.address);
75
+ await this.removeSwapData(swap, FromBtcSwapAbs_1.FromBtcSwapState.CANCELED);
76
+ return false;
77
+ }
78
+ }
79
+ /**
80
+ * Checks past swaps, refunds and deletes ones that are already expired.
81
+ */
82
+ async processPastSwaps() {
83
+ const queriedData = await this.storageManager.query([
84
+ {
85
+ key: "state",
86
+ value: [
87
+ FromBtcSwapAbs_1.FromBtcSwapState.CREATED,
88
+ FromBtcSwapAbs_1.FromBtcSwapState.COMMITED
89
+ ]
90
+ }
91
+ ]);
92
+ const refundSwaps = [];
93
+ for (let { obj: swap } of queriedData) {
94
+ if (await this.processPastSwap(swap))
95
+ refundSwaps.push(swap);
96
+ }
97
+ await this.refundSwaps(refundSwaps);
98
+ }
99
+ /**
100
+ * Refunds all swaps (calls SC on-chain refund function)
101
+ *
102
+ * @param refundSwaps
103
+ * @protected
104
+ */
105
+ async refundSwaps(refundSwaps) {
106
+ for (let refundSwap of refundSwaps) {
107
+ const { swapContract, signer } = this.getChain(refundSwap.chainIdentifier);
108
+ const unlock = refundSwap.lock(swapContract.refundTimeout);
109
+ if (unlock == null)
110
+ continue;
111
+ this.swapLogger.debug(refundSwap, "refundSwaps(): initiate refund of swap");
112
+ await swapContract.refund(signer, refundSwap.data, true, false, { waitForConfirmation: true });
113
+ this.swapLogger.info(refundSwap, "refundSwaps(): swap refunded, address: " + refundSwap.address);
114
+ //The swap should be removed by the event handler
115
+ await refundSwap.setState(FromBtcSwapAbs_1.FromBtcSwapState.REFUNDED);
116
+ unlock();
117
+ }
118
+ }
119
+ async processInitializeEvent(chainIdentifier, savedSwap, event) {
120
+ this.swapLogger.info(savedSwap, "SC: InitializeEvent: swap initialized by the client, address: " + savedSwap.address);
121
+ if (savedSwap.state === FromBtcSwapAbs_1.FromBtcSwapState.CREATED) {
122
+ await savedSwap.setState(FromBtcSwapAbs_1.FromBtcSwapState.COMMITED);
123
+ await this.saveSwapData(savedSwap);
124
+ }
125
+ }
126
+ async processClaimEvent(chainIdentifier, savedSwap, event) {
127
+ savedSwap.txId = Buffer.from(event.result, "hex").reverse().toString("hex");
128
+ this.swapLogger.info(savedSwap, "SC: ClaimEvent: swap successfully claimed by the client, address: " + savedSwap.address);
129
+ await this.removeSwapData(savedSwap, FromBtcSwapAbs_1.FromBtcSwapState.CLAIMED);
130
+ }
131
+ async processRefundEvent(chainIdentifier, savedSwap, event) {
132
+ savedSwap.txIds.refund = event.meta?.txId;
133
+ this.swapLogger.info(event, "SC: RefundEvent: swap refunded, address: " + savedSwap.address);
134
+ await this.removeSwapData(savedSwap, FromBtcSwapAbs_1.FromBtcSwapState.REFUNDED);
135
+ await this.bitcoin.addUnusedAddress(savedSwap.address);
136
+ }
137
+ /**
138
+ * Calculates the requested claimer bounty, based on client's request
139
+ *
140
+ * @param req
141
+ * @param expiry
142
+ * @param signal
143
+ * @throws {DefinedRuntimeError} will throw an error if the plugin cancelled the request
144
+ * @returns {Promise<BN>} resulting claimer bounty to be used with the swap
145
+ */
146
+ async getClaimerBounty(req, expiry, signal) {
147
+ const parsedClaimerBounty = await req.paramReader.getParams({
148
+ claimerBounty: {
149
+ feePerBlock: SchemaVerifier_1.FieldTypeEnum.BigInt,
150
+ safetyFactor: SchemaVerifier_1.FieldTypeEnum.BigInt,
151
+ startTimestamp: SchemaVerifier_1.FieldTypeEnum.BigInt,
152
+ addBlock: SchemaVerifier_1.FieldTypeEnum.BigInt,
153
+ addFee: SchemaVerifier_1.FieldTypeEnum.BigInt,
154
+ },
155
+ }).catch(e => null);
156
+ signal.throwIfAborted();
157
+ if (parsedClaimerBounty == null || parsedClaimerBounty.claimerBounty == null) {
158
+ throw {
159
+ code: 20043,
160
+ msg: "Invalid claimerBounty"
161
+ };
162
+ }
163
+ const tsDelta = expiry - parsedClaimerBounty.claimerBounty.startTimestamp;
164
+ const blocksDelta = tsDelta / this.config.bitcoinBlocktime * parsedClaimerBounty.claimerBounty.safetyFactor;
165
+ const totalBlock = blocksDelta + parsedClaimerBounty.claimerBounty.addBlock;
166
+ return parsedClaimerBounty.claimerBounty.addFee + (totalBlock * parsedClaimerBounty.claimerBounty.feePerBlock);
167
+ }
168
+ getDummySwapData(chainIdentifier, useToken, address) {
169
+ const { swapContract, signer } = this.getChain(chainIdentifier);
170
+ const dummyAmount = BigInt(Math.floor(Math.random() * 0x1000000));
171
+ return swapContract.createSwapData(base_1.ChainSwapType.CHAIN, signer.getAddress(), address, useToken, dummyAmount, swapContract.getHashForOnchain((0, crypto_1.randomBytes)(32), dummyAmount, 3, null).toString("hex"), base_1.BigIntBufferUtils.fromBuffer((0, crypto_1.randomBytes)(8)), BigInt(Math.floor(Date.now() / 1000)) + this.config.swapTsCsvDelta, false, true, BigInt(Math.floor(Math.random() * 0x10000)), BigInt(Math.floor(Math.random() * 0x10000)));
172
+ }
173
+ /**
174
+ * Sets up required listeners for the REST server
175
+ *
176
+ * @param restServer
177
+ */
178
+ startRestServer(restServer) {
179
+ restServer.use(this.path + "/getAddress", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
180
+ restServer.post(this.path + "/getAddress", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
181
+ const metadata = { request: {}, times: {} };
182
+ const chainIdentifier = req.query.chain;
183
+ const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
184
+ const depositToken = req.query.depositToken ?? chainInterface.getNativeCurrencyAddress();
185
+ this.checkAllowedDepositToken(chainIdentifier, depositToken);
186
+ metadata.times.requestReceived = Date.now();
187
+ /**
188
+ * address: string solana address of the recipient
189
+ * amount: string amount (in sats) of the invoice
190
+ * token: string Desired token to use
191
+ * exactOut: boolean Whether the swap should be an exact out instead of exact in swap
192
+ * sequence: BN Unique sequence number for the swap
193
+ *
194
+ *Sent later
195
+ * claimerBounty: object Data for calculating claimer bounty
196
+ * - feePerBlock: string Fee per block to be synchronized with btc relay
197
+ * - safetyFactor: number Safety factor to multiply required blocks (when using 10 min block time)
198
+ * - startTimestamp: string UNIX seconds used for timestamp delta calc
199
+ * - addBlock: number Additional blocks to add to the calculation
200
+ * - addFee: string Additional fee to add to the final claimer bounty
201
+ * feeRate: string Fee rate to be used for init signature
202
+ */
203
+ const parsedBody = await req.paramReader.getParams({
204
+ address: (val) => val != null &&
205
+ typeof (val) === "string" &&
206
+ chainInterface.isValidAddress(val, true) ? val : null,
207
+ amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
208
+ token: (val) => val != null &&
209
+ typeof (val) === "string" &&
210
+ this.isTokenSupported(chainIdentifier, val) ? val : null,
211
+ sequence: SchemaVerifier_1.FieldTypeEnum.BigInt,
212
+ exactOut: SchemaVerifier_1.FieldTypeEnum.BooleanOptional
213
+ });
214
+ if (parsedBody == null)
215
+ throw {
216
+ code: 20100,
217
+ msg: "Invalid request body"
218
+ };
219
+ metadata.request = parsedBody;
220
+ const requestedAmount = { input: !parsedBody.exactOut, amount: parsedBody.amount, token: parsedBody.token };
221
+ const request = {
222
+ chainIdentifier,
223
+ raw: req,
224
+ parsed: parsedBody,
225
+ metadata
226
+ };
227
+ const useToken = parsedBody.token;
228
+ //Check request params
229
+ this.checkTooManyInflightSwaps();
230
+ this.checkSequence(parsedBody.sequence);
231
+ const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount);
232
+ metadata.times.requestChecked = Date.now();
233
+ //Create abortController for parallel prefetches
234
+ const responseStream = res.responseStream;
235
+ const abortController = (0, Utils_1.getAbortController)(responseStream);
236
+ //Pre-fetch data
237
+ const { pricePrefetchPromise, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise } = this.getFromBtcPricePrefetches(chainIdentifier, useToken, depositToken, abortController);
238
+ const balancePrefetch = this.getBalancePrefetch(chainIdentifier, useToken, abortController);
239
+ const signDataPrefetchPromise = this.getSignDataPrefetch(chainIdentifier, abortController, responseStream);
240
+ const nativeBalancePrefetch = this.prefetchNativeBalanceIfNeeded(chainIdentifier, abortController);
241
+ const dummySwapData = await this.getDummySwapData(chainIdentifier, useToken, parsedBody.address);
242
+ abortController.signal.throwIfAborted();
243
+ const baseSDPromise = this.getBaseSecurityDepositPrefetch(chainIdentifier, dummySwapData, depositToken, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise, abortController);
244
+ await this.checkNativeBalance(chainIdentifier, nativeBalancePrefetch, abortController.signal);
245
+ //Check valid amount specified (min/max)
246
+ const { amountBD, swapFee, swapFeeInToken, totalInToken, securityDepositApyPPM, securityDepositBaseMultiplierPPM } = await this.AmountAssertions.checkFromBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, abortController.signal);
247
+ metadata.times.priceCalculated = Date.now();
248
+ if (securityDepositApyPPM != null)
249
+ fees.securityDepositApyPPM = securityDepositApyPPM;
250
+ if (securityDepositBaseMultiplierPPM != null)
251
+ fees.securityDepositBaseMultiplierPPM = securityDepositBaseMultiplierPPM;
252
+ //Check if we have enough funds to honor the request
253
+ await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
254
+ metadata.times.balanceChecked = Date.now();
255
+ //Create swap receive bitcoin address
256
+ const receiveAddress = await this.bitcoin.getAddress();
257
+ abortController.signal.throwIfAborted();
258
+ metadata.times.addressCreated = Date.now();
259
+ const paymentHash = this.getHash(chainIdentifier, receiveAddress, amountBD);
260
+ const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
261
+ const expiryTimeout = this.config.swapTsCsvDelta;
262
+ const expiry = currentTimestamp + expiryTimeout;
263
+ //Calculate security deposit
264
+ const totalSecurityDeposit = await this.getSecurityDeposit(chainIdentifier, amountBD, swapFee, expiryTimeout, baseSDPromise, depositToken, depositTokenPricePrefetchPromise, fees, abortController.signal, metadata);
265
+ metadata.times.securityDepositCalculated = Date.now();
266
+ //Calculate claimer bounty
267
+ const totalClaimerBounty = await this.getClaimerBounty(req, expiry, abortController.signal);
268
+ metadata.times.claimerBountyCalculated = Date.now();
269
+ //Create swap data
270
+ const data = await swapContract.createSwapData(base_1.ChainSwapType.CHAIN, signer.getAddress(), parsedBody.address, useToken, totalInToken, paymentHash.toString("hex"), parsedBody.sequence, expiry, false, true, totalSecurityDeposit, totalClaimerBounty, depositToken);
271
+ data.setExtraData(swapContract.getExtraData(this.bitcoin.toOutputScript(receiveAddress), amountBD, this.config.confirmations).toString("hex"));
272
+ abortController.signal.throwIfAborted();
273
+ metadata.times.swapCreated = Date.now();
274
+ //Sign the swap
275
+ const sigData = await this.getFromBtcSignatureData(chainIdentifier, data, req, abortController.signal, signDataPrefetchPromise);
276
+ metadata.times.swapSigned = Date.now();
277
+ const createdSwap = new FromBtcSwapAbs_1.FromBtcSwapAbs(chainIdentifier, receiveAddress, this.config.confirmations, amountBD, swapFee, swapFeeInToken);
278
+ createdSwap.data = data;
279
+ createdSwap.metadata = metadata;
280
+ createdSwap.prefix = sigData.prefix;
281
+ createdSwap.timeout = sigData.timeout;
282
+ createdSwap.signature = sigData.signature;
283
+ createdSwap.feeRate = sigData.feeRate;
284
+ await PluginManager_1.PluginManager.swapCreate(createdSwap);
285
+ await this.saveSwapData(createdSwap);
286
+ this.swapLogger.info(createdSwap, "REST: /getAddress: Created swap address: " + receiveAddress + " amount: " + amountBD.toString(10));
287
+ await responseStream.writeParamsAndEnd({
288
+ code: 20000,
289
+ msg: "Success",
290
+ data: {
291
+ amount: amountBD.toString(10),
292
+ btcAddress: receiveAddress,
293
+ address: signer.getAddress(),
294
+ swapFee: swapFeeInToken.toString(10),
295
+ total: totalInToken.toString(10),
296
+ confirmations: this.config.confirmations,
297
+ data: data.serialize(),
298
+ prefix: sigData.prefix,
299
+ timeout: sigData.timeout,
300
+ signature: sigData.signature
301
+ }
302
+ });
303
+ }));
304
+ this.logger.info("REST: Started at path: ", this.path);
305
+ }
306
+ /**
307
+ * Initializes swap handler, loads data and subscribes to chain events
308
+ */
309
+ async init() {
310
+ await this.loadData(FromBtcSwapAbs_1.FromBtcSwapAbs);
311
+ this.subscribeToEvents();
312
+ await PluginManager_1.PluginManager.serviceInitialize(this);
313
+ }
314
+ getInfoData() {
315
+ return {
316
+ confirmations: this.config.confirmations,
317
+ cltv: this.config.swapCsvDelta,
318
+ timestampCltv: Number(this.config.swapTsCsvDelta)
319
+ };
320
+ }
321
+ }
322
+ exports.FromBtcAbs = FromBtcAbs;