@atomiqlabs/lp-lib 13.0.0 → 14.0.0-dev.10

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 (54) hide show
  1. package/dist/index.d.ts +2 -0
  2. package/dist/index.js +2 -0
  3. package/dist/plugins/IPlugin.d.ts +2 -2
  4. package/dist/plugins/PluginManager.d.ts +2 -2
  5. package/dist/storagemanager/IntermediaryStorageManager.d.ts +1 -0
  6. package/dist/storagemanager/IntermediaryStorageManager.js +9 -2
  7. package/dist/storagemanager/StorageManager.d.ts +1 -0
  8. package/dist/storagemanager/StorageManager.js +9 -2
  9. package/dist/swaps/SwapHandler.d.ts +4 -7
  10. package/dist/swaps/SwapHandler.js +4 -7
  11. package/dist/swaps/assertions/FromBtcAmountAssertions.d.ts +2 -2
  12. package/dist/swaps/escrow/EscrowHandlerSwap.js +2 -2
  13. package/dist/swaps/escrow/FromBtcBaseSwapHandler.d.ts +2 -1
  14. package/dist/swaps/escrow/FromBtcBaseSwapHandler.js +8 -5
  15. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +1 -0
  16. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.js +3 -0
  17. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.d.ts +104 -0
  18. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.js +629 -0
  19. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.d.ts +55 -0
  20. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.js +120 -0
  21. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.js +6 -2
  22. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.js +6 -2
  23. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.js +4 -2
  24. package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +1 -6
  25. package/dist/swaps/spv_vault_swap/SpvVaults.js +2 -7
  26. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.js +1 -1
  27. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.js +3 -4
  28. package/dist/utils/Utils.d.ts +7 -7
  29. package/dist/utils/Utils.js +12 -11
  30. package/dist/utils/paramcoders/server/ServerParamDecoder.js +8 -6
  31. package/package.json +2 -2
  32. package/src/index.ts +2 -0
  33. package/src/plugins/IPlugin.ts +2 -2
  34. package/src/plugins/PluginManager.ts +2 -2
  35. package/src/storagemanager/IntermediaryStorageManager.ts +11 -2
  36. package/src/storagemanager/StorageManager.ts +12 -2
  37. package/src/swaps/SwapHandler.ts +5 -8
  38. package/src/swaps/assertions/FromBtcAmountAssertions.ts +3 -3
  39. package/src/swaps/escrow/EscrowHandler.ts +3 -3
  40. package/src/swaps/escrow/EscrowHandlerSwap.ts +2 -2
  41. package/src/swaps/escrow/FromBtcBaseSwapHandler.ts +8 -5
  42. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +4 -0
  43. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.ts +789 -0
  44. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.ts +196 -0
  45. package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +7 -4
  46. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +7 -4
  47. package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +4 -2
  48. package/src/swaps/spv_vault_swap/SpvVaults.ts +3 -8
  49. package/src/swaps/trusted/frombtc_trusted/FromBtcTrusted.ts +1 -1
  50. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +3 -5
  51. package/src/utils/Utils.ts +19 -17
  52. package/src/utils/paramcoders/server/ServerParamDecoder.ts +9 -6
  53. package/dist/wallets/ISpvVaultWallet.d.ts +0 -42
  54. package/dist/wallets/ISpvVaultWallet.js +0 -2
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FromBtcLnAutoSwap = exports.FromBtcLnAutoSwapState = void 0;
4
+ const index_1 = require("../../../index");
5
+ const FromBtcBaseSwap_1 = require("../FromBtcBaseSwap");
6
+ const Utils_1 = require("../../../utils/Utils");
7
+ var FromBtcLnAutoSwapState;
8
+ (function (FromBtcLnAutoSwapState) {
9
+ FromBtcLnAutoSwapState[FromBtcLnAutoSwapState["REFUNDED"] = -2] = "REFUNDED";
10
+ FromBtcLnAutoSwapState[FromBtcLnAutoSwapState["CANCELED"] = -1] = "CANCELED";
11
+ FromBtcLnAutoSwapState[FromBtcLnAutoSwapState["CREATED"] = 0] = "CREATED";
12
+ FromBtcLnAutoSwapState[FromBtcLnAutoSwapState["RECEIVED"] = 1] = "RECEIVED";
13
+ FromBtcLnAutoSwapState[FromBtcLnAutoSwapState["TXS_SENT"] = 2] = "TXS_SENT";
14
+ FromBtcLnAutoSwapState[FromBtcLnAutoSwapState["COMMITED"] = 3] = "COMMITED";
15
+ FromBtcLnAutoSwapState[FromBtcLnAutoSwapState["CLAIMED"] = 4] = "CLAIMED";
16
+ FromBtcLnAutoSwapState[FromBtcLnAutoSwapState["SETTLED"] = 5] = "SETTLED";
17
+ })(FromBtcLnAutoSwapState = exports.FromBtcLnAutoSwapState || (exports.FromBtcLnAutoSwapState = {}));
18
+ class FromBtcLnAutoSwap extends FromBtcBaseSwap_1.FromBtcBaseSwap {
19
+ constructor(chainIdOrObj, pr, lnPaymentHash, claimHash, amountMtokens, claimer, token, gasToken, amountToken, amountGasToken, tokenSwapFee, tokenSwapFeeInToken, gasSwapFee, gasSwapFeeInToken, claimerBounty) {
20
+ if (typeof (chainIdOrObj) === "string") {
21
+ super(chainIdOrObj, (amountMtokens + 999n) / 1000n, tokenSwapFee + gasSwapFee, tokenSwapFeeInToken);
22
+ this.state = FromBtcLnAutoSwapState.CREATED;
23
+ this.pr = pr;
24
+ this.lnPaymentHash = lnPaymentHash;
25
+ this.claimHash = claimHash;
26
+ this.claimer = claimer;
27
+ this.token = token;
28
+ this.gasToken = gasToken;
29
+ this.amountToken = amountToken;
30
+ this.amountGasToken = amountGasToken;
31
+ this.tokenSwapFee = tokenSwapFee;
32
+ this.tokenSwapFeeInToken = tokenSwapFeeInToken;
33
+ this.gasSwapFee = gasSwapFee;
34
+ this.gasSwapFeeInToken = gasSwapFeeInToken;
35
+ this.claimerBounty = claimerBounty;
36
+ }
37
+ else {
38
+ super(chainIdOrObj);
39
+ this.pr = chainIdOrObj.pr;
40
+ this.lnPaymentHash = chainIdOrObj.lnPaymentHash;
41
+ this.claimHash = chainIdOrObj.claimHash;
42
+ this.claimer = chainIdOrObj.claimer;
43
+ this.token = chainIdOrObj.token;
44
+ this.gasToken = chainIdOrObj.gasToken;
45
+ this.amountToken = (0, Utils_1.deserializeBN)(chainIdOrObj.amountToken);
46
+ this.amountGasToken = (0, Utils_1.deserializeBN)(chainIdOrObj.amountGasToken);
47
+ this.tokenSwapFee = (0, Utils_1.deserializeBN)(chainIdOrObj.tokenSwapFee);
48
+ this.tokenSwapFeeInToken = (0, Utils_1.deserializeBN)(chainIdOrObj.tokenSwapFeeInToken);
49
+ this.gasSwapFee = (0, Utils_1.deserializeBN)(chainIdOrObj.gasSwapFee);
50
+ this.gasSwapFeeInToken = (0, Utils_1.deserializeBN)(chainIdOrObj.gasSwapFeeInToken);
51
+ this.claimerBounty = (0, Utils_1.deserializeBN)(chainIdOrObj.claimerBounty);
52
+ this.secret = chainIdOrObj.secret;
53
+ }
54
+ this.type = index_1.SwapHandlerType.FROM_BTCLN;
55
+ }
56
+ serialize() {
57
+ const partialSerialized = super.serialize();
58
+ partialSerialized.pr = this.pr;
59
+ partialSerialized.secret = this.secret;
60
+ partialSerialized.lnPaymentHash = this.lnPaymentHash;
61
+ partialSerialized.claimHash = this.claimHash;
62
+ partialSerialized.claimer = this.claimer;
63
+ partialSerialized.token = this.token;
64
+ partialSerialized.gasToken = this.gasToken;
65
+ partialSerialized.amountToken = (0, Utils_1.serializeBN)(this.amountToken);
66
+ partialSerialized.amountGasToken = (0, Utils_1.serializeBN)(this.amountGasToken);
67
+ partialSerialized.tokenSwapFee = (0, Utils_1.serializeBN)(this.tokenSwapFee);
68
+ partialSerialized.tokenSwapFeeInToken = (0, Utils_1.serializeBN)(this.tokenSwapFeeInToken);
69
+ partialSerialized.gasSwapFee = (0, Utils_1.serializeBN)(this.gasSwapFee);
70
+ partialSerialized.gasSwapFeeInToken = (0, Utils_1.serializeBN)(this.gasSwapFeeInToken);
71
+ partialSerialized.claimerBounty = (0, Utils_1.serializeBN)(this.claimerBounty);
72
+ return partialSerialized;
73
+ }
74
+ getClaimHash() {
75
+ return this.claimHash;
76
+ }
77
+ getIdentifierHash() {
78
+ return this.lnPaymentHash;
79
+ }
80
+ getOutputGasAmount() {
81
+ return this.amountGasToken;
82
+ }
83
+ getOutputAmount() {
84
+ return this.amountToken;
85
+ }
86
+ getTotalOutputAmount() {
87
+ return this.amountToken;
88
+ }
89
+ getTotalOutputGasAmount() {
90
+ return this.amountGasToken + this.claimerBounty;
91
+ }
92
+ getSequence() {
93
+ return 0n;
94
+ }
95
+ getSwapFee() {
96
+ return { inInputToken: this.swapFee, inOutputToken: this.swapFeeInToken };
97
+ }
98
+ getTokenSwapFee() {
99
+ return { inInputToken: this.tokenSwapFee, inOutputToken: this.tokenSwapFeeInToken };
100
+ }
101
+ getGasSwapFee() {
102
+ return { inInputToken: this.gasSwapFee, inOutputToken: this.gasSwapFeeInToken };
103
+ }
104
+ getToken() {
105
+ return this.token;
106
+ }
107
+ getGasToken() {
108
+ return this.gasToken;
109
+ }
110
+ isInitiated() {
111
+ return this.state !== FromBtcLnAutoSwapState.CREATED;
112
+ }
113
+ isFailed() {
114
+ return this.state === FromBtcLnAutoSwapState.CANCELED || this.state === FromBtcLnAutoSwapState.REFUNDED;
115
+ }
116
+ isSuccess() {
117
+ return this.state === FromBtcLnAutoSwapState.SETTLED;
118
+ }
119
+ }
120
+ exports.FromBtcLnAutoSwap = FromBtcLnAutoSwap;
@@ -100,14 +100,18 @@ class ToBtcAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
100
100
  const isCommited = await swapContract.isCommited(swap.data);
101
101
  if (!isCommited) {
102
102
  const status = await swapContract.getCommitStatus(signer.getAddress(), swap.data);
103
- if (status === base_1.SwapCommitStatus.PAID) {
103
+ if (status.type === base_1.SwapCommitStateType.PAID) {
104
104
  this.swapLogger.info(swap, "processPastSwap(state=BTC_SENT): swap claimed (detected from processPastSwap), address: " + swap.address);
105
105
  this.unsubscribePayment(swap);
106
+ swap.txIds ?? (swap.txIds = {});
107
+ swap.txIds.claim = await status.getClaimTxId();
106
108
  await this.removeSwapData(swap, ToBtcSwapAbs_1.ToBtcSwapState.CLAIMED);
107
109
  }
108
- else if (status === base_1.SwapCommitStatus.EXPIRED) {
110
+ else if (status.type === base_1.SwapCommitStateType.EXPIRED) {
109
111
  this.swapLogger.warn(swap, "processPastSwap(state=BTC_SENT): swap expired, but bitcoin was probably already sent, txId: " + swap.txId + " address: " + swap.address);
110
112
  this.unsubscribePayment(swap);
113
+ swap.txIds ?? (swap.txIds = {});
114
+ swap.txIds.refund = status.getRefundTxId == null ? null : await status.getRefundTxId();
111
115
  await this.removeSwapData(swap, ToBtcSwapAbs_1.ToBtcSwapState.REFUNDED);
112
116
  }
113
117
  return;
@@ -120,13 +120,17 @@ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
120
120
  const isCommited = await swapContract.isCommited(swap.data);
121
121
  if (!isCommited) {
122
122
  const status = await swapContract.getCommitStatus(signer.getAddress(), swap.data);
123
- if (status === base_1.SwapCommitStatus.PAID) {
123
+ if (status?.type === base_1.SwapCommitStateType.PAID) {
124
124
  //This is alright, we got the money
125
+ swap.txIds ?? (swap.txIds = {});
126
+ swap.txIds.claim = await status.getClaimTxId();
125
127
  await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CLAIMED);
126
128
  return true;
127
129
  }
128
- else if (status === base_1.SwapCommitStatus.EXPIRED) {
130
+ else if (status?.type === base_1.SwapCommitStateType.EXPIRED) {
129
131
  //This means the user was able to refund before we were able to claim, no good
132
+ swap.txIds ?? (swap.txIds = {});
133
+ swap.txIds.refund = status.getRefundTxId == null ? null : await status.getRefundTxId();
130
134
  await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.REFUNDED);
131
135
  }
132
136
  this.swapLogger.warn(swap, "processPaymentResult(): tried to claim but escrow doesn't exist anymore," +
@@ -366,7 +366,7 @@ class SpvVaultSwapHandler extends SwapHandler_1.SwapHandler {
366
366
  msg: "PSBT transaction cannot be parsed!"
367
367
  };
368
368
  }
369
- if (data.recipient !== swap.recipient ||
369
+ if (!data.isRecipient(swap.recipient) ||
370
370
  data.callerFeeRate !== swap.callerFeeShare ||
371
371
  data.frontingFeeRate !== swap.frontingFeeShare ||
372
372
  data.executionFeeRate !== swap.executionFeeShare ||
@@ -376,7 +376,9 @@ class SpvVaultSwapHandler extends SwapHandler_1.SwapHandler {
376
376
  data.btcTx.outs[0].value !== SpvVaults_1.VAULT_DUST_AMOUNT ||
377
377
  !Buffer.from(data.btcTx.outs[0].scriptPubKey.hex, "hex").equals(this.bitcoin.toOutputScript(swap.vaultAddress)) ||
378
378
  BigInt(data.btcTx.outs[2].value) !== swap.amountBtc ||
379
- !Buffer.from(data.btcTx.outs[2].scriptPubKey.hex, "hex").equals(this.bitcoin.toOutputScript(swap.btcAddress))) {
379
+ !Buffer.from(data.btcTx.outs[2].scriptPubKey.hex, "hex").equals(this.bitcoin.toOutputScript(swap.btcAddress)) ||
380
+ (data.btcTx.locktime > 0 && data.btcTx.locktime < 500000000) ||
381
+ data.btcTx.locktime > Math.floor(Date.now() / 1000) - 1000000) {
380
382
  this.swapLogger.error(swap, "REST: /postQuote: Invalid psbt data submitted, raw psbt hex: ", parsedBody.psbtHex);
381
383
  throw {
382
384
  code: 20509,
@@ -15,12 +15,7 @@ export declare class SpvVaults {
15
15
  maxUnclaimedWithdrawals?: number;
16
16
  };
17
17
  readonly getChain: (chainId: string) => ChainData;
18
- readonly logger: {
19
- debug: (msg: string, ...args: any) => void;
20
- info: (msg: string, ...args: any) => void;
21
- warn: (msg: string, ...args: any) => void;
22
- error: (msg: string, ...args: any) => void;
23
- };
18
+ readonly logger: import("../../utils/Utils").LoggerType;
24
19
  constructor(vaultStorage: IStorageManager<SpvVault>, bitcoin: IBitcoinWallet, vaultSigner: ISpvVaultSigner, bitcoinRpc: BitcoinRpc<any>, getChain: (chainId: string) => ChainData, config: {
25
20
  vaultsCheckInterval: number;
26
21
  maxUnclaimedWithdrawals?: number;
@@ -11,12 +11,7 @@ const VAULT_INIT_CONFIRMATIONS = 2;
11
11
  const BTC_FINALIZATION_CONFIRMATIONS = 6;
12
12
  class SpvVaults {
13
13
  constructor(vaultStorage, bitcoin, vaultSigner, bitcoinRpc, getChain, config) {
14
- this.logger = {
15
- debug: (msg, ...args) => console.debug("SpvVaults: " + msg, ...args),
16
- info: (msg, ...args) => console.info("SpvVaults: " + msg, ...args),
17
- warn: (msg, ...args) => console.warn("SpvVaults: " + msg, ...args),
18
- error: (msg, ...args) => console.error("SpvVaults: " + msg, ...args)
19
- };
14
+ this.logger = (0, Utils_1.getLogger)("SpvVaults: ");
20
15
  this.vaultStorage = vaultStorage;
21
16
  this.bitcoin = bitcoin;
22
17
  this.vaultSigner = vaultSigner;
@@ -357,7 +352,7 @@ class SpvVaults {
357
352
  async startVaultsWatchdog() {
358
353
  let rerun;
359
354
  rerun = async () => {
360
- await this.checkVaults().catch(e => console.error(e));
355
+ await this.checkVaults().catch(e => this.logger.error("startVaultsWatchdog(): Error when periodically checking SPV vaults: ", e));
361
356
  setTimeout(rerun, this.config.vaultsCheckInterval);
362
357
  };
363
358
  await rerun();
@@ -618,7 +618,7 @@ class FromBtcTrusted extends SwapHandler_1.SwapHandler {
618
618
  async startDoubleSpendWatchdog() {
619
619
  let rerun;
620
620
  rerun = async () => {
621
- await this.checkDoubleSpends().catch(e => console.error(e));
621
+ await this.checkDoubleSpends().catch(e => this.logger.error("startDoubleSpendWatchdog(): Error when checking double spends: ", e));
622
622
  setTimeout(rerun, this.config.doubleSpendCheckInterval);
623
623
  };
624
624
  await rerun();
@@ -53,7 +53,7 @@ class FromBtcLnTrusted extends SwapHandler_1.SwapHandler {
53
53
  this.swapLogger.debug(invoiceData, "subscribeToInvoice(): invoice_updated: ", invoice);
54
54
  if (invoice.status !== "held")
55
55
  return;
56
- this.htlcReceived(invoiceData, invoice).catch(e => console.error(e));
56
+ this.htlcReceived(invoiceData, invoice).catch(e => this.swapLogger.error(invoiceData, "subscribeToInvoice(): Error calling htlcReceived(): ", e));
57
57
  this.activeSubscriptions.delete(hash);
58
58
  });
59
59
  this.swapLogger.debug(invoiceData, "subscribeToInvoice(): Subscribed to invoice payment");
@@ -79,7 +79,7 @@ class FromBtcLnTrusted extends SwapHandler_1.SwapHandler {
79
79
  //Result is either FromBtcLnTrustedSwapState.RECEIVED or FromBtcLnTrustedSwapState.CANCELED
80
80
  }
81
81
  catch (e) {
82
- console.error(e);
82
+ this.swapLogger.error(swap, "processPastSwap(): Error calling htlcReceived(): ", e);
83
83
  }
84
84
  return false;
85
85
  case "confirmed":
@@ -182,7 +182,7 @@ class FromBtcLnTrusted extends SwapHandler_1.SwapHandler {
182
182
  await invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.SENT);
183
183
  await this.storageManager.saveData(invoice.id, null, invoiceData);
184
184
  }
185
- }).catch(e => console.error(e));
185
+ }).catch(e => this.swapLogger.error(invoiceData, "htlcReceived(): Error sending transfer txns", e));
186
186
  if (result == null) {
187
187
  //Cancel invoice
188
188
  await invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.REFUNDED);
@@ -385,7 +385,6 @@ class FromBtcLnTrusted extends SwapHandler_1.SwapHandler {
385
385
  abortController.signal.throwIfAborted();
386
386
  metadata.times.invoiceCreated = Date.now();
387
387
  metadata.invoiceResponse = { ...hodlInvoice };
388
- console.log("[From BTC-LN: REST.CreateInvoice] hodl invoice created: ", hodlInvoice);
389
388
  const createdSwap = new FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwap(chainIdentifier, hodlInvoice.request, hodlInvoice.mtokens, swapFee, swapFeeInToken, totalInToken, secret.toString("hex"), parsedBody.address, useToken);
390
389
  metadata.times.swapCreated = Date.now();
391
390
  createdSwap.metadata = metadata;
@@ -1,5 +1,12 @@
1
1
  import { Request, Response } from "express";
2
2
  import { ServerParamEncoder } from "./paramcoders/server/ServerParamEncoder";
3
+ export type LoggerType = {
4
+ debug: (msg: string, ...args: any[]) => void;
5
+ info: (msg: string, ...args: any[]) => void;
6
+ warn: (msg: string, ...args: any[]) => void;
7
+ error: (msg: string, ...args: any[]) => void;
8
+ };
9
+ export declare function getLogger(prefix: string | (() => string)): LoggerType;
3
10
  export type DefinedRuntimeError = {
4
11
  code: number;
5
12
  msg?: string;
@@ -10,13 +17,6 @@ export declare function isDefinedRuntimeError(obj: any): obj is DefinedRuntimeEr
10
17
  export declare function expressHandlerWrapper(func: (req: Request, res: Response) => Promise<void>): ((req: Request, res: Response & {
11
18
  responseStream: ServerParamEncoder;
12
19
  }) => void);
13
- export type LoggerType = {
14
- debug: (msg: string, ...args: any[]) => void;
15
- info: (msg: string, ...args: any[]) => void;
16
- warn: (msg: string, ...args: any[]) => void;
17
- error: (msg: string, ...args: any[]) => void;
18
- };
19
- export declare function getLogger(prefix: string): LoggerType;
20
20
  export declare const HEX_REGEX: RegExp;
21
21
  export declare function serializeBN(bn: bigint | null): string | null;
22
22
  export declare function deserializeBN(str: string | null): bigint | null;
@@ -1,6 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getAbortController = exports.bigIntSorter = exports.deserializeBN = exports.serializeBN = exports.HEX_REGEX = exports.getLogger = exports.expressHandlerWrapper = exports.isDefinedRuntimeError = void 0;
3
+ exports.getAbortController = exports.bigIntSorter = exports.deserializeBN = exports.serializeBN = exports.HEX_REGEX = exports.expressHandlerWrapper = exports.isDefinedRuntimeError = exports.getLogger = void 0;
4
+ function getLogger(prefix) {
5
+ return {
6
+ debug: (msg, ...args) => global.atomiqLogLevel >= 3 && console.debug((typeof (prefix) === "function" ? prefix() : prefix) + msg, ...args),
7
+ info: (msg, ...args) => global.atomiqLogLevel >= 2 && console.info((typeof (prefix) === "function" ? prefix() : prefix) + msg, ...args),
8
+ warn: (msg, ...args) => (global.atomiqLogLevel == null || global.atomiqLogLevel >= 1) && console.warn((typeof (prefix) === "function" ? prefix() : prefix) + msg, ...args),
9
+ error: (msg, ...args) => (global.atomiqLogLevel == null || global.atomiqLogLevel >= 0) && console.error((typeof (prefix) === "function" ? prefix() : prefix) + msg, ...args)
10
+ };
11
+ }
12
+ exports.getLogger = getLogger;
4
13
  function isDefinedRuntimeError(obj) {
5
14
  if (obj.code != null && typeof (obj.code) === "number") {
6
15
  if (obj.msg != null && typeof (obj.msg) !== "string")
@@ -12,6 +21,7 @@ function isDefinedRuntimeError(obj) {
12
21
  return false;
13
22
  }
14
23
  exports.isDefinedRuntimeError = isDefinedRuntimeError;
24
+ const expressHandlerWrapperLogger = getLogger("ExpressHandlerWrapper: ");
15
25
  function expressHandlerWrapper(func) {
16
26
  return (req, res) => {
17
27
  (async () => {
@@ -19,7 +29,7 @@ function expressHandlerWrapper(func) {
19
29
  await func(req, res);
20
30
  }
21
31
  catch (e) {
22
- console.error(e);
32
+ expressHandlerWrapperLogger.error("Error in called function " + req.path + ": ", e);
23
33
  let statusCode = 500;
24
34
  const obj = {
25
35
  code: 0,
@@ -46,15 +56,6 @@ function expressHandlerWrapper(func) {
46
56
  };
47
57
  }
48
58
  exports.expressHandlerWrapper = expressHandlerWrapper;
49
- function getLogger(prefix) {
50
- return {
51
- debug: (msg, ...args) => console.debug(prefix + msg, ...args),
52
- info: (msg, ...args) => console.info(prefix + msg, ...args),
53
- warn: (msg, ...args) => console.warn(prefix + msg, ...args),
54
- error: (msg, ...args) => console.error(prefix + msg, ...args)
55
- };
56
- }
57
- exports.getLogger = getLogger;
58
59
  exports.HEX_REGEX = /[0-9a-fA-F]+/;
59
60
  function serializeBN(bn) {
60
61
  return bn == null ? null : bn.toString(10);
@@ -4,6 +4,7 @@ exports.serverParamDecoder = exports.RequestParsingError = exports.RequestTimeou
4
4
  const SchemaVerifier_1 = require("../SchemaVerifier");
5
5
  const ParamDecoder_1 = require("../ParamDecoder");
6
6
  const ServerParamEncoder_1 = require("./ServerParamEncoder");
7
+ const Utils_1 = require("../../Utils");
7
8
  class RequestTimeoutError extends Error {
8
9
  constructor() {
9
10
  super("Request timed out");
@@ -20,6 +21,7 @@ class RequestParsingError extends Error {
20
21
  }
21
22
  }
22
23
  exports.RequestParsingError = RequestParsingError;
24
+ const logger = (0, Utils_1.getLogger)("ServerParamDecoder: ");
23
25
  const serverParamDecoder = (timeoutMillis) => (req, res, next) => {
24
26
  let timeout;
25
27
  res.responseStream = new ServerParamEncoder_1.ServerParamEncoder(res, 200, req);
@@ -43,14 +45,14 @@ const serverParamDecoder = (timeoutMillis) => (req, res, next) => {
43
45
  next();
44
46
  }
45
47
  catch (e) {
46
- console.error("ServerParamDecoder: error reading legacy (non-streaming) http request", e);
48
+ logger.error("error reading legacy (non-streaming) http request", e);
47
49
  req.destroy(new RequestParsingError());
48
50
  res.destroy(new RequestParsingError());
49
51
  }
50
52
  clearTimeout(timeout);
51
53
  });
52
54
  req.on("error", (e) => {
53
- console.error("ServerParamDecoder: error reading legacy (non-streaming) http request", e);
55
+ logger.error("error reading legacy (non-streaming) http request", e);
54
56
  });
55
57
  timeout = setTimeout(() => {
56
58
  req.destroy(new RequestTimeoutError());
@@ -64,7 +66,7 @@ const serverParamDecoder = (timeoutMillis) => (req, res, next) => {
64
66
  decoder.onData(data);
65
67
  }
66
68
  catch (e) {
67
- console.error("ServerParamDecoder: error reading streaming http request: on(\"data\")", e);
69
+ logger.error("error reading streaming http request: on(\"data\")", e);
68
70
  req.destroy(new RequestParsingError());
69
71
  res.destroy(new RequestParsingError());
70
72
  }
@@ -74,7 +76,7 @@ const serverParamDecoder = (timeoutMillis) => (req, res, next) => {
74
76
  decoder.onEnd();
75
77
  }
76
78
  catch (e) {
77
- console.error("ServerParamDecoder: error reading streaming http request: on(\"end\")", e);
79
+ logger.error("error reading streaming http request: on(\"end\")", e);
78
80
  req.destroy(new RequestParsingError());
79
81
  res.destroy(new RequestParsingError());
80
82
  }
@@ -85,7 +87,7 @@ const serverParamDecoder = (timeoutMillis) => (req, res, next) => {
85
87
  decoder.onError(e);
86
88
  }
87
89
  catch (e) {
88
- console.error("ServerParamDecoder: error reading streaming http request: on(\"error\")", e);
90
+ logger.error("error reading streaming http request: on(\"error\")", e);
89
91
  }
90
92
  });
91
93
  timeout = setTimeout(() => {
@@ -93,7 +95,7 @@ const serverParamDecoder = (timeoutMillis) => (req, res, next) => {
93
95
  decoder.onEnd();
94
96
  }
95
97
  catch (e) {
96
- console.error("ServerParamDecoder: error reading streaming http request: timeout", e);
98
+ logger.error("error reading streaming http request: timeout", e);
97
99
  }
98
100
  req.destroy(new RequestTimeoutError());
99
101
  res.destroy(new RequestTimeoutError());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atomiqlabs/lp-lib",
3
- "version": "13.0.0",
3
+ "version": "14.0.0-dev.10",
4
4
  "description": "Main functionality implementation for atomiq LP node",
5
5
  "main": "./dist/index.js",
6
6
  "types:": "./dist/index.d.ts",
@@ -22,7 +22,7 @@
22
22
  "author": "adambor",
23
23
  "license": "ISC",
24
24
  "dependencies": {
25
- "@atomiqlabs/base": "^9.0.0",
25
+ "@atomiqlabs/base": "^10.0.0-dev.7",
26
26
  "@atomiqlabs/server-base": "2.0.0",
27
27
  "@scure/btc-signer": "1.6.0",
28
28
  "express": "4.21.1",
package/src/index.ts CHANGED
@@ -13,6 +13,8 @@ export * from "./swaps/escrow/frombtc_abstract/FromBtcAbs";
13
13
  export * from "./swaps/escrow/frombtc_abstract/FromBtcSwapAbs";
14
14
  export * from "./swaps/escrow/frombtcln_abstract/FromBtcLnAbs";
15
15
  export * from "./swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs";
16
+ export * from "./swaps/escrow/frombtcln_autoinit/FromBtcLnAuto";
17
+ export * from "./swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap";
16
18
  export * from "./swaps/escrow/tobtc_abstract/ToBtcAbs";
17
19
  export * from "./swaps/escrow/tobtc_abstract/ToBtcSwapAbs";
18
20
  export * from "./swaps/escrow/tobtcln_abstract/ToBtcLnAbs";
@@ -116,7 +116,7 @@ export interface IPlugin {
116
116
  onSwapRemove?(swap: SwapHandlerSwap): Promise<void>;
117
117
 
118
118
  onHandlePreFromBtcQuote?(
119
- swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV,
119
+ swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV | SwapHandlerType.FROM_BTCLN_AUTO,
120
120
  request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>,
121
121
  requestedAmount: {input: boolean, amount: bigint, token: string},
122
122
  chainIdentifier: string,
@@ -125,7 +125,7 @@ export interface IPlugin {
125
125
  gasTokenAmount?: {input: false, amount: bigint, token: string}
126
126
  ): Promise<QuoteThrow | QuoteSetFees | QuoteAmountTooLow | QuoteAmountTooHigh>;
127
127
  onHandlePostFromBtcQuote?(
128
- swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV,
128
+ swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV | SwapHandlerType.FROM_BTCLN_AUTO,
129
129
  request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>,
130
130
  requestedAmount: {input: boolean, amount: bigint, token: string, pricePrefetch?: Promise<bigint>},
131
131
  chainIdentifier: string,
@@ -167,7 +167,7 @@ export class PluginManager {
167
167
  }
168
168
 
169
169
  static async onHandlePostFromBtcQuote(
170
- swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV,
170
+ swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV | SwapHandlerType.FROM_BTCLN_AUTO,
171
171
  request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>,
172
172
  requestedAmount: {input: boolean, amount: bigint, token: string, pricePrefetch?: Promise<bigint>},
173
173
  chainIdentifier: string,
@@ -198,7 +198,7 @@ export class PluginManager {
198
198
  }
199
199
 
200
200
  static async onHandlePreFromBtcQuote(
201
- swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV,
201
+ swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV | SwapHandlerType.FROM_BTCLN_AUTO,
202
202
  request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>,
203
203
  requestedAmount: {input: boolean, amount: bigint, token: string},
204
204
  chainIdentifier: string,
@@ -1,6 +1,8 @@
1
1
  import {StorageObject} from "@atomiqlabs/base";
2
2
  import * as fs from "fs/promises";
3
+ import * as fsSync from "fs";
3
4
  import {IIntermediaryStorage, StorageQueryParam} from "../storage/IIntermediaryStorage";
5
+ import {getLogger, LoggerType} from "../utils/Utils";
4
6
 
5
7
  export class IntermediaryStorageManager<T extends StorageObject> implements IIntermediaryStorage<T> {
6
8
 
@@ -9,9 +11,11 @@ export class IntermediaryStorageManager<T extends StorageObject> implements IInt
9
11
  private data: {
10
12
  [key: string]: T
11
13
  } = {};
14
+ private logger: LoggerType;
12
15
 
13
16
  constructor(directory: string) {
14
17
  this.directory = directory;
18
+ this.logger = getLogger("IntermediaryStorageManager("+directory+"): ");
15
19
  }
16
20
 
17
21
  async init(): Promise<void> {
@@ -82,18 +86,23 @@ export class IntermediaryStorageManager<T extends StorageObject> implements IInt
82
86
  if(this.data[identifier]!=null) delete this.data[identifier];
83
87
  await fs.rm(this.directory+"/"+identifier+".json");
84
88
  } catch (e) {
85
- console.error(e);
89
+ this.logger.error("removeData(): Error when removing data: ", e);
86
90
  }
87
91
  }
88
92
 
89
93
  async loadData(type: new(data: any) => T): Promise<void> {
90
94
  this.type = type;
91
95
 
96
+ if(!fsSync.existsSync(this.directory)) {
97
+ this.logger.debug("loadData(): Data directory not found!");
98
+ return;
99
+ }
100
+
92
101
  let files: string[];
93
102
  try {
94
103
  files = await fs.readdir(this.directory);
95
104
  } catch (e) {
96
- console.error(e);
105
+ this.logger.error("loadData(): Error when checking directory: ", e);
97
106
  return;
98
107
  }
99
108
 
@@ -1,5 +1,7 @@
1
1
  import {StorageObject, IStorageManager} from "@atomiqlabs/base";
2
2
  import * as fs from "fs/promises";
3
+ import {getLogger, LoggerType} from "../utils/Utils";
4
+ import * as fsSync from "fs";
3
5
 
4
6
  export class StorageManager<T extends StorageObject> implements IStorageManager<T> {
5
7
 
@@ -8,8 +10,11 @@ export class StorageManager<T extends StorageObject> implements IStorageManager<
8
10
  [key: string]: T
9
11
  } = {};
10
12
 
13
+ private logger: LoggerType;
14
+
11
15
  constructor(directory: string) {
12
16
  this.directory = directory;
17
+ this.logger = getLogger("StorageManager("+directory+"): ");
13
18
  }
14
19
 
15
20
  async init(): Promise<void> {
@@ -38,16 +43,21 @@ export class StorageManager<T extends StorageObject> implements IStorageManager<
38
43
  if(this.data[paymentHash]!=null) delete this.data[paymentHash];
39
44
  await fs.rm(this.directory+"/"+paymentHash+".json");
40
45
  } catch (e) {
41
- console.error(e);
46
+ this.logger.error("removeData(): Error when removing data: ", e);
42
47
  }
43
48
  }
44
49
 
45
50
  async loadData(type: new(data: any) => T): Promise<T[]> {
51
+ if(!fsSync.existsSync(this.directory)) {
52
+ this.logger.debug("loadData(): Data directory not found!");
53
+ return;
54
+ }
55
+
46
56
  let files;
47
57
  try {
48
58
  files = await fs.readdir(this.directory);
49
59
  } catch (e) {
50
- console.error(e);
60
+ this.logger.error("loadData(): Error when checking directory: ", e);
51
61
  return [];
52
62
  }
53
63
 
@@ -8,6 +8,7 @@ import {SwapHandlerSwap} from "./SwapHandlerSwap";
8
8
  import {PluginManager} from "../plugins/PluginManager";
9
9
  import {IIntermediaryStorage} from "../storage/IIntermediaryStorage";
10
10
  import {IParamReader} from "../utils/paramcoders/IParamReader";
11
+ import {getLogger, LoggerType} from "../utils/Utils";
11
12
 
12
13
  export enum SwapHandlerType {
13
14
  TO_BTC = "TO_BTC",
@@ -16,7 +17,8 @@ export enum SwapHandlerType {
16
17
  FROM_BTCLN = "FROM_BTCLN",
17
18
  FROM_BTCLN_TRUSTED = "FROM_BTCLN_TRUSTED",
18
19
  FROM_BTC_TRUSTED = "FROM_BTC_TRUSTED",
19
- FROM_BTC_SPV = "FROM_BTC_SPV"
20
+ FROM_BTC_SPV = "FROM_BTC_SPV",
21
+ FROM_BTCLN_AUTO = "FROM_BTCLN_AUTO"
20
22
  }
21
23
 
22
24
  export type SwapHandlerInfoType = {
@@ -85,12 +87,7 @@ export abstract class SwapHandler<V extends SwapHandlerSwap<S> = SwapHandlerSwap
85
87
 
86
88
  abstract config: SwapBaseConfig;
87
89
 
88
- logger = {
89
- debug: (msg: string, ...args: any) => console.debug("SwapHandler("+this.type+"): "+msg, ...args),
90
- info: (msg: string, ...args: any) => console.info("SwapHandler("+this.type+"): "+msg, ...args),
91
- warn: (msg: string, ...args: any) => console.warn("SwapHandler("+this.type+"): "+msg, ...args),
92
- error: (msg: string, ...args: any) => console.error("SwapHandler("+this.type+"): "+msg, ...args)
93
- };
90
+ logger: LoggerType = getLogger(() => "SwapHandler("+this.type+"): ");
94
91
 
95
92
  protected swapLogger = {
96
93
  debug: (swap: SwapHandlerSwap, msg: string, ...args: any) => this.logger.debug(swap.getIdentifier()+": "+msg, ...args),
@@ -137,7 +134,7 @@ export abstract class SwapHandler<V extends SwapHandlerSwap<S> = SwapHandlerSwap
137
134
  async startWatchdog() {
138
135
  let rerun: () => Promise<void>;
139
136
  rerun = async () => {
140
- await this.processPastSwaps().catch( e => console.error(e));
137
+ await this.processPastSwaps().catch( e => this.logger.error("startWatchdog(): Error when processing past swaps: ", e));
141
138
  setTimeout(rerun, this.config.swapCheckInterval);
142
139
  };
143
140
  await rerun();
@@ -3,7 +3,7 @@ import {FromBtcRequestType} from "../escrow/frombtc_abstract/FromBtcAbs";
3
3
  import {FromBtcLnTrustedRequestType} from "../trusted/frombtcln_trusted/FromBtcLnTrusted";
4
4
  import {PluginManager} from "../../plugins/PluginManager";
5
5
  import {isPluginQuote, isQuoteSetFees} from "../../plugins/IPlugin";
6
- import {RequestData, SwapHandlerType} from "../SwapHandler";
6
+ import {RequestData, SwapHandler, SwapHandlerType} from "../SwapHandler";
7
7
  import {AmountAssertions, AmountAssertionsConfig} from "./AmountAssertions";
8
8
  import {ISwapPrice} from "../../prices/ISwapPrice";
9
9
  import {FromBtcTrustedRequestType} from "../trusted/frombtc_trusted/FromBtcTrusted";
@@ -32,7 +32,7 @@ export class FromBtcAmountAssertions extends AmountAssertions {
32
32
  * @throws {DefinedRuntimeError} will throw an error if the amount is outside minimum/maximum bounds
33
33
  */
34
34
  async preCheckFromBtcAmounts(
35
- swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV,
35
+ swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV | SwapHandlerType.FROM_BTCLN_AUTO,
36
36
  request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>,
37
37
  requestedAmount: {input: boolean, amount: bigint, token: string},
38
38
  gasAmount?: {input: false, amount: bigint, token: string}
@@ -94,7 +94,7 @@ export class FromBtcAmountAssertions extends AmountAssertions {
94
94
  * @throws {DefinedRuntimeError} will throw an error if the amount is outside minimum/maximum bounds
95
95
  */
96
96
  async checkFromBtcAmount(
97
- swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV,
97
+ swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV | SwapHandlerType.FROM_BTCLN_AUTO,
98
98
  request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>,
99
99
  requestedAmount: {input: boolean, amount: bigint, token: string, pricePrefetch?: Promise<bigint>},
100
100
  fees: {baseFee: bigint, feePPM: bigint},