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