@atomiqlabs/lp-lib 11.0.5 → 12.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/info/InfoHandler.js +3 -12
  2. package/dist/plugins/IPlugin.d.ts +34 -35
  3. package/dist/plugins/IPlugin.js +7 -8
  4. package/dist/plugins/PluginManager.d.ts +29 -30
  5. package/dist/plugins/PluginManager.js +160 -188
  6. package/dist/prices/BinanceSwapPrice.d.ts +1 -2
  7. package/dist/prices/BinanceSwapPrice.js +56 -70
  8. package/dist/prices/CoinGeckoSwapPrice.d.ts +2 -3
  9. package/dist/prices/CoinGeckoSwapPrice.js +30 -42
  10. package/dist/prices/OKXSwapPrice.d.ts +1 -2
  11. package/dist/prices/OKXSwapPrice.js +56 -70
  12. package/dist/storage/IIntermediaryStorage.d.ts +8 -5
  13. package/dist/storagemanager/IntermediaryStorageManager.d.ts +8 -5
  14. package/dist/storagemanager/IntermediaryStorageManager.js +52 -61
  15. package/dist/storagemanager/StorageManager.js +42 -59
  16. package/dist/swaps/FromBtcBaseSwap.d.ts +7 -8
  17. package/dist/swaps/FromBtcBaseSwap.js +2 -3
  18. package/dist/swaps/FromBtcBaseSwapHandler.d.ts +44 -31
  19. package/dist/swaps/FromBtcBaseSwapHandler.js +217 -196
  20. package/dist/swaps/FromBtcLnBaseSwapHandler.d.ts +1 -2
  21. package/dist/swaps/FromBtcLnBaseSwapHandler.js +13 -24
  22. package/dist/swaps/ISwapPrice.d.ts +4 -5
  23. package/dist/swaps/ISwapPrice.js +8 -30
  24. package/dist/swaps/SwapHandler.d.ts +26 -15
  25. package/dist/swaps/SwapHandler.js +107 -66
  26. package/dist/swaps/SwapHandlerSwap.d.ts +22 -11
  27. package/dist/swaps/SwapHandlerSwap.js +32 -8
  28. package/dist/swaps/ToBtcBaseSwap.d.ts +16 -17
  29. package/dist/swaps/ToBtcBaseSwap.js +4 -4
  30. package/dist/swaps/ToBtcBaseSwapHandler.d.ts +17 -17
  31. package/dist/swaps/ToBtcBaseSwapHandler.js +140 -155
  32. package/dist/swaps/frombtc_abstract/FromBtcAbs.d.ts +8 -15
  33. package/dist/swaps/frombtc_abstract/FromBtcAbs.js +131 -196
  34. package/dist/swaps/frombtc_abstract/FromBtcSwapAbs.d.ts +3 -5
  35. package/dist/swaps/frombtc_abstract/FromBtcSwapAbs.js +4 -4
  36. package/dist/swaps/frombtc_trusted/FromBtcTrusted.d.ts +10 -8
  37. package/dist/swaps/frombtc_trusted/FromBtcTrusted.js +330 -362
  38. package/dist/swaps/frombtc_trusted/FromBtcTrustedSwap.d.ts +10 -10
  39. package/dist/swaps/frombtc_trusted/FromBtcTrustedSwap.js +7 -4
  40. package/dist/swaps/frombtcln_abstract/FromBtcLnAbs.d.ts +8 -8
  41. package/dist/swaps/frombtcln_abstract/FromBtcLnAbs.js +330 -400
  42. package/dist/swaps/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +10 -4
  43. package/dist/swaps/frombtcln_abstract/FromBtcLnSwapAbs.js +36 -6
  44. package/dist/swaps/frombtcln_trusted/FromBtcLnTrusted.d.ts +8 -7
  45. package/dist/swaps/frombtcln_trusted/FromBtcLnTrusted.js +251 -273
  46. package/dist/swaps/frombtcln_trusted/FromBtcLnTrustedSwap.d.ts +5 -5
  47. package/dist/swaps/frombtcln_trusted/FromBtcLnTrustedSwap.js +7 -5
  48. package/dist/swaps/tobtc_abstract/ToBtcAbs.d.ts +13 -12
  49. package/dist/swaps/tobtc_abstract/ToBtcAbs.js +261 -323
  50. package/dist/swaps/tobtc_abstract/ToBtcSwapAbs.d.ts +4 -4
  51. package/dist/swaps/tobtc_abstract/ToBtcSwapAbs.js +7 -6
  52. package/dist/swaps/tobtcln_abstract/ToBtcLnAbs.d.ts +22 -21
  53. package/dist/swaps/tobtcln_abstract/ToBtcLnAbs.js +398 -453
  54. package/dist/swaps/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +3 -2
  55. package/dist/swaps/tobtcln_abstract/ToBtcLnSwapAbs.js +10 -6
  56. package/dist/utils/Utils.d.ts +2 -3
  57. package/dist/utils/Utils.js +4 -14
  58. package/dist/utils/paramcoders/LegacyParamEncoder.js +3 -14
  59. package/dist/utils/paramcoders/ParamDecoder.js +53 -65
  60. package/dist/utils/paramcoders/SchemaVerifier.d.ts +4 -5
  61. package/dist/utils/paramcoders/SchemaVerifier.js +8 -9
  62. package/dist/utils/paramcoders/server/ServerParamDecoder.js +1 -1
  63. package/dist/utils/paramcoders/server/ServerParamEncoder.js +3 -14
  64. package/dist/wallets/IBitcoinWallet.d.ts +4 -5
  65. package/dist/wallets/ILightningWallet.d.ts +20 -21
  66. package/dist/wallets/ILightningWallet.js +1 -1
  67. package/package.json +4 -6
  68. package/src/plugins/IPlugin.ts +28 -29
  69. package/src/plugins/PluginManager.ts +21 -22
  70. package/src/prices/BinanceSwapPrice.ts +3 -4
  71. package/src/prices/CoinGeckoSwapPrice.ts +4 -5
  72. package/src/prices/OKXSwapPrice.ts +3 -4
  73. package/src/storage/IIntermediaryStorage.ts +4 -5
  74. package/src/storagemanager/IntermediaryStorageManager.ts +17 -9
  75. package/src/swaps/FromBtcBaseSwap.ts +9 -10
  76. package/src/swaps/FromBtcBaseSwapHandler.ts +133 -91
  77. package/src/swaps/FromBtcLnBaseSwapHandler.ts +2 -3
  78. package/src/swaps/ISwapPrice.ts +10 -20
  79. package/src/swaps/SwapHandler.ts +101 -35
  80. package/src/swaps/SwapHandlerSwap.ts +42 -17
  81. package/src/swaps/ToBtcBaseSwap.ts +20 -18
  82. package/src/swaps/ToBtcBaseSwapHandler.ts +33 -33
  83. package/src/swaps/frombtc_abstract/FromBtcAbs.ts +64 -97
  84. package/src/swaps/frombtc_abstract/FromBtcSwapAbs.ts +7 -8
  85. package/src/swaps/frombtc_trusted/FromBtcTrusted.ts +56 -55
  86. package/src/swaps/frombtc_trusted/FromBtcTrustedSwap.ts +28 -21
  87. package/src/swaps/frombtcln_abstract/FromBtcLnAbs.ts +81 -116
  88. package/src/swaps/frombtcln_abstract/FromBtcLnSwapAbs.ts +73 -9
  89. package/src/swaps/frombtcln_trusted/FromBtcLnTrusted.ts +39 -36
  90. package/src/swaps/frombtcln_trusted/FromBtcLnTrustedSwap.ts +26 -12
  91. package/src/swaps/tobtc_abstract/ToBtcAbs.ts +82 -98
  92. package/src/swaps/tobtc_abstract/ToBtcSwapAbs.ts +25 -20
  93. package/src/swaps/tobtcln_abstract/ToBtcLnAbs.ts +106 -118
  94. package/src/swaps/tobtcln_abstract/ToBtcLnSwapAbs.ts +17 -9
  95. package/src/utils/Utils.ts +3 -4
  96. package/src/utils/paramcoders/ParamDecoder.ts +5 -5
  97. package/src/utils/paramcoders/SchemaVerifier.ts +10 -11
  98. package/src/utils/paramcoders/server/ServerParamDecoder.ts +1 -1
  99. package/src/wallets/IBitcoinWallet.ts +4 -5
  100. package/src/wallets/ILightningWallet.ts +21 -22
@@ -1,16 +1,6 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.ToBtcLnAbs = void 0;
13
- const BN = require("bn.js");
14
4
  const ToBtcLnSwapAbs_1 = require("./ToBtcLnSwapAbs");
15
5
  const SwapHandler_1 = require("../SwapHandler");
16
6
  const base_1 = require("@atomiqlabs/base");
@@ -30,13 +20,14 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
30
20
  this.LIGHTNING_LIQUIDITY_CACHE_TIMEOUT = 5 * 1000;
31
21
  this.activeSubscriptions = new Set();
32
22
  this.type = SwapHandler_1.SwapHandlerType.TO_BTCLN;
23
+ this.swapType = base_1.ChainSwapType.HTLC;
33
24
  this.exactInAuths = {};
34
25
  this.lightning = lightning;
35
26
  const anyConfig = config;
36
- anyConfig.minTsSendCltv = config.gracePeriod.add(config.bitcoinBlocktime.mul(config.minSendCltv).mul(config.safetyFactor));
27
+ anyConfig.minTsSendCltv = config.gracePeriod + (config.bitcoinBlocktime * config.minSendCltv * config.safetyFactor);
37
28
  this.config = anyConfig;
38
- this.config.minLnRoutingFeePPM = this.config.minLnRoutingFeePPM || new BN(1000);
39
- this.config.minLnBaseFee = this.config.minLnBaseFee || new BN(5);
29
+ this.config.minLnRoutingFeePPM = this.config.minLnRoutingFeePPM || 1000n;
30
+ this.config.minLnBaseFee = this.config.minLnBaseFee || 5n;
40
31
  this.config.exactInExpiry = this.config.exactInExpiry || 10 * 1000;
41
32
  }
42
33
  /**
@@ -53,69 +44,65 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
53
44
  }
54
45
  }
55
46
  }
56
- processPastSwap(swap) {
57
- return __awaiter(this, void 0, void 0, function* () {
58
- const { swapContract, signer } = this.getChain(swap.chainIdentifier);
59
- if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED) {
60
- //Cancel the swaps where signature is expired
61
- const isSignatureExpired = yield swapContract.isInitAuthorizationExpired(swap.data, swap);
62
- if (isSignatureExpired) {
63
- const isCommitted = yield swapContract.isCommited(swap.data);
64
- if (!isCommitted) {
65
- this.swapLogger.info(swap, "processPastSwap(state=SAVED): authorization expired & swap not committed, cancelling swap, invoice: " + swap.pr);
66
- yield this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CANCELED);
67
- return;
68
- }
69
- else {
70
- this.swapLogger.info(swap, "processPastSwap(state=SAVED): swap committed (detected from processPastSwap), invoice: " + swap.pr);
71
- yield swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED);
72
- yield this.storageManager.saveData(swap.data.getHash(), swap.getSequence(), swap);
73
- }
74
- }
75
- //Cancel the swaps where lightning invoice is expired
76
- const decodedPR = yield this.lightning.parsePaymentRequest(swap.pr);
77
- const isInvoiceExpired = decodedPR.expiryEpochMillis < Date.now();
78
- if (isInvoiceExpired) {
79
- this.swapLogger.info(swap, "processPastSwap(state=SAVED): invoice expired, cancel uncommited swap, invoice: " + swap.pr);
80
- yield this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CANCELED);
47
+ async processPastSwap(swap) {
48
+ const { swapContract, signer } = this.getChain(swap.chainIdentifier);
49
+ if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED) {
50
+ //Cancel the swaps where signature is expired
51
+ const isSignatureExpired = await swapContract.isInitAuthorizationExpired(swap.data, swap);
52
+ if (isSignatureExpired) {
53
+ const isCommitted = await swapContract.isCommited(swap.data);
54
+ if (!isCommitted) {
55
+ this.swapLogger.info(swap, "processPastSwap(state=SAVED): authorization expired & swap not committed, cancelling swap, invoice: " + swap.pr);
56
+ await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CANCELED);
81
57
  return;
82
58
  }
59
+ else {
60
+ this.swapLogger.info(swap, "processPastSwap(state=SAVED): swap committed (detected from processPastSwap), invoice: " + swap.pr);
61
+ await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED);
62
+ await this.saveSwapData(swap);
63
+ }
83
64
  }
84
- if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED || swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.PAID) {
85
- //Process swaps in commited & paid state
86
- yield this.processInitialized(swap);
65
+ //Cancel the swaps where lightning invoice is expired
66
+ const decodedPR = await this.lightning.parsePaymentRequest(swap.pr);
67
+ const isInvoiceExpired = decodedPR.expiryEpochMillis < Date.now();
68
+ if (isInvoiceExpired) {
69
+ this.swapLogger.info(swap, "processPastSwap(state=SAVED): invoice expired, cancel uncommited swap, invoice: " + swap.pr);
70
+ await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CANCELED);
71
+ return;
87
72
  }
88
- if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE) {
89
- //Remove expired swaps (as these can already be unilaterally refunded by the client), so we don't need
90
- // to be able to cooperatively refund them
91
- if (swapContract.isExpired(signer.getAddress(), swap.data)) {
92
- this.swapLogger.info(swap, "processPastSwap(state=NON_PAYABLE): swap expired, removing swap data, invoice: " + swap.pr);
93
- yield this.removeSwapData(swap);
94
- }
73
+ }
74
+ if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED || swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.PAID) {
75
+ //Process swaps in commited & paid state
76
+ await this.processInitialized(swap);
77
+ }
78
+ if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE) {
79
+ //Remove expired swaps (as these can already be unilaterally refunded by the client), so we don't need
80
+ // to be able to cooperatively refund them
81
+ if (await swapContract.isExpired(signer.getAddress(), swap.data)) {
82
+ this.swapLogger.info(swap, "processPastSwap(state=NON_PAYABLE): swap expired, removing swap data, invoice: " + swap.pr);
83
+ await this.removeSwapData(swap);
95
84
  }
96
- });
85
+ }
97
86
  }
98
87
  /**
99
88
  * Checks past swaps, deletes ones that are already expired, and tries to process ones that are committed.
100
89
  */
101
- processPastSwaps() {
102
- return __awaiter(this, void 0, void 0, function* () {
103
- this.cleanExpiredExactInAuthorizations();
104
- const queriedData = yield this.storageManager.query([
105
- {
106
- key: "state",
107
- value: [
108
- ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED,
109
- ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED,
110
- ToBtcLnSwapAbs_1.ToBtcLnSwapState.PAID,
111
- ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE
112
- ]
113
- }
114
- ]);
115
- for (let swap of queriedData) {
116
- yield this.processPastSwap(swap);
90
+ async processPastSwaps() {
91
+ this.cleanExpiredExactInAuthorizations();
92
+ const queriedData = await this.storageManager.query([
93
+ {
94
+ key: "state",
95
+ value: [
96
+ ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED,
97
+ ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED,
98
+ ToBtcLnSwapAbs_1.ToBtcLnSwapState.PAID,
99
+ ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE
100
+ ]
117
101
  }
118
- });
102
+ ]);
103
+ for (let { obj: swap } of queriedData) {
104
+ await this.processPastSwap(swap);
105
+ }
119
106
  }
120
107
  /**
121
108
  * Tries to claim the swap funds on the SC side, returns false if the swap is already locked (claim tx is already being sent)
@@ -124,31 +111,29 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
124
111
  * @private
125
112
  * @returns Whether the transaction was successfully sent
126
113
  */
127
- tryClaimSwap(swap) {
128
- return __awaiter(this, void 0, void 0, function* () {
129
- if (swap.secret == null)
130
- throw new Error("Invalid swap state, needs payment pre-image!");
131
- const { swapContract, signer } = this.getChain(swap.chainIdentifier);
132
- //Set flag that we are sending the transaction already, so we don't end up with race condition
133
- const unlock = swap.lock(swapContract.claimWithSecretTimeout);
134
- if (unlock == null)
135
- return false;
136
- try {
137
- this.swapLogger.debug(swap, "tryClaimSwap(): initiate claim of swap, secret: " + swap.secret);
138
- const success = yield swapContract.claimWithSecret(signer, swap.data, swap.secret, false, false, {
139
- waitForConfirmation: true
140
- });
141
- this.swapLogger.info(swap, "tryClaimSwap(): swap claimed successfully, secret: " + swap.secret + " invoice: " + swap.pr);
142
- if (swap.metadata != null)
143
- swap.metadata.times.txClaimed = Date.now();
144
- unlock();
145
- return true;
146
- }
147
- catch (e) {
148
- this.swapLogger.error(swap, "tryClaimSwap(): error occurred claiming swap, secret: " + swap.secret + " invoice: " + swap.pr, e);
149
- return false;
150
- }
151
- });
114
+ async tryClaimSwap(swap) {
115
+ if (swap.secret == null)
116
+ throw new Error("Invalid swap state, needs payment pre-image!");
117
+ const { swapContract, signer } = this.getChain(swap.chainIdentifier);
118
+ //Set flag that we are sending the transaction already, so we don't end up with race condition
119
+ const unlock = swap.lock(swapContract.claimWithSecretTimeout);
120
+ if (unlock == null)
121
+ return false;
122
+ try {
123
+ this.swapLogger.debug(swap, "tryClaimSwap(): initiate claim of swap, secret: " + swap.secret);
124
+ const success = await swapContract.claimWithSecret(signer, swap.data, swap.secret, false, false, {
125
+ waitForConfirmation: true
126
+ });
127
+ this.swapLogger.info(swap, "tryClaimSwap(): swap claimed successfully, secret: " + swap.secret + " invoice: " + swap.pr);
128
+ if (swap.metadata != null)
129
+ swap.metadata.times.txClaimed = Date.now();
130
+ unlock();
131
+ return true;
132
+ }
133
+ catch (e) {
134
+ this.swapLogger.error(swap, "tryClaimSwap(): error occurred claiming swap, secret: " + swap.secret + " invoice: " + swap.pr, e);
135
+ return false;
136
+ }
152
137
  }
153
138
  /**
154
139
  * Process the result of attempted lightning network payment
@@ -156,49 +141,47 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
156
141
  * @param swap
157
142
  * @param lnPaymentStatus
158
143
  */
159
- processPaymentResult(swap, lnPaymentStatus) {
160
- return __awaiter(this, void 0, void 0, function* () {
161
- switch (lnPaymentStatus.status) {
162
- case "pending":
163
- return;
164
- case "failed":
165
- this.swapLogger.info(swap, "processPaymentResult(): invoice payment failed, cancelling swap, invoice: " + swap.pr);
166
- yield swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE);
167
- yield this.storageManager.saveData(swap.data.getHash(), swap.data.getSequence(), swap);
168
- return;
169
- case "confirmed":
170
- const { swapContract, signer } = this.getChain(swap.chainIdentifier);
171
- swap.secret = lnPaymentStatus.secret;
172
- swap.setRealNetworkFee(lnPaymentStatus.feeMtokens.div(new BN(1000)));
173
- this.swapLogger.info(swap, "processPaymentResult(): invoice paid, secret: " + swap.secret + " realRoutingFee: " + swap.realNetworkFee.toString(10) + " invoice: " + swap.pr);
174
- yield swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.PAID);
175
- yield this.storageManager.saveData(swap.data.getHash(), swap.data.getSequence(), swap);
176
- //Check if escrow state exists
177
- const isCommited = yield swapContract.isCommited(swap.data);
178
- if (!isCommited) {
179
- const status = yield swapContract.getCommitStatus(signer.getAddress(), swap.data);
180
- if (status === base_1.SwapCommitStatus.PAID) {
181
- //This is alright, we got the money
182
- yield this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CLAIMED);
183
- return;
184
- }
185
- else if (status === base_1.SwapCommitStatus.EXPIRED) {
186
- //This means the user was able to refund before we were able to claim, no good
187
- yield this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.REFUNDED);
188
- }
189
- this.swapLogger.warn(swap, "processPaymentResult(): tried to claim but escrow doesn't exist anymore," +
190
- " status: " + status +
191
- " invoice: " + swap.pr);
144
+ async processPaymentResult(swap, lnPaymentStatus) {
145
+ switch (lnPaymentStatus.status) {
146
+ case "pending":
147
+ return;
148
+ case "failed":
149
+ this.swapLogger.info(swap, "processPaymentResult(): invoice payment failed, cancelling swap, invoice: " + swap.pr);
150
+ await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE);
151
+ await this.saveSwapData(swap);
152
+ return;
153
+ case "confirmed":
154
+ const { swapContract, signer } = this.getChain(swap.chainIdentifier);
155
+ swap.secret = lnPaymentStatus.secret;
156
+ swap.setRealNetworkFee(lnPaymentStatus.feeMtokens / 1000n);
157
+ this.swapLogger.info(swap, "processPaymentResult(): invoice paid, secret: " + swap.secret + " realRoutingFee: " + swap.realNetworkFee.toString(10) + " invoice: " + swap.pr);
158
+ await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.PAID);
159
+ await this.saveSwapData(swap);
160
+ //Check if escrow state exists
161
+ const isCommited = await swapContract.isCommited(swap.data);
162
+ if (!isCommited) {
163
+ const status = await swapContract.getCommitStatus(signer.getAddress(), swap.data);
164
+ if (status === base_1.SwapCommitStatus.PAID) {
165
+ //This is alright, we got the money
166
+ await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CLAIMED);
192
167
  return;
193
168
  }
194
- const success = yield this.tryClaimSwap(swap);
195
- if (success)
196
- this.swapLogger.info(swap, "processPaymentResult(): swap claimed successfully, invoice: " + swap.pr);
169
+ else if (status === base_1.SwapCommitStatus.EXPIRED) {
170
+ //This means the user was able to refund before we were able to claim, no good
171
+ await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.REFUNDED);
172
+ }
173
+ this.swapLogger.warn(swap, "processPaymentResult(): tried to claim but escrow doesn't exist anymore," +
174
+ " status: " + status +
175
+ " invoice: " + swap.pr);
197
176
  return;
198
- default:
199
- throw new Error("Invalid lnPaymentStatus");
200
- }
201
- });
177
+ }
178
+ const success = await this.tryClaimSwap(swap);
179
+ if (success)
180
+ this.swapLogger.info(swap, "processPaymentResult(): swap claimed successfully, invoice: " + swap.pr);
181
+ return;
182
+ default:
183
+ throw new Error("Invalid lnPaymentStatus");
184
+ }
202
185
  }
203
186
  /**
204
187
  * Subscribe to a pending lightning network payment attempt
@@ -206,7 +189,7 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
206
189
  * @param invoiceData
207
190
  */
208
191
  subscribeToPayment(invoiceData) {
209
- const paymentHash = invoiceData.data.getHash();
192
+ const paymentHash = invoiceData.lnPaymentHash;
210
193
  if (this.activeSubscriptions.has(paymentHash))
211
194
  return false;
212
195
  this.lightning.waitForPayment(paymentHash).then(result => {
@@ -218,145 +201,116 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
218
201
  this.activeSubscriptions.add(paymentHash);
219
202
  return true;
220
203
  }
221
- sendLightningPayment(swap) {
222
- return __awaiter(this, void 0, void 0, function* () {
223
- const decodedPR = yield this.lightning.parsePaymentRequest(swap.pr);
224
- const expiryTimestamp = swap.data.getExpiry();
225
- const currentTimestamp = new BN(Math.floor(Date.now() / 1000));
226
- //Run checks
227
- const hasEnoughTimeToPay = expiryTimestamp.sub(currentTimestamp).gte(this.config.minTsSendCltv);
228
- if (!hasEnoughTimeToPay)
229
- throw {
230
- code: 90005,
231
- msg: "Not enough time to reliably pay the invoice"
232
- };
233
- const isInvoiceExpired = decodedPR.expiryEpochMillis < Date.now();
234
- if (isInvoiceExpired)
235
- throw {
236
- code: 90006,
237
- msg: "Invoice already expired"
238
- };
239
- //Compute max cltv delta
240
- const maxFee = swap.quotedNetworkFee;
241
- const maxUsableCLTVdelta = expiryTimestamp.sub(currentTimestamp).sub(this.config.gracePeriod).div(this.config.bitcoinBlocktime.mul(this.config.safetyFactor));
242
- //Initiate payment
243
- this.swapLogger.info(swap, "sendLightningPayment(): paying lightning network invoice," +
244
- " cltvDelta: " + maxUsableCLTVdelta.toString(10) +
245
- " maxFee: " + maxFee.toString(10) +
246
- " invoice: " + swap.pr);
247
- const blockHeight = yield this.lightning.getBlockheight();
248
- try {
249
- yield this.lightning.pay({
250
- request: swap.pr,
251
- maxFeeMtokens: maxFee.mul(new BN(1000)),
252
- maxTimeoutHeight: blockHeight + maxUsableCLTVdelta.toNumber()
253
- });
254
- }
255
- catch (e) {
256
- throw {
257
- code: 90007,
258
- msg: "Failed to initiate invoice payment",
259
- data: {
260
- error: JSON.stringify(e)
261
- }
262
- };
263
- }
264
- if (swap.metadata != null)
265
- swap.metadata.times.payComplete = Date.now();
266
- });
204
+ async sendLightningPayment(swap) {
205
+ const decodedPR = await this.lightning.parsePaymentRequest(swap.pr);
206
+ const expiryTimestamp = swap.data.getExpiry();
207
+ const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
208
+ //Run checks
209
+ const hasEnoughTimeToPay = (expiryTimestamp - currentTimestamp) >= this.config.minTsSendCltv;
210
+ if (!hasEnoughTimeToPay)
211
+ throw {
212
+ code: 90005,
213
+ msg: "Not enough time to reliably pay the invoice"
214
+ };
215
+ const isInvoiceExpired = decodedPR.expiryEpochMillis < Date.now();
216
+ if (isInvoiceExpired)
217
+ throw {
218
+ code: 90006,
219
+ msg: "Invoice already expired"
220
+ };
221
+ //Compute max cltv delta
222
+ const maxFee = swap.quotedNetworkFee;
223
+ const maxUsableCLTVdelta = (expiryTimestamp - currentTimestamp - this.config.gracePeriod)
224
+ / (this.config.bitcoinBlocktime * this.config.safetyFactor);
225
+ //Initiate payment
226
+ this.swapLogger.info(swap, "sendLightningPayment(): paying lightning network invoice," +
227
+ " cltvDelta: " + maxUsableCLTVdelta.toString(10) +
228
+ " maxFee: " + maxFee.toString(10) +
229
+ " invoice: " + swap.pr);
230
+ const blockHeight = await this.lightning.getBlockheight();
231
+ try {
232
+ await this.lightning.pay({
233
+ request: swap.pr,
234
+ maxFeeMtokens: maxFee * 1000n,
235
+ maxTimeoutHeight: blockHeight + Number(maxUsableCLTVdelta)
236
+ });
237
+ }
238
+ catch (e) {
239
+ throw {
240
+ code: 90007,
241
+ msg: "Failed to initiate invoice payment",
242
+ data: {
243
+ error: JSON.stringify(e)
244
+ }
245
+ };
246
+ }
247
+ if (swap.metadata != null)
248
+ swap.metadata.times.payComplete = Date.now();
267
249
  }
268
250
  /**
269
251
  * Begins a lightning network payment attempt, if not attempted already
270
252
  *
271
253
  * @param swap
272
254
  */
273
- processInitialized(swap) {
274
- return __awaiter(this, void 0, void 0, function* () {
275
- //Check if payment was already made
276
- if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED) {
277
- let lnPaymentStatus = yield this.lightning.getPayment(swap.getHash());
278
- if (lnPaymentStatus != null) {
279
- if (lnPaymentStatus.status === "pending") {
280
- //Payment still ongoing, process the result
281
- this.subscribeToPayment(swap);
282
- return;
283
- }
284
- else {
285
- //Payment has already concluded, process the result
286
- yield this.processPaymentResult(swap, lnPaymentStatus);
287
- return;
288
- }
255
+ async processInitialized(swap) {
256
+ //Check if payment was already made
257
+ if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED) {
258
+ if (swap.metadata != null)
259
+ swap.metadata.times.payPaymentChecked = Date.now();
260
+ let lnPaymentStatus = await this.lightning.getPayment(swap.lnPaymentHash);
261
+ if (lnPaymentStatus != null) {
262
+ if (lnPaymentStatus.status === "pending") {
263
+ //Payment still ongoing, process the result
264
+ this.subscribeToPayment(swap);
265
+ return;
289
266
  }
290
267
  else {
291
- //Payment not founds, try to process again
292
- yield swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED);
268
+ //Payment has already concluded, process the result
269
+ await this.processPaymentResult(swap, lnPaymentStatus);
270
+ return;
293
271
  }
294
272
  }
295
- if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED) {
296
- yield swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED);
297
- yield this.storageManager.saveData(swap.data.getHash(), swap.data.getSequence(), swap);
298
- try {
299
- yield this.sendLightningPayment(swap);
300
- }
301
- catch (e) {
302
- this.swapLogger.error(swap, "processInitialized(): lightning payment error", e);
303
- if ((0, Utils_1.isDefinedRuntimeError)(e)) {
304
- if (swap.metadata != null)
305
- swap.metadata.payError = e;
306
- yield swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE);
307
- yield this.storageManager.saveData(swap.data.getHash(), swap.data.getSequence(), swap);
308
- return;
309
- }
310
- else
311
- throw e;
273
+ else {
274
+ //Payment not founds, try to process again
275
+ await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED);
276
+ }
277
+ }
278
+ if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED) {
279
+ await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED);
280
+ await this.saveSwapData(swap);
281
+ try {
282
+ await this.sendLightningPayment(swap);
283
+ }
284
+ catch (e) {
285
+ this.swapLogger.error(swap, "processInitialized(): lightning payment error", e);
286
+ if ((0, Utils_1.isDefinedRuntimeError)(e)) {
287
+ if (swap.metadata != null)
288
+ swap.metadata.payError = e;
289
+ await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE);
290
+ await this.saveSwapData(swap);
291
+ return;
312
292
  }
313
- this.subscribeToPayment(swap);
314
- return;
293
+ else
294
+ throw e;
315
295
  }
316
- });
296
+ this.subscribeToPayment(swap);
297
+ return;
298
+ }
317
299
  }
318
- processInitializeEvent(chainIdentifier, event) {
319
- var _a;
320
- return __awaiter(this, void 0, void 0, function* () {
321
- if (event.swapType !== base_1.ChainSwapType.HTLC)
322
- return;
323
- const paymentHash = event.paymentHash;
324
- const swap = yield this.storageManager.getData(paymentHash, event.sequence);
325
- if (swap == null || swap.chainIdentifier !== chainIdentifier)
326
- return;
327
- swap.txIds.init = (_a = event.meta) === null || _a === void 0 ? void 0 : _a.txId;
328
- if (swap.metadata != null)
329
- swap.metadata.times.txReceived = Date.now();
330
- this.swapLogger.info(swap, "SC: InitializeEvent: swap initialized by the client, invoice: " + swap.pr);
331
- //Only process swaps in SAVED state
332
- if (swap.state !== ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED)
333
- return;
334
- yield this.processInitialized(swap);
335
- });
300
+ async processInitializeEvent(chainIdentifier, swap, event) {
301
+ this.swapLogger.info(swap, "SC: InitializeEvent: swap initialized by the client, invoice: " + swap.pr);
302
+ //Only process swaps in SAVED state
303
+ if (swap.state !== ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED)
304
+ return;
305
+ await this.processInitialized(swap);
336
306
  }
337
- processClaimEvent(chainIdentifier, event) {
338
- var _a;
339
- return __awaiter(this, void 0, void 0, function* () {
340
- const paymentHash = event.paymentHash;
341
- const swap = yield this.storageManager.getData(paymentHash, event.sequence);
342
- if (swap == null || swap.chainIdentifier !== chainIdentifier)
343
- return;
344
- swap.txIds.claim = (_a = event.meta) === null || _a === void 0 ? void 0 : _a.txId;
345
- this.swapLogger.info(swap, "SC: ClaimEvent: swap claimed to us, secret: " + event.secret + " invoice: " + swap.pr);
346
- yield this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CLAIMED);
347
- });
307
+ async processClaimEvent(chainIdentifier, swap, event) {
308
+ this.swapLogger.info(swap, "SC: ClaimEvent: swap claimed to us, secret: " + event.result + " invoice: " + swap.pr);
309
+ await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CLAIMED);
348
310
  }
349
- processRefundEvent(chainIdentifier, event) {
350
- var _a;
351
- return __awaiter(this, void 0, void 0, function* () {
352
- const paymentHash = event.paymentHash;
353
- const swap = yield this.storageManager.getData(paymentHash, event.sequence);
354
- if (swap == null || swap.chainIdentifier !== chainIdentifier)
355
- return;
356
- swap.txIds.refund = (_a = event.meta) === null || _a === void 0 ? void 0 : _a.txId;
357
- this.swapLogger.info(swap, "SC: RefundEvent: swap refunded back to the client, invoice: " + swap.pr);
358
- yield this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.REFUNDED);
359
- });
311
+ async processRefundEvent(chainIdentifier, swap, event) {
312
+ this.swapLogger.info(swap, "SC: RefundEvent: swap refunded back to the client, invoice: " + swap.pr);
313
+ await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.REFUNDED);
360
314
  }
361
315
  /**
362
316
  * Checks if the amount was supplied in the exactIn request
@@ -382,7 +336,7 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
382
336
  * @throws {DefinedRuntimeError} will throw an error if the maxFee is zero or negative
383
337
  */
384
338
  checkMaxFee(maxFee) {
385
- if (maxFee.isNeg() || maxFee.isZero()) {
339
+ if (maxFee <= 0) {
386
340
  throw {
387
341
  code: 20030,
388
342
  msg: "Invalid request body (maxFee too low)!"
@@ -392,44 +346,43 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
392
346
  /**
393
347
  * Checks and parses a payment request (bolt11 invoice), additionally also checks expiration time of the invoice
394
348
  *
349
+ * @param chainIdentifier
395
350
  * @param pr
396
351
  * @throws {DefinedRuntimeError} will throw an error if the pr is invalid, without amount or expired
397
352
  */
398
- checkPaymentRequest(pr) {
399
- return __awaiter(this, void 0, void 0, function* () {
400
- let parsedPR;
401
- try {
402
- parsedPR = yield this.lightning.parsePaymentRequest(pr);
403
- }
404
- catch (e) {
353
+ async checkPaymentRequest(chainIdentifier, pr) {
354
+ let parsedPR;
355
+ try {
356
+ parsedPR = await this.lightning.parsePaymentRequest(pr);
357
+ }
358
+ catch (e) {
359
+ throw {
360
+ code: 20021,
361
+ msg: "Invalid request body (pr - cannot be parsed)"
362
+ };
363
+ }
364
+ if (parsedPR.mtokens == null)
365
+ throw {
366
+ code: 20022,
367
+ msg: "Invalid request body (pr - needs to have amount)"
368
+ };
369
+ let halfConfidence = false;
370
+ if (parsedPR.expiryEpochMillis < Date.now() + ((this.getInitAuthorizationTimeout(chainIdentifier) + (2 * 60)) * 1000)) {
371
+ if (!this.config.allowShortExpiry) {
405
372
  throw {
406
- code: 20021,
407
- msg: "Invalid request body (pr - cannot be parsed)"
373
+ code: 20020,
374
+ msg: "Invalid request body (pr - expired)"
408
375
  };
409
376
  }
410
- if (parsedPR.mtokens == null)
377
+ else if (parsedPR.expiryEpochMillis < Date.now()) {
411
378
  throw {
412
- code: 20022,
413
- msg: "Invalid request body (pr - needs to have amount)"
379
+ code: 20020,
380
+ msg: "Invalid request body (pr - expired)"
414
381
  };
415
- let halfConfidence = false;
416
- if (parsedPR.expiryEpochMillis < Date.now() + ((this.config.authorizationTimeout + (2 * 60)) * 1000)) {
417
- if (!this.config.allowShortExpiry) {
418
- throw {
419
- code: 20020,
420
- msg: "Invalid request body (pr - expired)"
421
- };
422
- }
423
- else if (parsedPR.expiryEpochMillis < Date.now()) {
424
- throw {
425
- code: 20020,
426
- msg: "Invalid request body (pr - expired)"
427
- };
428
- }
429
- halfConfidence = true;
430
382
  }
431
- return { parsedPR, halfConfidence };
432
- });
383
+ halfConfidence = true;
384
+ }
385
+ return { parsedPR, halfConfidence };
433
386
  }
434
387
  /**
435
388
  * Checks if the request specified too short of an expiry
@@ -439,7 +392,7 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
439
392
  * @throws {DefinedRuntimeError} will throw an error if the expiry time is too short
440
393
  */
441
394
  checkExpiry(expiryTimestamp, currentTimestamp) {
442
- const expiresTooSoon = expiryTimestamp.sub(currentTimestamp).lt(this.config.minTsSendCltv);
395
+ const expiresTooSoon = (expiryTimestamp - currentTimestamp) < this.config.minTsSendCltv;
443
396
  if (expiresTooSoon) {
444
397
  throw {
445
398
  code: 20001,
@@ -454,16 +407,14 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
454
407
  * @param abortSignal
455
408
  * @throws {DefinedRuntimeError} will throw an error if payment already exists
456
409
  */
457
- checkPriorPayment(paymentHash, abortSignal) {
458
- return __awaiter(this, void 0, void 0, function* () {
459
- const payment = yield this.lightning.getPayment(paymentHash);
460
- if (payment != null)
461
- throw {
462
- code: 20010,
463
- msg: "Already processed"
464
- };
465
- abortSignal.throwIfAborted();
466
- });
410
+ async checkPriorPayment(paymentHash, abortSignal) {
411
+ const payment = await this.lightning.getPayment(paymentHash);
412
+ if (payment != null)
413
+ throw {
414
+ code: 20010,
415
+ msg: "Already processed"
416
+ };
417
+ abortSignal.throwIfAborted();
467
418
  }
468
419
  /**
469
420
  * Checks if the underlying LND backend has enough liquidity in channels to honor the swap
@@ -473,23 +424,21 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
473
424
  * @param useCached Whether to use cached liquidity values
474
425
  * @throws {DefinedRuntimeError} will throw an error if there isn't enough liquidity
475
426
  */
476
- checkLiquidity(amount, abortSignal, useCached = false) {
477
- return __awaiter(this, void 0, void 0, function* () {
478
- if (!useCached || this.lightningLiquidityCache == null || this.lightningLiquidityCache.timestamp < Date.now() - this.LIGHTNING_LIQUIDITY_CACHE_TIMEOUT) {
479
- const channelBalances = yield this.lightning.getLightningBalance();
480
- this.lightningLiquidityCache = {
481
- liquidity: channelBalances.localBalance,
482
- timestamp: Date.now()
483
- };
484
- }
485
- if (amount.gt(this.lightningLiquidityCache.liquidity)) {
486
- throw {
487
- code: 20002,
488
- msg: "Not enough liquidity"
489
- };
490
- }
491
- abortSignal.throwIfAborted();
492
- });
427
+ async checkLiquidity(amount, abortSignal, useCached = false) {
428
+ if (!useCached || this.lightningLiquidityCache == null || this.lightningLiquidityCache.timestamp < Date.now() - this.LIGHTNING_LIQUIDITY_CACHE_TIMEOUT) {
429
+ const channelBalances = await this.lightning.getLightningBalance();
430
+ this.lightningLiquidityCache = {
431
+ liquidity: channelBalances.localBalance,
432
+ timestamp: Date.now()
433
+ };
434
+ }
435
+ if (amount > this.lightningLiquidityCache.liquidity) {
436
+ throw {
437
+ code: 20002,
438
+ msg: "Not enough liquidity"
439
+ };
440
+ }
441
+ abortSignal.throwIfAborted();
493
442
  }
494
443
  /**
495
444
  * Estimates the routing fee & confidence by either probing or routing (if probing fails), the fee is also adjusted
@@ -504,67 +453,65 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
504
453
  * @param abortSignal
505
454
  * @throws {DefinedRuntimeError} will throw an error if the destination is unreachable
506
455
  */
507
- checkAndGetNetworkFee(amountBD, maxFee, expiryTimestamp, currentTimestamp, pr, metadata, abortSignal) {
508
- return __awaiter(this, void 0, void 0, function* () {
509
- const maxUsableCLTV = expiryTimestamp.sub(currentTimestamp).sub(this.config.gracePeriod).div(this.config.bitcoinBlocktime.mul(this.config.safetyFactor));
510
- const blockHeight = yield this.lightning.getBlockheight();
511
- abortSignal.throwIfAborted();
512
- metadata.times.blockheightFetched = Date.now();
513
- const maxTimeoutBlockheight = new BN(blockHeight).add(maxUsableCLTV);
514
- const req = {
515
- request: pr,
516
- amountMtokens: amountBD.mul(new BN(1000)),
517
- maxFeeMtokens: maxFee.mul(new BN(1000)),
518
- maxTimeoutHeight: maxTimeoutBlockheight.toNumber()
519
- };
520
- let probeOrRouteResp = yield this.lightning.probe(req);
521
- metadata.times.probeResult = Date.now();
522
- metadata.probeResponse = Object.assign({}, probeOrRouteResp);
456
+ async checkAndGetNetworkFee(amountBD, maxFee, expiryTimestamp, currentTimestamp, pr, metadata, abortSignal) {
457
+ const maxUsableCLTV = (expiryTimestamp - currentTimestamp - this.config.gracePeriod) / (this.config.bitcoinBlocktime * this.config.safetyFactor);
458
+ const blockHeight = await this.lightning.getBlockheight();
459
+ abortSignal.throwIfAborted();
460
+ metadata.times.blockheightFetched = Date.now();
461
+ const maxTimeoutBlockheight = BigInt(blockHeight) + maxUsableCLTV;
462
+ const req = {
463
+ request: pr,
464
+ amountMtokens: amountBD * 1000n,
465
+ maxFeeMtokens: maxFee * 1000n,
466
+ maxTimeoutHeight: Number(maxTimeoutBlockheight)
467
+ };
468
+ let probeOrRouteResp = await this.lightning.probe(req);
469
+ metadata.times.probeResult = Date.now();
470
+ metadata.probeResponse = { ...probeOrRouteResp };
471
+ abortSignal.throwIfAborted();
472
+ if (probeOrRouteResp == null) {
473
+ if (!this.config.allowProbeFailedSwaps)
474
+ throw {
475
+ code: 20002,
476
+ msg: "Cannot route the payment!"
477
+ };
478
+ const routeResp = await this.lightning.route(req);
479
+ metadata.times.routingResult = Date.now();
480
+ metadata.routeResponse = { ...routeResp };
523
481
  abortSignal.throwIfAborted();
524
- if (probeOrRouteResp == null) {
525
- if (!this.config.allowProbeFailedSwaps)
526
- throw {
527
- code: 20002,
528
- msg: "Cannot route the payment!"
529
- };
530
- const routeResp = yield this.lightning.route(req);
531
- metadata.times.routingResult = Date.now();
532
- metadata.routeResponse = Object.assign({}, routeResp);
533
- abortSignal.throwIfAborted();
534
- if (routeResp == null)
535
- throw {
536
- code: 20002,
537
- msg: "Cannot route the payment!"
538
- };
539
- this.logger.info("checkAndGetNetworkFee(): routing result," +
540
- " destination: " + routeResp.destination +
541
- " confidence: " + routeResp.confidence +
542
- " fee mtokens: " + routeResp.feeMtokens.toString(10));
543
- probeOrRouteResp = routeResp;
544
- }
545
- else {
546
- this.logger.info("checkAndGetNetworkFee(): route probed," +
547
- " destination: " + probeOrRouteResp.destination +
548
- " confidence: " + probeOrRouteResp.confidence +
549
- " fee mtokens: " + probeOrRouteResp.feeMtokens.toString(10));
550
- }
551
- const safeFeeTokens = probeOrRouteResp.feeMtokens.add(new BN(999)).div(new BN(1000));
552
- let actualRoutingFee = safeFeeTokens.mul(this.config.routingFeeMultiplier);
553
- const minRoutingFee = amountBD.mul(this.config.minLnRoutingFeePPM).div(new BN(1000000)).add(this.config.minLnBaseFee);
554
- if (actualRoutingFee.lt(minRoutingFee)) {
555
- actualRoutingFee = minRoutingFee;
556
- if (actualRoutingFee.gt(maxFee)) {
557
- probeOrRouteResp.confidence = 0;
558
- }
559
- }
560
- if (actualRoutingFee.gt(maxFee)) {
561
- actualRoutingFee = maxFee;
482
+ if (routeResp == null)
483
+ throw {
484
+ code: 20002,
485
+ msg: "Cannot route the payment!"
486
+ };
487
+ this.logger.info("checkAndGetNetworkFee(): routing result," +
488
+ " destination: " + routeResp.destination +
489
+ " confidence: " + routeResp.confidence +
490
+ " fee mtokens: " + routeResp.feeMtokens.toString(10));
491
+ probeOrRouteResp = routeResp;
492
+ }
493
+ else {
494
+ this.logger.info("checkAndGetNetworkFee(): route probed," +
495
+ " destination: " + probeOrRouteResp.destination +
496
+ " confidence: " + probeOrRouteResp.confidence +
497
+ " fee mtokens: " + probeOrRouteResp.feeMtokens.toString(10));
498
+ }
499
+ const safeFeeTokens = (probeOrRouteResp.feeMtokens + 999n) / 1000n;
500
+ let actualRoutingFee = safeFeeTokens * this.config.routingFeeMultiplier;
501
+ const minRoutingFee = (amountBD * this.config.minLnRoutingFeePPM / 1000000n) + this.config.minLnBaseFee;
502
+ if (actualRoutingFee < minRoutingFee) {
503
+ actualRoutingFee = minRoutingFee;
504
+ if (actualRoutingFee > maxFee) {
505
+ probeOrRouteResp.confidence = 0;
562
506
  }
563
- return {
564
- networkFee: actualRoutingFee,
565
- confidence: probeOrRouteResp.confidence
566
- };
567
- });
507
+ }
508
+ if (actualRoutingFee > maxFee) {
509
+ actualRoutingFee = maxFee;
510
+ }
511
+ return {
512
+ networkFee: actualRoutingFee,
513
+ confidence: probeOrRouteResp.confidence
514
+ };
568
515
  }
569
516
  /**
570
517
  * Checks and consumes (deletes & returns) exactIn authorizaton with a specific reqId
@@ -597,34 +544,32 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
597
544
  * @param parsedAuth
598
545
  * @throws {DefinedRuntimeError} will throw an error if the details don't match
599
546
  */
600
- checkPaymentRequestMatchesInitial(pr, parsedAuth) {
601
- return __awaiter(this, void 0, void 0, function* () {
602
- const parsedRequest = yield this.lightning.parsePaymentRequest(pr);
603
- if (parsedRequest.destination !== parsedAuth.initialInvoice.destination ||
604
- parsedRequest.cltvDelta !== parsedAuth.initialInvoice.cltvDelta ||
605
- !parsedRequest.mtokens.eq(parsedAuth.amount.mul(new BN(1000)))) {
606
- throw {
607
- code: 20102,
608
- msg: "Provided PR doesn't match initial!"
609
- };
610
- }
611
- if (!(0, ILightningWallet_1.routesMatch)(parsedRequest.routes, parsedAuth.initialInvoice.routes)) {
612
- throw {
613
- code: 20102,
614
- msg: "Provided PR doesn't match initial (routes)!"
615
- };
616
- }
617
- });
547
+ async checkPaymentRequestMatchesInitial(pr, parsedAuth) {
548
+ const parsedRequest = await this.lightning.parsePaymentRequest(pr);
549
+ if (parsedRequest.destination !== parsedAuth.initialInvoice.destination ||
550
+ parsedRequest.cltvDelta !== parsedAuth.initialInvoice.cltvDelta ||
551
+ parsedRequest.mtokens !== parsedAuth.amount * 1000n) {
552
+ throw {
553
+ code: 20102,
554
+ msg: "Provided PR doesn't match initial!"
555
+ };
556
+ }
557
+ if (!(0, ILightningWallet_1.routesMatch)(parsedRequest.routes, parsedAuth.initialInvoice.routes)) {
558
+ throw {
559
+ code: 20102,
560
+ msg: "Provided PR doesn't match initial (routes)!"
561
+ };
562
+ }
618
563
  }
619
564
  startRestServer(restServer) {
620
565
  restServer.use(this.path + "/payInvoiceExactIn", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
621
- restServer.post(this.path + "/payInvoiceExactIn", (0, Utils_1.expressHandlerWrapper)((req, res) => __awaiter(this, void 0, void 0, function* () {
566
+ restServer.post(this.path + "/payInvoiceExactIn", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
622
567
  /**
623
568
  * pr: string bolt11 lightning invoice
624
569
  * reqId: string Identifier of the swap
625
570
  * feeRate: string Fee rate to use for the init tx
626
571
  */
627
- const parsedBody = yield req.paramReader.getParams({
572
+ const parsedBody = await req.paramReader.getParams({
628
573
  pr: SchemaVerifier_1.FieldTypeEnum.String,
629
574
  reqId: SchemaVerifier_1.FieldTypeEnum.String,
630
575
  feeRate: SchemaVerifier_1.FieldTypeEnum.String
@@ -639,33 +584,34 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
639
584
  const abortSignal = responseStream.getAbortSignal();
640
585
  //Check request params
641
586
  const parsedAuth = this.checkExactInAuthorization(parsedBody.reqId);
642
- const { parsedPR, halfConfidence } = yield this.checkPaymentRequest(parsedBody.pr);
643
- yield this.checkPaymentRequestMatchesInitial(parsedBody.pr, parsedAuth);
587
+ const { parsedPR, halfConfidence } = await this.checkPaymentRequest(parsedAuth.chainIdentifier, parsedBody.pr);
588
+ await this.checkPaymentRequestMatchesInitial(parsedBody.pr, parsedAuth);
644
589
  const metadata = parsedAuth.metadata;
645
- const sequence = new BN((0, crypto_1.randomBytes)(8));
590
+ const sequence = base_1.BigIntBufferUtils.fromBuffer((0, crypto_1.randomBytes)(8));
646
591
  const { swapContract, signer } = this.getChain(parsedAuth.chainIdentifier);
592
+ const claimHash = swapContract.getHashForHtlc(Buffer.from(parsedPR.id, "hex"));
647
593
  //Create swap data
648
- const payObject = yield swapContract.createSwapData(base_1.ChainSwapType.HTLC, parsedAuth.offerer, signer.getAddress(), parsedAuth.token, parsedAuth.total, parsedPR.id, sequence, parsedAuth.swapExpiry, new BN(0), 0, true, false, new BN(0), new BN(0));
594
+ const payObject = await swapContract.createSwapData(base_1.ChainSwapType.HTLC, parsedAuth.offerer, signer.getAddress(), parsedAuth.token, parsedAuth.total, claimHash.toString("hex"), sequence, parsedAuth.swapExpiry, true, false, 0n, 0n);
649
595
  metadata.times.swapCreated = Date.now();
650
596
  //Sign swap data
651
597
  const prefetchedSignData = parsedAuth.preFetchSignData;
652
- const sigData = yield this.getToBtcSignatureData(parsedAuth.chainIdentifier, payObject, req, abortSignal, prefetchedSignData);
598
+ const sigData = await this.getToBtcSignatureData(parsedAuth.chainIdentifier, payObject, req, abortSignal, prefetchedSignData);
653
599
  metadata.times.swapSigned = Date.now();
654
600
  //Create swap
655
- const createdSwap = new ToBtcLnSwapAbs_1.ToBtcLnSwapAbs(parsedAuth.chainIdentifier, parsedBody.pr, parsedPR.mtokens, parsedAuth.swapFee, parsedAuth.swapFeeInToken, parsedAuth.quotedNetworkFee, parsedAuth.quotedNetworkFeeInToken);
601
+ const createdSwap = new ToBtcLnSwapAbs_1.ToBtcLnSwapAbs(parsedAuth.chainIdentifier, parsedPR.id, parsedBody.pr, parsedPR.mtokens, parsedAuth.swapFee, parsedAuth.swapFeeInToken, parsedAuth.quotedNetworkFee, parsedAuth.quotedNetworkFeeInToken);
656
602
  createdSwap.data = payObject;
657
603
  createdSwap.metadata = metadata;
658
604
  createdSwap.prefix = sigData.prefix;
659
605
  createdSwap.timeout = sigData.timeout;
660
606
  createdSwap.signature = sigData.signature;
661
607
  createdSwap.feeRate = sigData.feeRate;
662
- yield PluginManager_1.PluginManager.swapCreate(createdSwap);
663
- yield this.storageManager.saveData(parsedPR.id, sequence, createdSwap);
608
+ await PluginManager_1.PluginManager.swapCreate(createdSwap);
609
+ await this.storageManager.saveData(parsedPR.id, sequence, createdSwap);
664
610
  this.swapLogger.info(createdSwap, "REST: /payInvoiceExactIn: created exact in swap," +
665
611
  " reqId: " + parsedBody.reqId +
666
612
  " mtokens: " + parsedPR.mtokens.toString(10) +
667
613
  " invoice: " + createdSwap.pr);
668
- yield responseStream.writeParamsAndEnd({
614
+ await responseStream.writeParamsAndEnd({
669
615
  code: 20000,
670
616
  msg: "Success",
671
617
  data: {
@@ -681,12 +627,11 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
681
627
  signature: sigData.signature
682
628
  }
683
629
  });
684
- })));
630
+ }));
685
631
  restServer.use(this.path + "/payInvoice", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
686
- restServer.post(this.path + "/payInvoice", (0, Utils_1.expressHandlerWrapper)((req, res) => __awaiter(this, void 0, void 0, function* () {
687
- var _a;
632
+ restServer.post(this.path + "/payInvoice", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
688
633
  const metadata = { request: {}, times: {} };
689
- const chainIdentifier = (_a = req.query.chain) !== null && _a !== void 0 ? _a : this.chains.default;
634
+ const chainIdentifier = req.query.chain ?? this.chains.default;
690
635
  const { swapContract, signer } = this.getChain(chainIdentifier);
691
636
  metadata.times.requestReceived = Date.now();
692
637
  /**
@@ -702,10 +647,10 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
702
647
  *Sent later:
703
648
  * feeRate: string Fee rate to use for the init signature
704
649
  */
705
- const parsedBody = yield req.paramReader.getParams({
650
+ const parsedBody = await req.paramReader.getParams({
706
651
  pr: SchemaVerifier_1.FieldTypeEnum.String,
707
- maxFee: SchemaVerifier_1.FieldTypeEnum.BN,
708
- expiryTimestamp: SchemaVerifier_1.FieldTypeEnum.BN,
652
+ maxFee: SchemaVerifier_1.FieldTypeEnum.BigInt,
653
+ expiryTimestamp: SchemaVerifier_1.FieldTypeEnum.BigInt,
709
654
  token: (val) => val != null &&
710
655
  typeof (val) === "string" &&
711
656
  this.isTokenSupported(chainIdentifier, val) ? val : null,
@@ -713,7 +658,7 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
713
658
  typeof (val) === "string" &&
714
659
  swapContract.isValidAddress(val) ? val : null,
715
660
  exactIn: SchemaVerifier_1.FieldTypeEnum.BooleanOptional,
716
- amount: SchemaVerifier_1.FieldTypeEnum.BNOptional
661
+ amount: SchemaVerifier_1.FieldTypeEnum.BigIntOptional
717
662
  });
718
663
  if (parsedBody == null) {
719
664
  throw {
@@ -730,36 +675,36 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
730
675
  };
731
676
  const useToken = parsedBody.token;
732
677
  const responseStream = res.responseStream;
733
- const currentTimestamp = new BN(Math.floor(Date.now() / 1000));
678
+ const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
734
679
  //Check request params
735
680
  this.checkAmount(parsedBody.amount, parsedBody.exactIn);
736
681
  this.checkMaxFee(parsedBody.maxFee);
737
682
  this.checkExpiry(parsedBody.expiryTimestamp, currentTimestamp);
738
- yield this.checkVaultInitialized(chainIdentifier, parsedBody.token);
739
- const { parsedPR, halfConfidence } = yield this.checkPaymentRequest(parsedBody.pr);
683
+ await this.checkVaultInitialized(chainIdentifier, parsedBody.token);
684
+ const { parsedPR, halfConfidence } = await this.checkPaymentRequest(chainIdentifier, parsedBody.pr);
740
685
  const requestedAmount = {
741
686
  input: !!parsedBody.exactIn,
742
- amount: !!parsedBody.exactIn ? parsedBody.amount : parsedPR.mtokens.add(new BN(999)).div(new BN(1000))
687
+ amount: !!parsedBody.exactIn ? parsedBody.amount : (parsedPR.mtokens + 999n) / 1000n
743
688
  };
744
- const fees = yield this.preCheckAmounts(request, requestedAmount, useToken);
689
+ const fees = await this.preCheckAmounts(request, requestedAmount, useToken);
745
690
  metadata.times.requestChecked = Date.now();
746
691
  //Create abort controller for parallel pre-fetches
747
692
  const abortController = this.getAbortController(responseStream);
748
693
  //Pre-fetch
749
694
  const { pricePrefetchPromise, signDataPrefetchPromise } = this.getToBtcPrefetches(chainIdentifier, useToken, responseStream, abortController);
750
695
  //Check if prior payment has been made
751
- yield this.checkPriorPayment(parsedPR.id, abortController.signal);
696
+ await this.checkPriorPayment(parsedPR.id, abortController.signal);
752
697
  metadata.times.priorPaymentChecked = Date.now();
753
698
  //Check amounts
754
- const { amountBD, networkFeeData, totalInToken, swapFee, swapFeeInToken, networkFeeInToken } = yield this.checkToBtcAmount(request, requestedAmount, fees, useToken, (amountBD) => __awaiter(this, void 0, void 0, function* () {
699
+ const { amountBD, networkFeeData, totalInToken, swapFee, swapFeeInToken, networkFeeInToken } = await this.checkToBtcAmount(request, requestedAmount, fees, useToken, async (amountBD) => {
755
700
  //Check if we have enough liquidity to process the swap
756
- yield this.checkLiquidity(amountBD, abortController.signal, true);
701
+ await this.checkLiquidity(amountBD, abortController.signal, true);
757
702
  metadata.times.liquidityChecked = Date.now();
758
703
  const maxFee = parsedBody.exactIn ?
759
- yield this.swapPricing.getToBtcSwapAmount(parsedBody.maxFee, useToken, chainIdentifier, null, pricePrefetchPromise) :
704
+ await this.swapPricing.getToBtcSwapAmount(parsedBody.maxFee, useToken, chainIdentifier, null, pricePrefetchPromise) :
760
705
  parsedBody.maxFee;
761
- return yield this.checkAndGetNetworkFee(amountBD, maxFee, parsedBody.expiryTimestamp, currentTimestamp, parsedBody.pr, metadata, abortController.signal);
762
- }), abortController.signal, pricePrefetchPromise);
706
+ return await this.checkAndGetNetworkFee(amountBD, maxFee, parsedBody.expiryTimestamp, currentTimestamp, parsedBody.pr, metadata, abortController.signal);
707
+ }, abortController.signal, pricePrefetchPromise);
763
708
  metadata.times.priceCalculated = Date.now();
764
709
  //For exactIn swap, just save and wait for the actual invoice to be submitted
765
710
  if (parsedBody.exactIn) {
@@ -779,14 +724,14 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
779
724
  token: useToken,
780
725
  swapExpiry: parsedBody.expiryTimestamp,
781
726
  offerer: parsedBody.offerer,
782
- preFetchSignData: signDataPrefetchPromise != null ? yield signDataPrefetchPromise : null,
727
+ preFetchSignData: signDataPrefetchPromise != null ? await signDataPrefetchPromise : null,
783
728
  metadata
784
729
  };
785
730
  this.logger.info("REST: /payInvoice: created exact in swap," +
786
731
  " reqId: " + reqId +
787
732
  " amount: " + amountBD.toString(10) +
788
733
  " destination: " + parsedPR.destination);
789
- yield responseStream.writeParamsAndEnd({
734
+ await responseStream.writeParamsAndEnd({
790
735
  code: 20000,
791
736
  msg: "Success",
792
737
  data: {
@@ -796,28 +741,29 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
796
741
  });
797
742
  return;
798
743
  }
799
- const sequence = new BN((0, crypto_1.randomBytes)(8));
744
+ const sequence = base_1.BigIntBufferUtils.fromBuffer((0, crypto_1.randomBytes)(8));
745
+ const claimHash = swapContract.getHashForHtlc(Buffer.from(parsedPR.id, "hex"));
800
746
  //Create swap data
801
- const payObject = yield swapContract.createSwapData(base_1.ChainSwapType.HTLC, parsedBody.offerer, signer.getAddress(), useToken, totalInToken, parsedPR.id, sequence, parsedBody.expiryTimestamp, new BN(0), 0, true, false, new BN(0), new BN(0));
747
+ const payObject = await swapContract.createSwapData(base_1.ChainSwapType.HTLC, parsedBody.offerer, signer.getAddress(), useToken, totalInToken, claimHash.toString("hex"), sequence, parsedBody.expiryTimestamp, true, false, 0n, 0n);
802
748
  abortController.signal.throwIfAborted();
803
749
  metadata.times.swapCreated = Date.now();
804
750
  //Sign swap data
805
- const sigData = yield this.getToBtcSignatureData(chainIdentifier, payObject, req, abortController.signal, signDataPrefetchPromise);
751
+ const sigData = await this.getToBtcSignatureData(chainIdentifier, payObject, req, abortController.signal, signDataPrefetchPromise);
806
752
  metadata.times.swapSigned = Date.now();
807
753
  //Create swap
808
- const createdSwap = new ToBtcLnSwapAbs_1.ToBtcLnSwapAbs(chainIdentifier, parsedBody.pr, parsedPR.mtokens, swapFee, swapFeeInToken, networkFeeData.networkFee, networkFeeInToken);
754
+ const createdSwap = new ToBtcLnSwapAbs_1.ToBtcLnSwapAbs(chainIdentifier, parsedPR.id, parsedBody.pr, parsedPR.mtokens, swapFee, swapFeeInToken, networkFeeData.networkFee, networkFeeInToken);
809
755
  createdSwap.data = payObject;
810
756
  createdSwap.metadata = metadata;
811
757
  createdSwap.prefix = sigData.prefix;
812
758
  createdSwap.timeout = sigData.timeout;
813
759
  createdSwap.signature = sigData.signature;
814
760
  createdSwap.feeRate = sigData.feeRate;
815
- yield PluginManager_1.PluginManager.swapCreate(createdSwap);
816
- yield this.storageManager.saveData(parsedPR.id, sequence, createdSwap);
761
+ await PluginManager_1.PluginManager.swapCreate(createdSwap);
762
+ await this.saveSwapData(createdSwap);
817
763
  this.swapLogger.info(createdSwap, "REST: /payInvoice: created swap," +
818
764
  " amount: " + amountBD.toString(10) +
819
765
  " invoice: " + createdSwap.pr);
820
- yield responseStream.writeParamsAndEnd({
766
+ await responseStream.writeParamsAndEnd({
821
767
  code: 20000,
822
768
  msg: "Success",
823
769
  data: {
@@ -833,18 +779,18 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
833
779
  signature: sigData.signature
834
780
  }
835
781
  });
836
- })));
837
- const getRefundAuthorization = (0, Utils_1.expressHandlerWrapper)((req, res) => __awaiter(this, void 0, void 0, function* () {
782
+ }));
783
+ const getRefundAuthorization = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
838
784
  /**
839
785
  * paymentHash: string Identifier of the swap
840
786
  * sequence: BN Sequence identifier of the swap
841
787
  */
842
- const parsedBody = (0, SchemaVerifier_1.verifySchema)(Object.assign(Object.assign({}, req.body), req.query), {
788
+ const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
843
789
  paymentHash: (val) => val != null &&
844
790
  typeof (val) === "string" &&
845
791
  val.length === 64 &&
846
792
  Utils_1.HEX_REGEX.test(val) ? val : null,
847
- sequence: SchemaVerifier_1.FieldTypeEnum.BN
793
+ sequence: SchemaVerifier_1.FieldTypeEnum.BigInt
848
794
  });
849
795
  if (parsedBody == null)
850
796
  throw {
@@ -852,18 +798,18 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
852
798
  msg: "Invalid request body/query (paymentHash/sequence)"
853
799
  };
854
800
  this.checkSequence(parsedBody.sequence);
855
- const data = yield this.storageManager.getData(parsedBody.paymentHash, parsedBody.sequence);
801
+ const data = await this.storageManager.getData(parsedBody.paymentHash, parsedBody.sequence);
856
802
  const isSwapFound = data != null;
857
803
  if (isSwapFound) {
858
804
  const { signer, swapContract } = this.getChain(data.chainIdentifier);
859
- if (swapContract.isExpired(signer.getAddress(), data.data))
805
+ if (await swapContract.isExpired(signer.getAddress(), data.data))
860
806
  throw {
861
807
  _httpStatus: 200,
862
808
  code: 20010,
863
809
  msg: "Payment expired"
864
810
  };
865
811
  if (data.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE) {
866
- const refundSigData = yield swapContract.getRefundSignature(signer, data.data, this.config.authorizationTimeout);
812
+ const refundSigData = await swapContract.getRefundSignature(signer, data.data, this.config.refundAuthorizationTimeout);
867
813
  //Double check the state after promise result
868
814
  if (data.state !== ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE)
869
815
  throw {
@@ -884,7 +830,7 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
884
830
  return;
885
831
  }
886
832
  }
887
- const payment = yield this.lightning.getPayment(parsedBody.paymentHash);
833
+ const payment = await this.lightning.getPayment(parsedBody.paymentHash);
888
834
  if (payment == null)
889
835
  throw {
890
836
  _httpStatus: 200,
@@ -915,29 +861,28 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
915
861
  reason: payment.failedReason
916
862
  }
917
863
  };
918
- }));
864
+ });
919
865
  restServer.post(this.path + '/getRefundAuthorization', getRefundAuthorization);
920
866
  restServer.get(this.path + '/getRefundAuthorization', getRefundAuthorization);
921
867
  this.logger.info("started at path: ", this.path);
922
868
  }
923
- init() {
924
- return __awaiter(this, void 0, void 0, function* () {
925
- yield this.storageManager.loadData(ToBtcLnSwapAbs_1.ToBtcLnSwapAbs);
926
- //Check if all swaps contain a valid amount
927
- for (let swap of yield this.storageManager.query([])) {
928
- if (swap.amount == null) {
929
- const parsedPR = yield this.lightning.parsePaymentRequest(swap.pr);
930
- swap.amount = parsedPR.mtokens.add(new BN(999)).div(new BN(1000));
931
- }
869
+ async init() {
870
+ await this.loadData(ToBtcLnSwapAbs_1.ToBtcLnSwapAbs);
871
+ //Check if all swaps contain a valid amount
872
+ for (let { obj: swap } of await this.storageManager.query([])) {
873
+ if (swap.amount == null || swap.lnPaymentHash == null) {
874
+ const parsedPR = await this.lightning.parsePaymentRequest(swap.pr);
875
+ swap.amount = (parsedPR.mtokens + 999n) / 1000n;
876
+ swap.lnPaymentHash = parsedPR.id;
932
877
  }
933
- this.subscribeToEvents();
934
- yield PluginManager_1.PluginManager.serviceInitialize(this);
935
- });
878
+ }
879
+ this.subscribeToEvents();
880
+ await PluginManager_1.PluginManager.serviceInitialize(this);
936
881
  }
937
882
  getInfoData() {
938
883
  return {
939
- minCltv: this.config.minSendCltv.toNumber(),
940
- minTimestampCltv: this.config.minTsSendCltv.toNumber()
884
+ minCltv: Number(this.config.minSendCltv),
885
+ minTimestampCltv: Number(this.config.minTsSendCltv)
941
886
  };
942
887
  }
943
888
  }