@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,468 +1,468 @@
1
- import {Express, Request, Response} from "express";
2
- import {FromBtcSwapAbs, FromBtcSwapState} from "./FromBtcSwapAbs";
3
- import {MultichainData, SwapHandlerType} from "../../SwapHandler";
4
- import {ISwapPrice} from "../../../prices/ISwapPrice";
5
- import {
6
- BigIntBufferUtils,
7
- ChainSwapType,
8
- ClaimEvent,
9
- InitializeEvent,
10
- RefundEvent,
11
- SwapData
12
- } from "@atomiqlabs/base";
13
- import {randomBytes} from "crypto";
14
- import {expressHandlerWrapper, getAbortController} from "../../../utils/Utils";
15
- import {PluginManager} from "../../../plugins/PluginManager";
16
- import {IIntermediaryStorage} from "../../../storage/IIntermediaryStorage";
17
- import {FieldTypeEnum} from "../../../utils/paramcoders/SchemaVerifier";
18
- import {serverParamDecoder} from "../../../utils/paramcoders/server/ServerParamDecoder";
19
- import {IParamReader} from "../../../utils/paramcoders/IParamReader";
20
- import {ServerParamEncoder} from "../../../utils/paramcoders/server/ServerParamEncoder";
21
- import {FromBtcBaseConfig, FromBtcBaseSwapHandler} from "../FromBtcBaseSwapHandler";
22
- import {IBitcoinWallet} from "../../../wallets/IBitcoinWallet";
23
- import {isQuoteThrow} from "../../../plugins/IPlugin";
24
- import {FromBtcLnSwapState} from "../frombtcln_abstract/FromBtcLnSwapAbs";
25
-
26
- export type FromBtcConfig = FromBtcBaseConfig & {
27
- confirmations: number,
28
- swapCsvDelta: number
29
- };
30
-
31
- export type FromBtcRequestType = {
32
- address: string,
33
- amount: bigint,
34
- token: string,
35
- sequence: bigint,
36
- exactOut?: boolean
37
- };
38
-
39
- /**
40
- * Swap handler handling from BTC swaps using PTLCs (proof-time locked contracts) and btc relay (on-chain bitcoin SPV)
41
- */
42
- export class FromBtcAbs extends FromBtcBaseSwapHandler<FromBtcSwapAbs, FromBtcSwapState> {
43
- readonly type = SwapHandlerType.FROM_BTC;
44
- readonly swapType = ChainSwapType.CHAIN;
45
- readonly inflightSwapStates = new Set([FromBtcSwapState.COMMITED]);
46
-
47
- readonly config: FromBtcConfig & {swapTsCsvDelta: bigint};
48
-
49
- readonly bitcoin: IBitcoinWallet;
50
-
51
- constructor(
52
- storageDirectory: IIntermediaryStorage<FromBtcSwapAbs>,
53
- path: string,
54
- chains: MultichainData,
55
- bitcoin: IBitcoinWallet,
56
- swapPricing: ISwapPrice,
57
- config: FromBtcConfig
58
- ) {
59
- super(storageDirectory, path, chains, swapPricing, config);
60
- this.bitcoin = bitcoin;
61
- this.config = {
62
- ...config,
63
- swapTsCsvDelta: BigInt(config.swapCsvDelta) * (config.bitcoinBlocktime / config.safetyFactor)
64
- };
65
- }
66
-
67
- /**
68
- * Returns the payment hash of the swap, takes swap nonce into account. Payment hash is chain-specific.
69
- *
70
- * @param chainIdentifier
71
- * @param address
72
- * @param amount
73
- */
74
- private getHash(chainIdentifier: string, address: string, amount: bigint): Buffer {
75
- const parsedOutputScript = this.bitcoin.toOutputScript(address);
76
- const {swapContract} = this.getChain(chainIdentifier);
77
- return swapContract.getHashForOnchain(parsedOutputScript, amount, this.config.confirmations, 0n);
78
- }
79
-
80
- /**
81
- * Processes past swap
82
- *
83
- * @param swap
84
- * @protected
85
- * @returns true if the swap should be refunded, false if nothing should be done
86
- */
87
- protected async processPastSwap(swap: FromBtcSwapAbs): Promise<boolean> {
88
- const {swapContract, signer} = this.getChain(swap.chainIdentifier);
89
-
90
- //Once authorization expires in CREATED state, the user can no more commit it on-chain
91
- if(swap.state===FromBtcSwapState.CREATED) {
92
- if(!await swapContract.isInitAuthorizationExpired(swap.data, swap)) return false;
93
-
94
- const isCommited = await swapContract.isCommited(swap.data);
95
- if(isCommited) {
96
- this.swapLogger.info(swap, "processPastSwap(state=CREATED): swap was commited, but processed from watchdog, address: "+swap.address);
97
- await swap.setState(FromBtcSwapState.COMMITED);
98
- await this.saveSwapData(swap);
99
- return false;
100
- }
101
-
102
- this.swapLogger.info(swap, "processPastSwap(state=CREATED): removing past swap due to authorization expiry, address: "+swap.address);
103
- await this.removeSwapData(swap, FromBtcSwapState.CANCELED);
104
- await this.bitcoin.addUnusedAddress(swap.address);
105
- return false;
106
- }
107
-
108
- //Check if commited swap expired by now
109
- if(swap.state===FromBtcSwapState.COMMITED) {
110
- if(!await swapContract.isExpired(signer.getAddress(), swap.data)) return false;
111
-
112
- const isCommited = await swapContract.isCommited(swap.data);
113
- if(isCommited) {
114
- this.swapLogger.info(swap, "processPastSwap(state=COMMITED): swap expired, will refund, address: "+swap.address);
115
- return true;
116
- }
117
-
118
- this.swapLogger.warn(swap, "processPastSwap(state=COMMITED): commited swap expired and not committed anymore (already refunded?), address: "+swap.address);
119
- await this.removeSwapData(swap, FromBtcSwapState.CANCELED);
120
- return false;
121
- }
122
- }
123
-
124
- /**
125
- * Checks past swaps, refunds and deletes ones that are already expired.
126
- */
127
- protected async processPastSwaps() {
128
-
129
- const queriedData = await this.storageManager.query([
130
- {
131
- key: "state",
132
- value: [
133
- FromBtcSwapState.CREATED,
134
- FromBtcSwapState.COMMITED
135
- ]
136
- }
137
- ]);
138
-
139
- const refundSwaps: FromBtcSwapAbs[] = [];
140
-
141
- for(let {obj: swap} of queriedData) {
142
- if(await this.processPastSwap(swap)) refundSwaps.push(swap);
143
- }
144
-
145
- await this.refundSwaps(refundSwaps);
146
- }
147
-
148
- /**
149
- * Refunds all swaps (calls SC on-chain refund function)
150
- *
151
- * @param refundSwaps
152
- * @protected
153
- */
154
- protected async refundSwaps(refundSwaps: FromBtcSwapAbs[]) {
155
- for(let refundSwap of refundSwaps) {
156
- const {swapContract, signer} = this.getChain(refundSwap.chainIdentifier);
157
- const unlock = refundSwap.lock(swapContract.refundTimeout);
158
- if(unlock==null) continue;
159
- this.swapLogger.debug(refundSwap, "refundSwaps(): initiate refund of swap");
160
- await swapContract.refund(signer, refundSwap.data, true, false, {waitForConfirmation: true});
161
- this.swapLogger.info(refundSwap, "refundSwaps(): swap refunded, address: "+refundSwap.address);
162
- //The swap should be removed by the event handler
163
- await refundSwap.setState(FromBtcSwapState.REFUNDED);
164
- unlock();
165
- }
166
- }
167
-
168
- protected async processInitializeEvent(chainIdentifier: string, savedSwap: FromBtcSwapAbs, event: InitializeEvent<SwapData>) {
169
- this.swapLogger.info(savedSwap, "SC: InitializeEvent: swap initialized by the client, address: "+savedSwap.address);
170
-
171
- if(savedSwap.state===FromBtcSwapState.CREATED) {
172
- await savedSwap.setState(FromBtcSwapState.COMMITED);
173
- await this.saveSwapData(savedSwap);
174
- }
175
- }
176
-
177
- protected async processClaimEvent(chainIdentifier: string, savedSwap: FromBtcSwapAbs, event: ClaimEvent<SwapData>): Promise<void> {
178
- savedSwap.txId = Buffer.from(event.result, "hex").reverse().toString("hex");
179
-
180
- this.swapLogger.info(savedSwap, "SC: ClaimEvent: swap successfully claimed by the client, address: "+savedSwap.address);
181
- await this.removeSwapData(savedSwap, FromBtcSwapState.CLAIMED);
182
- }
183
-
184
- protected async processRefundEvent(chainIdentifier: string, savedSwap: FromBtcSwapAbs, event: RefundEvent<SwapData>) {
185
- savedSwap.txIds.refund = (event as any).meta?.txId;
186
-
187
- this.swapLogger.info(event, "SC: RefundEvent: swap refunded, address: "+savedSwap.address);
188
- await this.removeSwapData(savedSwap, FromBtcSwapState.REFUNDED);
189
- await this.bitcoin.addUnusedAddress(savedSwap.address);
190
- }
191
-
192
- /**
193
- * Calculates the requested claimer bounty, based on client's request
194
- *
195
- * @param req
196
- * @param expiry
197
- * @param signal
198
- * @throws {DefinedRuntimeError} will throw an error if the plugin cancelled the request
199
- * @returns {Promise<BN>} resulting claimer bounty to be used with the swap
200
- */
201
- private async getClaimerBounty(req: Request & {paramReader: IParamReader}, expiry: bigint, signal: AbortSignal): Promise<bigint> {
202
- const parsedClaimerBounty = await req.paramReader.getParams({
203
- claimerBounty: {
204
- feePerBlock: FieldTypeEnum.BigInt,
205
- safetyFactor: FieldTypeEnum.BigInt,
206
- startTimestamp: FieldTypeEnum.BigInt,
207
- addBlock: FieldTypeEnum.BigInt,
208
- addFee: FieldTypeEnum.BigInt,
209
- },
210
- }).catch(e => null);
211
-
212
- signal.throwIfAborted();
213
-
214
- if(parsedClaimerBounty==null || parsedClaimerBounty.claimerBounty==null) {
215
- throw {
216
- code: 20043,
217
- msg: "Invalid claimerBounty"
218
- };
219
- }
220
-
221
- const tsDelta: bigint = expiry - parsedClaimerBounty.claimerBounty.startTimestamp;
222
- const blocksDelta: bigint = tsDelta / this.config.bitcoinBlocktime * parsedClaimerBounty.claimerBounty.safetyFactor;
223
- const totalBlock: bigint = blocksDelta + parsedClaimerBounty.claimerBounty.addBlock;
224
- return parsedClaimerBounty.claimerBounty.addFee + (totalBlock * parsedClaimerBounty.claimerBounty.feePerBlock);
225
- }
226
-
227
- private getDummySwapData(chainIdentifier: string, useToken: string, address: string): Promise<SwapData> {
228
- const {swapContract, signer} = this.getChain(chainIdentifier);
229
- const dummyAmount = BigInt(Math.floor(Math.random() * 0x1000000));
230
- return swapContract.createSwapData(
231
- ChainSwapType.CHAIN,
232
- signer.getAddress(),
233
- address,
234
- useToken,
235
- dummyAmount,
236
- swapContract.getHashForOnchain(randomBytes(32), dummyAmount, 3, null).toString("hex"),
237
- BigIntBufferUtils.fromBuffer(randomBytes(8)),
238
- BigInt(Math.floor(Date.now()/1000)) + this.config.swapTsCsvDelta,
239
- false,
240
- true,
241
- BigInt(Math.floor(Math.random() * 0x10000)),
242
- BigInt(Math.floor(Math.random() * 0x10000))
243
- );
244
- }
245
-
246
- /**
247
- * Sets up required listeners for the REST server
248
- *
249
- * @param restServer
250
- */
251
- startRestServer(restServer: Express) {
252
-
253
- restServer.use(this.path+"/getAddress", serverParamDecoder(10*1000));
254
- restServer.post(this.path+"/getAddress", expressHandlerWrapper(async (req: Request & {paramReader: IParamReader}, res: Response & {responseStream: ServerParamEncoder}) => {
255
- const metadata: {
256
- request: any,
257
- times: {[key: string]: number},
258
- } = {request: {}, times: {}};
259
-
260
- const chainIdentifier = req.query.chain as string;
261
- const {swapContract, signer, chainInterface} = this.getChain(chainIdentifier);
262
- const depositToken = req.query.depositToken as string ?? chainInterface.getNativeCurrencyAddress();
263
- this.checkAllowedDepositToken(chainIdentifier, depositToken);
264
-
265
- metadata.times.requestReceived = Date.now();
266
- /**
267
- * address: string solana address of the recipient
268
- * amount: string amount (in sats) of the invoice
269
- * token: string Desired token to use
270
- * exactOut: boolean Whether the swap should be an exact out instead of exact in swap
271
- * sequence: BN Unique sequence number for the swap
272
- *
273
- *Sent later
274
- * claimerBounty: object Data for calculating claimer bounty
275
- * - feePerBlock: string Fee per block to be synchronized with btc relay
276
- * - safetyFactor: number Safety factor to multiply required blocks (when using 10 min block time)
277
- * - startTimestamp: string UNIX seconds used for timestamp delta calc
278
- * - addBlock: number Additional blocks to add to the calculation
279
- * - addFee: string Additional fee to add to the final claimer bounty
280
- * feeRate: string Fee rate to be used for init signature
281
- */
282
- const parsedBody: FromBtcRequestType = await req.paramReader.getParams({
283
- address: (val: string) => val!=null &&
284
- typeof(val)==="string" &&
285
- chainInterface.isValidAddress(val, true) ? val : null,
286
- amount: FieldTypeEnum.BigInt,
287
- token: (val: string) => val!=null &&
288
- typeof(val)==="string" &&
289
- this.isTokenSupported(chainIdentifier, val) ? val : null,
290
- sequence: FieldTypeEnum.BigInt,
291
- exactOut: FieldTypeEnum.BooleanOptional
292
- });
293
- if(parsedBody==null) throw {
294
- code: 20100,
295
- msg: "Invalid request body"
296
- };
297
- metadata.request = parsedBody;
298
-
299
- const requestedAmount = {input: !parsedBody.exactOut, amount: parsedBody.amount, token: parsedBody.token};
300
- const request = {
301
- chainIdentifier,
302
- raw: req,
303
- parsed: parsedBody,
304
- metadata
305
- };
306
- const useToken = parsedBody.token;
307
-
308
- //Check request params
309
- this.checkTooManyInflightSwaps();
310
- this.checkSequence(parsedBody.sequence);
311
- const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount);
312
- metadata.times.requestChecked = Date.now();
313
-
314
- //Create abortController for parallel prefetches
315
- const responseStream = res.responseStream;
316
- const abortController = getAbortController(responseStream);
317
-
318
- //Pre-fetch data
319
- const {
320
- pricePrefetchPromise,
321
- gasTokenPricePrefetchPromise,
322
- depositTokenPricePrefetchPromise
323
- } = this.getFromBtcPricePrefetches(chainIdentifier, useToken, depositToken, abortController);
324
- const balancePrefetch: Promise<bigint> = this.getBalancePrefetch(chainIdentifier, useToken, abortController);
325
- const signDataPrefetchPromise: Promise<any> = this.getSignDataPrefetch(chainIdentifier, abortController, responseStream);
326
- const nativeBalancePrefetch = this.prefetchNativeBalanceIfNeeded(chainIdentifier, abortController);
327
-
328
- const dummySwapData = await this.getDummySwapData(chainIdentifier, useToken, parsedBody.address);
329
- abortController.signal.throwIfAborted();
330
- const baseSDPromise: Promise<bigint> = this.getBaseSecurityDepositPrefetch(
331
- chainIdentifier, dummySwapData, depositToken,
332
- gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise,
333
- abortController
334
- );
335
-
336
- await this.checkNativeBalance(chainIdentifier, nativeBalancePrefetch, abortController.signal);
337
-
338
- //Check valid amount specified (min/max)
339
- const {
340
- amountBD,
341
- swapFee,
342
- swapFeeInToken,
343
- totalInToken,
344
- securityDepositApyPPM,
345
- securityDepositBaseMultiplierPPM
346
- } = await this.AmountAssertions.checkFromBtcAmount(this.type, request, {...requestedAmount, pricePrefetch: pricePrefetchPromise}, fees, abortController.signal);
347
- metadata.times.priceCalculated = Date.now();
348
-
349
- if(securityDepositApyPPM!=null) fees.securityDepositApyPPM = securityDepositApyPPM;
350
- if(securityDepositBaseMultiplierPPM!=null) fees.securityDepositBaseMultiplierPPM = securityDepositBaseMultiplierPPM;
351
-
352
- //Check if we have enough funds to honor the request
353
- await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
354
- metadata.times.balanceChecked = Date.now();
355
-
356
- //Create swap receive bitcoin address
357
- const receiveAddress = await this.bitcoin.getAddress();
358
- abortController.signal.throwIfAborted();
359
- metadata.times.addressCreated = Date.now();
360
-
361
- const paymentHash = this.getHash(chainIdentifier, receiveAddress, amountBD);
362
- const currentTimestamp = BigInt(Math.floor(Date.now()/1000));
363
- const expiryTimeout = this.config.swapTsCsvDelta;
364
- const expiry = currentTimestamp + expiryTimeout;
365
-
366
- //Calculate security deposit
367
- const totalSecurityDeposit = await this.getSecurityDeposit(
368
- chainIdentifier, amountBD, swapFee, expiryTimeout,
369
- baseSDPromise, depositToken, depositTokenPricePrefetchPromise, fees,
370
- abortController.signal, metadata
371
- );
372
- metadata.times.securityDepositCalculated = Date.now();
373
-
374
- //Calculate claimer bounty
375
- const totalClaimerBounty = await this.getClaimerBounty(req, expiry, abortController.signal);
376
- metadata.times.claimerBountyCalculated = Date.now();
377
-
378
- //Create swap data
379
- const data: SwapData = await swapContract.createSwapData(
380
- ChainSwapType.CHAIN,
381
- signer.getAddress(),
382
- parsedBody.address,
383
- useToken,
384
- totalInToken,
385
- paymentHash.toString("hex"),
386
- parsedBody.sequence,
387
- expiry,
388
- false,
389
- true,
390
- totalSecurityDeposit,
391
- totalClaimerBounty,
392
- depositToken
393
- );
394
- data.setExtraData(swapContract.getExtraData(
395
- this.bitcoin.toOutputScript(receiveAddress),
396
- amountBD,
397
- this.config.confirmations
398
- ).toString("hex"));
399
- abortController.signal.throwIfAborted();
400
- metadata.times.swapCreated = Date.now();
401
-
402
- //Sign the swap
403
- const sigData = await this.getFromBtcSignatureData(chainIdentifier, data, req, abortController.signal, signDataPrefetchPromise);
404
- metadata.times.swapSigned = Date.now();
405
-
406
- const createdSwap: FromBtcSwapAbs = new FromBtcSwapAbs(chainIdentifier, receiveAddress, this.config.confirmations, amountBD, swapFee, swapFeeInToken);
407
- createdSwap.data = data;
408
- createdSwap.metadata = metadata;
409
- createdSwap.prefix = sigData.prefix;
410
- createdSwap.timeout = sigData.timeout;
411
- createdSwap.signature = sigData.signature;
412
- createdSwap.feeRate = sigData.feeRate;
413
-
414
- const pluginCheckResult = await PluginManager.onHandlePreFromBtcExecute(
415
- SwapHandlerType.FROM_BTC,
416
- createdSwap
417
- );
418
- if(isQuoteThrow(pluginCheckResult)) throw {
419
- code: 29999,
420
- msg: pluginCheckResult.message
421
- };
422
-
423
- await PluginManager.swapCreate(createdSwap);
424
- await this.saveSwapData(createdSwap);
425
-
426
- this.swapLogger.info(createdSwap, "REST: /getAddress: Created swap address: "+receiveAddress+" amount: "+amountBD.toString(10));
427
-
428
- await responseStream.writeParamsAndEnd({
429
- code: 20000,
430
- msg: "Success",
431
- data: {
432
- amount: amountBD.toString(10),
433
- btcAddress: receiveAddress,
434
- address: signer.getAddress(),
435
- swapFee: swapFeeInToken.toString(10),
436
- total: totalInToken.toString(10),
437
- confirmations: this.config.confirmations,
438
- data: data.serialize(),
439
- prefix: sigData.prefix,
440
- timeout: sigData.timeout,
441
- signature: sigData.signature
442
- }
443
- });
444
-
445
- }));
446
-
447
- this.logger.info("REST: Started at path: ", this.path);
448
- }
449
-
450
- /**
451
- * Initializes swap handler, loads data and subscribes to chain events
452
- */
453
- async init() {
454
- await this.loadData(FromBtcSwapAbs);
455
- this.subscribeToEvents();
456
- await PluginManager.serviceInitialize(this);
457
- }
458
-
459
- getInfoData(): any {
460
- return {
461
- confirmations: this.config.confirmations,
462
-
463
- cltv: this.config.swapCsvDelta,
464
- timestampCltv: Number(this.config.swapTsCsvDelta)
465
- };
466
- }
467
-
468
- }
1
+ import {Express, Request, Response} from "express";
2
+ import {FromBtcSwapAbs, FromBtcSwapState} from "./FromBtcSwapAbs";
3
+ import {MultichainData, SwapHandlerType} from "../../SwapHandler";
4
+ import {ISwapPrice} from "../../../prices/ISwapPrice";
5
+ import {
6
+ BigIntBufferUtils,
7
+ ChainSwapType,
8
+ ClaimEvent,
9
+ InitializeEvent,
10
+ RefundEvent,
11
+ SwapData
12
+ } from "@atomiqlabs/base";
13
+ import {randomBytes} from "crypto";
14
+ import {expressHandlerWrapper, getAbortController} from "../../../utils/Utils";
15
+ import {PluginManager} from "../../../plugins/PluginManager";
16
+ import {IIntermediaryStorage} from "../../../storage/IIntermediaryStorage";
17
+ import {FieldTypeEnum} from "../../../utils/paramcoders/SchemaVerifier";
18
+ import {serverParamDecoder} from "../../../utils/paramcoders/server/ServerParamDecoder";
19
+ import {IParamReader} from "../../../utils/paramcoders/IParamReader";
20
+ import {ServerParamEncoder} from "../../../utils/paramcoders/server/ServerParamEncoder";
21
+ import {FromBtcBaseConfig, FromBtcBaseSwapHandler} from "../FromBtcBaseSwapHandler";
22
+ import {IBitcoinWallet} from "../../../wallets/IBitcoinWallet";
23
+ import {isQuoteThrow} from "../../../plugins/IPlugin";
24
+ import {FromBtcLnSwapState} from "../frombtcln_abstract/FromBtcLnSwapAbs";
25
+
26
+ export type FromBtcConfig = FromBtcBaseConfig & {
27
+ confirmations: number,
28
+ swapCsvDelta: number
29
+ };
30
+
31
+ export type FromBtcRequestType = {
32
+ address: string,
33
+ amount: bigint,
34
+ token: string,
35
+ sequence: bigint,
36
+ exactOut?: boolean
37
+ };
38
+
39
+ /**
40
+ * Swap handler handling from BTC swaps using PTLCs (proof-time locked contracts) and btc relay (on-chain bitcoin SPV)
41
+ */
42
+ export class FromBtcAbs extends FromBtcBaseSwapHandler<FromBtcSwapAbs, FromBtcSwapState> {
43
+ readonly type = SwapHandlerType.FROM_BTC;
44
+ readonly swapType = ChainSwapType.CHAIN;
45
+ readonly inflightSwapStates = new Set([FromBtcSwapState.COMMITED]);
46
+
47
+ readonly config: FromBtcConfig & {swapTsCsvDelta: bigint};
48
+
49
+ readonly bitcoin: IBitcoinWallet;
50
+
51
+ constructor(
52
+ storageDirectory: IIntermediaryStorage<FromBtcSwapAbs>,
53
+ path: string,
54
+ chains: MultichainData,
55
+ bitcoin: IBitcoinWallet,
56
+ swapPricing: ISwapPrice,
57
+ config: FromBtcConfig
58
+ ) {
59
+ super(storageDirectory, path, chains, swapPricing, config);
60
+ this.bitcoin = bitcoin;
61
+ this.config = {
62
+ ...config,
63
+ swapTsCsvDelta: BigInt(config.swapCsvDelta) * (config.bitcoinBlocktime / config.safetyFactor)
64
+ };
65
+ }
66
+
67
+ /**
68
+ * Returns the payment hash of the swap, takes swap nonce into account. Payment hash is chain-specific.
69
+ *
70
+ * @param chainIdentifier
71
+ * @param address
72
+ * @param amount
73
+ */
74
+ private getHash(chainIdentifier: string, address: string, amount: bigint): Buffer {
75
+ const parsedOutputScript = this.bitcoin.toOutputScript(address);
76
+ const {swapContract} = this.getChain(chainIdentifier);
77
+ return swapContract.getHashForOnchain(parsedOutputScript, amount, this.config.confirmations, 0n);
78
+ }
79
+
80
+ /**
81
+ * Processes past swap
82
+ *
83
+ * @param swap
84
+ * @protected
85
+ * @returns true if the swap should be refunded, false if nothing should be done
86
+ */
87
+ protected async processPastSwap(swap: FromBtcSwapAbs): Promise<boolean> {
88
+ const {swapContract, signer} = this.getChain(swap.chainIdentifier);
89
+
90
+ //Once authorization expires in CREATED state, the user can no more commit it on-chain
91
+ if(swap.state===FromBtcSwapState.CREATED) {
92
+ if(!await swapContract.isInitAuthorizationExpired(swap.data, swap)) return false;
93
+
94
+ const isCommited = await swapContract.isCommited(swap.data);
95
+ if(isCommited) {
96
+ this.swapLogger.info(swap, "processPastSwap(state=CREATED): swap was commited, but processed from watchdog, address: "+swap.address);
97
+ await swap.setState(FromBtcSwapState.COMMITED);
98
+ await this.saveSwapData(swap);
99
+ return false;
100
+ }
101
+
102
+ this.swapLogger.info(swap, "processPastSwap(state=CREATED): removing past swap due to authorization expiry, address: "+swap.address);
103
+ await this.removeSwapData(swap, FromBtcSwapState.CANCELED);
104
+ await this.bitcoin.addUnusedAddress(swap.address);
105
+ return false;
106
+ }
107
+
108
+ //Check if commited swap expired by now
109
+ if(swap.state===FromBtcSwapState.COMMITED) {
110
+ if(!await swapContract.isExpired(signer.getAddress(), swap.data)) return false;
111
+
112
+ const isCommited = await swapContract.isCommited(swap.data);
113
+ if(isCommited) {
114
+ this.swapLogger.info(swap, "processPastSwap(state=COMMITED): swap expired, will refund, address: "+swap.address);
115
+ return true;
116
+ }
117
+
118
+ this.swapLogger.warn(swap, "processPastSwap(state=COMMITED): commited swap expired and not committed anymore (already refunded?), address: "+swap.address);
119
+ await this.removeSwapData(swap, FromBtcSwapState.CANCELED);
120
+ return false;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Checks past swaps, refunds and deletes ones that are already expired.
126
+ */
127
+ protected async processPastSwaps() {
128
+
129
+ const queriedData = await this.storageManager.query([
130
+ {
131
+ key: "state",
132
+ value: [
133
+ FromBtcSwapState.CREATED,
134
+ FromBtcSwapState.COMMITED
135
+ ]
136
+ }
137
+ ]);
138
+
139
+ const refundSwaps: FromBtcSwapAbs[] = [];
140
+
141
+ for(let {obj: swap} of queriedData) {
142
+ if(await this.processPastSwap(swap)) refundSwaps.push(swap);
143
+ }
144
+
145
+ await this.refundSwaps(refundSwaps);
146
+ }
147
+
148
+ /**
149
+ * Refunds all swaps (calls SC on-chain refund function)
150
+ *
151
+ * @param refundSwaps
152
+ * @protected
153
+ */
154
+ protected async refundSwaps(refundSwaps: FromBtcSwapAbs[]) {
155
+ for(let refundSwap of refundSwaps) {
156
+ const {swapContract, signer} = this.getChain(refundSwap.chainIdentifier);
157
+ const unlock = refundSwap.lock(swapContract.refundTimeout);
158
+ if(unlock==null) continue;
159
+ this.swapLogger.debug(refundSwap, "refundSwaps(): initiate refund of swap");
160
+ await swapContract.refund(signer, refundSwap.data, true, false, {waitForConfirmation: true});
161
+ this.swapLogger.info(refundSwap, "refundSwaps(): swap refunded, address: "+refundSwap.address);
162
+ //The swap should be removed by the event handler
163
+ await refundSwap.setState(FromBtcSwapState.REFUNDED);
164
+ unlock();
165
+ }
166
+ }
167
+
168
+ protected async processInitializeEvent(chainIdentifier: string, savedSwap: FromBtcSwapAbs, event: InitializeEvent<SwapData>) {
169
+ this.swapLogger.info(savedSwap, "SC: InitializeEvent: swap initialized by the client, address: "+savedSwap.address);
170
+
171
+ if(savedSwap.state===FromBtcSwapState.CREATED) {
172
+ await savedSwap.setState(FromBtcSwapState.COMMITED);
173
+ await this.saveSwapData(savedSwap);
174
+ }
175
+ }
176
+
177
+ protected async processClaimEvent(chainIdentifier: string, savedSwap: FromBtcSwapAbs, event: ClaimEvent<SwapData>): Promise<void> {
178
+ savedSwap.txId = Buffer.from(event.result, "hex").reverse().toString("hex");
179
+
180
+ this.swapLogger.info(savedSwap, "SC: ClaimEvent: swap successfully claimed by the client, address: "+savedSwap.address);
181
+ await this.removeSwapData(savedSwap, FromBtcSwapState.CLAIMED);
182
+ }
183
+
184
+ protected async processRefundEvent(chainIdentifier: string, savedSwap: FromBtcSwapAbs, event: RefundEvent<SwapData>) {
185
+ savedSwap.txIds.refund = (event as any).meta?.txId;
186
+
187
+ this.swapLogger.info(event, "SC: RefundEvent: swap refunded, address: "+savedSwap.address);
188
+ await this.removeSwapData(savedSwap, FromBtcSwapState.REFUNDED);
189
+ await this.bitcoin.addUnusedAddress(savedSwap.address);
190
+ }
191
+
192
+ /**
193
+ * Calculates the requested claimer bounty, based on client's request
194
+ *
195
+ * @param req
196
+ * @param expiry
197
+ * @param signal
198
+ * @throws {DefinedRuntimeError} will throw an error if the plugin cancelled the request
199
+ * @returns {Promise<BN>} resulting claimer bounty to be used with the swap
200
+ */
201
+ private async getClaimerBounty(req: Request & {paramReader: IParamReader}, expiry: bigint, signal: AbortSignal): Promise<bigint> {
202
+ const parsedClaimerBounty = await req.paramReader.getParams({
203
+ claimerBounty: {
204
+ feePerBlock: FieldTypeEnum.BigInt,
205
+ safetyFactor: FieldTypeEnum.BigInt,
206
+ startTimestamp: FieldTypeEnum.BigInt,
207
+ addBlock: FieldTypeEnum.BigInt,
208
+ addFee: FieldTypeEnum.BigInt,
209
+ },
210
+ }).catch(e => null);
211
+
212
+ signal.throwIfAborted();
213
+
214
+ if(parsedClaimerBounty==null || parsedClaimerBounty.claimerBounty==null) {
215
+ throw {
216
+ code: 20043,
217
+ msg: "Invalid claimerBounty"
218
+ };
219
+ }
220
+
221
+ const tsDelta: bigint = expiry - parsedClaimerBounty.claimerBounty.startTimestamp;
222
+ const blocksDelta: bigint = tsDelta / this.config.bitcoinBlocktime * parsedClaimerBounty.claimerBounty.safetyFactor;
223
+ const totalBlock: bigint = blocksDelta + parsedClaimerBounty.claimerBounty.addBlock;
224
+ return parsedClaimerBounty.claimerBounty.addFee + (totalBlock * parsedClaimerBounty.claimerBounty.feePerBlock);
225
+ }
226
+
227
+ private getDummySwapData(chainIdentifier: string, useToken: string, address: string): Promise<SwapData> {
228
+ const {swapContract, signer} = this.getChain(chainIdentifier);
229
+ const dummyAmount = BigInt(Math.floor(Math.random() * 0x1000000));
230
+ return swapContract.createSwapData(
231
+ ChainSwapType.CHAIN,
232
+ signer.getAddress(),
233
+ address,
234
+ useToken,
235
+ dummyAmount,
236
+ swapContract.getHashForOnchain(randomBytes(32), dummyAmount, 3, null).toString("hex"),
237
+ BigIntBufferUtils.fromBuffer(randomBytes(8)),
238
+ BigInt(Math.floor(Date.now()/1000)) + this.config.swapTsCsvDelta,
239
+ false,
240
+ true,
241
+ BigInt(Math.floor(Math.random() * 0x10000)),
242
+ BigInt(Math.floor(Math.random() * 0x10000))
243
+ );
244
+ }
245
+
246
+ /**
247
+ * Sets up required listeners for the REST server
248
+ *
249
+ * @param restServer
250
+ */
251
+ startRestServer(restServer: Express) {
252
+
253
+ restServer.use(this.path+"/getAddress", serverParamDecoder(10*1000));
254
+ restServer.post(this.path+"/getAddress", expressHandlerWrapper(async (req: Request & {paramReader: IParamReader}, res: Response & {responseStream: ServerParamEncoder}) => {
255
+ const metadata: {
256
+ request: any,
257
+ times: {[key: string]: number},
258
+ } = {request: {}, times: {}};
259
+
260
+ const chainIdentifier = req.query.chain as string;
261
+ const {swapContract, signer, chainInterface} = this.getChain(chainIdentifier);
262
+ const depositToken = req.query.depositToken as string ?? chainInterface.getNativeCurrencyAddress();
263
+ this.checkAllowedDepositToken(chainIdentifier, depositToken);
264
+
265
+ metadata.times.requestReceived = Date.now();
266
+ /**
267
+ * address: string solana address of the recipient
268
+ * amount: string amount (in sats) of the invoice
269
+ * token: string Desired token to use
270
+ * exactOut: boolean Whether the swap should be an exact out instead of exact in swap
271
+ * sequence: BN Unique sequence number for the swap
272
+ *
273
+ *Sent later
274
+ * claimerBounty: object Data for calculating claimer bounty
275
+ * - feePerBlock: string Fee per block to be synchronized with btc relay
276
+ * - safetyFactor: number Safety factor to multiply required blocks (when using 10 min block time)
277
+ * - startTimestamp: string UNIX seconds used for timestamp delta calc
278
+ * - addBlock: number Additional blocks to add to the calculation
279
+ * - addFee: string Additional fee to add to the final claimer bounty
280
+ * feeRate: string Fee rate to be used for init signature
281
+ */
282
+ const parsedBody: FromBtcRequestType = await req.paramReader.getParams({
283
+ address: (val: string) => val!=null &&
284
+ typeof(val)==="string" &&
285
+ chainInterface.isValidAddress(val, true) ? val : null,
286
+ amount: FieldTypeEnum.BigInt,
287
+ token: (val: string) => val!=null &&
288
+ typeof(val)==="string" &&
289
+ this.isTokenSupported(chainIdentifier, val) ? val : null,
290
+ sequence: FieldTypeEnum.BigInt,
291
+ exactOut: FieldTypeEnum.BooleanOptional
292
+ });
293
+ if(parsedBody==null) throw {
294
+ code: 20100,
295
+ msg: "Invalid request body"
296
+ };
297
+ metadata.request = parsedBody;
298
+
299
+ const requestedAmount = {input: !parsedBody.exactOut, amount: parsedBody.amount, token: parsedBody.token};
300
+ const request = {
301
+ chainIdentifier,
302
+ raw: req,
303
+ parsed: parsedBody,
304
+ metadata
305
+ };
306
+ const useToken = parsedBody.token;
307
+
308
+ //Check request params
309
+ this.checkTooManyInflightSwaps();
310
+ this.checkSequence(parsedBody.sequence);
311
+ const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount);
312
+ metadata.times.requestChecked = Date.now();
313
+
314
+ //Create abortController for parallel prefetches
315
+ const responseStream = res.responseStream;
316
+ const abortController = getAbortController(responseStream);
317
+
318
+ //Pre-fetch data
319
+ const {
320
+ pricePrefetchPromise,
321
+ gasTokenPricePrefetchPromise,
322
+ depositTokenPricePrefetchPromise
323
+ } = this.getFromBtcPricePrefetches(chainIdentifier, useToken, depositToken, abortController);
324
+ const balancePrefetch: Promise<bigint> = this.getBalancePrefetch(chainIdentifier, useToken, abortController);
325
+ const signDataPrefetchPromise: Promise<any> = this.getSignDataPrefetch(chainIdentifier, abortController, responseStream);
326
+ const nativeBalancePrefetch = this.prefetchNativeBalanceIfNeeded(chainIdentifier, abortController);
327
+
328
+ const dummySwapData = await this.getDummySwapData(chainIdentifier, useToken, parsedBody.address);
329
+ abortController.signal.throwIfAborted();
330
+ const baseSDPromise: Promise<bigint> = this.getBaseSecurityDepositPrefetch(
331
+ chainIdentifier, dummySwapData, depositToken,
332
+ gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise,
333
+ abortController
334
+ );
335
+
336
+ await this.checkNativeBalance(chainIdentifier, nativeBalancePrefetch, abortController.signal);
337
+
338
+ //Check valid amount specified (min/max)
339
+ const {
340
+ amountBD,
341
+ swapFee,
342
+ swapFeeInToken,
343
+ totalInToken,
344
+ securityDepositApyPPM,
345
+ securityDepositBaseMultiplierPPM
346
+ } = await this.AmountAssertions.checkFromBtcAmount(this.type, request, {...requestedAmount, pricePrefetch: pricePrefetchPromise}, fees, abortController.signal);
347
+ metadata.times.priceCalculated = Date.now();
348
+
349
+ if(securityDepositApyPPM!=null) fees.securityDepositApyPPM = securityDepositApyPPM;
350
+ if(securityDepositBaseMultiplierPPM!=null) fees.securityDepositBaseMultiplierPPM = securityDepositBaseMultiplierPPM;
351
+
352
+ //Check if we have enough funds to honor the request
353
+ await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
354
+ metadata.times.balanceChecked = Date.now();
355
+
356
+ //Create swap receive bitcoin address
357
+ const receiveAddress = await this.bitcoin.getAddress();
358
+ abortController.signal.throwIfAborted();
359
+ metadata.times.addressCreated = Date.now();
360
+
361
+ const paymentHash = this.getHash(chainIdentifier, receiveAddress, amountBD);
362
+ const currentTimestamp = BigInt(Math.floor(Date.now()/1000));
363
+ const expiryTimeout = this.config.swapTsCsvDelta;
364
+ const expiry = currentTimestamp + expiryTimeout;
365
+
366
+ //Calculate security deposit
367
+ const totalSecurityDeposit = await this.getSecurityDeposit(
368
+ chainIdentifier, amountBD, swapFee, expiryTimeout,
369
+ baseSDPromise, depositToken, depositTokenPricePrefetchPromise, fees,
370
+ abortController.signal, metadata
371
+ );
372
+ metadata.times.securityDepositCalculated = Date.now();
373
+
374
+ //Calculate claimer bounty
375
+ const totalClaimerBounty = await this.getClaimerBounty(req, expiry, abortController.signal);
376
+ metadata.times.claimerBountyCalculated = Date.now();
377
+
378
+ //Create swap data
379
+ const data: SwapData = await swapContract.createSwapData(
380
+ ChainSwapType.CHAIN,
381
+ signer.getAddress(),
382
+ parsedBody.address,
383
+ useToken,
384
+ totalInToken,
385
+ paymentHash.toString("hex"),
386
+ parsedBody.sequence,
387
+ expiry,
388
+ false,
389
+ true,
390
+ totalSecurityDeposit,
391
+ totalClaimerBounty,
392
+ depositToken
393
+ );
394
+ data.setExtraData(swapContract.getExtraData(
395
+ this.bitcoin.toOutputScript(receiveAddress),
396
+ amountBD,
397
+ this.config.confirmations
398
+ ).toString("hex"));
399
+ abortController.signal.throwIfAborted();
400
+ metadata.times.swapCreated = Date.now();
401
+
402
+ //Sign the swap
403
+ const sigData = await this.getFromBtcSignatureData(chainIdentifier, data, req, abortController.signal, signDataPrefetchPromise);
404
+ metadata.times.swapSigned = Date.now();
405
+
406
+ const createdSwap: FromBtcSwapAbs = new FromBtcSwapAbs(chainIdentifier, receiveAddress, this.config.confirmations, amountBD, swapFee, swapFeeInToken);
407
+ createdSwap.data = data;
408
+ createdSwap.metadata = metadata;
409
+ createdSwap.prefix = sigData.prefix;
410
+ createdSwap.timeout = sigData.timeout;
411
+ createdSwap.signature = sigData.signature;
412
+ createdSwap.feeRate = sigData.feeRate;
413
+
414
+ const pluginCheckResult = await PluginManager.onHandlePreFromBtcExecute(
415
+ SwapHandlerType.FROM_BTC,
416
+ createdSwap
417
+ );
418
+ if(isQuoteThrow(pluginCheckResult)) throw {
419
+ code: 29999,
420
+ msg: pluginCheckResult.message
421
+ };
422
+
423
+ await PluginManager.swapCreate(createdSwap);
424
+ await this.saveSwapData(createdSwap);
425
+
426
+ this.swapLogger.info(createdSwap, "REST: /getAddress: Created swap address: "+receiveAddress+" amount: "+amountBD.toString(10));
427
+
428
+ await responseStream.writeParamsAndEnd({
429
+ code: 20000,
430
+ msg: "Success",
431
+ data: {
432
+ amount: amountBD.toString(10),
433
+ btcAddress: receiveAddress,
434
+ address: signer.getAddress(),
435
+ swapFee: swapFeeInToken.toString(10),
436
+ total: totalInToken.toString(10),
437
+ confirmations: this.config.confirmations,
438
+ data: data.serialize(),
439
+ prefix: sigData.prefix,
440
+ timeout: sigData.timeout,
441
+ signature: sigData.signature
442
+ }
443
+ });
444
+
445
+ }));
446
+
447
+ this.logger.info("REST: Started at path: ", this.path);
448
+ }
449
+
450
+ /**
451
+ * Initializes swap handler, loads data and subscribes to chain events
452
+ */
453
+ async init() {
454
+ await this.loadData(FromBtcSwapAbs);
455
+ this.subscribeToEvents();
456
+ await PluginManager.serviceInitialize(this);
457
+ }
458
+
459
+ getInfoData(): any {
460
+ return {
461
+ confirmations: this.config.confirmations,
462
+
463
+ cltv: this.config.swapCsvDelta,
464
+ timestampCltv: Number(this.config.swapTsCsvDelta)
465
+ };
466
+ }
467
+
468
+ }