@atomiqlabs/lp-lib 15.0.13 → 16.0.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 (66) hide show
  1. package/dist/index.d.ts +2 -0
  2. package/dist/index.js +2 -0
  3. package/dist/info/InfoHandler.js +0 -3
  4. package/dist/plugins/IPlugin.d.ts +2 -2
  5. package/dist/plugins/PluginManager.d.ts +2 -2
  6. package/dist/storagemanager/IntermediaryStorageManager.d.ts +1 -0
  7. package/dist/storagemanager/IntermediaryStorageManager.js +9 -2
  8. package/dist/storagemanager/StorageManager.d.ts +1 -0
  9. package/dist/storagemanager/StorageManager.js +9 -2
  10. package/dist/swaps/SwapHandler.d.ts +4 -10
  11. package/dist/swaps/SwapHandler.js +4 -13
  12. package/dist/swaps/assertions/FromBtcAmountAssertions.d.ts +2 -2
  13. package/dist/swaps/assertions/FromBtcAmountAssertions.js +13 -5
  14. package/dist/swaps/escrow/EscrowHandlerSwap.js +2 -2
  15. package/dist/swaps/escrow/FromBtcBaseSwapHandler.d.ts +2 -1
  16. package/dist/swaps/escrow/FromBtcBaseSwapHandler.js +8 -5
  17. package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.js +2 -2
  18. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.js +11 -13
  19. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +1 -0
  20. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.js +3 -0
  21. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.d.ts +111 -0
  22. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.js +682 -0
  23. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.d.ts +55 -0
  24. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.js +120 -0
  25. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.d.ts +0 -2
  26. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.js +44 -27
  27. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.js +12 -10
  28. package/dist/swaps/spv_vault_swap/SpvVault.d.ts +2 -3
  29. package/dist/swaps/spv_vault_swap/SpvVault.js +2 -2
  30. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.js +10 -8
  31. package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +4 -9
  32. package/dist/swaps/spv_vault_swap/SpvVaults.js +114 -80
  33. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.js +3 -3
  34. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.js +14 -17
  35. package/dist/utils/Utils.d.ts +7 -7
  36. package/dist/utils/Utils.js +12 -11
  37. package/dist/utils/paramcoders/server/ServerParamDecoder.js +8 -6
  38. package/dist/wallets/IBitcoinWallet.d.ts +7 -0
  39. package/package.json +3 -3
  40. package/src/index.ts +2 -0
  41. package/src/info/InfoHandler.ts +0 -6
  42. package/src/plugins/IPlugin.ts +2 -2
  43. package/src/plugins/PluginManager.ts +2 -2
  44. package/src/storagemanager/IntermediaryStorageManager.ts +11 -2
  45. package/src/storagemanager/StorageManager.ts +12 -2
  46. package/src/swaps/SwapHandler.ts +6 -17
  47. package/src/swaps/assertions/FromBtcAmountAssertions.ts +16 -8
  48. package/src/swaps/escrow/EscrowHandlerSwap.ts +2 -2
  49. package/src/swaps/escrow/FromBtcBaseSwapHandler.ts +8 -5
  50. package/src/swaps/escrow/frombtc_abstract/FromBtcAbs.ts +2 -2
  51. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.ts +11 -12
  52. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +4 -0
  53. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.ts +847 -0
  54. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.ts +196 -0
  55. package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +55 -36
  56. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +19 -15
  57. package/src/swaps/spv_vault_swap/SpvVault.ts +3 -3
  58. package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +10 -8
  59. package/src/swaps/spv_vault_swap/SpvVaults.ts +130 -91
  60. package/src/swaps/trusted/frombtc_trusted/FromBtcTrusted.ts +3 -3
  61. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +13 -16
  62. package/src/utils/Utils.ts +19 -17
  63. package/src/utils/paramcoders/server/ServerParamDecoder.ts +9 -6
  64. package/src/wallets/IBitcoinWallet.ts +8 -0
  65. package/dist/wallets/ISpvVaultWallet.d.ts +0 -42
  66. package/dist/wallets/ISpvVaultWallet.js +0 -2
package/dist/index.d.ts CHANGED
@@ -9,6 +9,8 @@ export * from "./swaps/escrow/frombtc_abstract/FromBtcAbs";
9
9
  export * from "./swaps/escrow/frombtc_abstract/FromBtcSwapAbs";
10
10
  export * from "./swaps/escrow/frombtcln_abstract/FromBtcLnAbs";
11
11
  export * from "./swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs";
12
+ export * from "./swaps/escrow/frombtcln_autoinit/FromBtcLnAuto";
13
+ export * from "./swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap";
12
14
  export * from "./swaps/escrow/tobtc_abstract/ToBtcAbs";
13
15
  export * from "./swaps/escrow/tobtc_abstract/ToBtcSwapAbs";
14
16
  export * from "./swaps/escrow/tobtcln_abstract/ToBtcLnAbs";
package/dist/index.js CHANGED
@@ -25,6 +25,8 @@ __exportStar(require("./swaps/escrow/frombtc_abstract/FromBtcAbs"), exports);
25
25
  __exportStar(require("./swaps/escrow/frombtc_abstract/FromBtcSwapAbs"), exports);
26
26
  __exportStar(require("./swaps/escrow/frombtcln_abstract/FromBtcLnAbs"), exports);
27
27
  __exportStar(require("./swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs"), exports);
28
+ __exportStar(require("./swaps/escrow/frombtcln_autoinit/FromBtcLnAuto"), exports);
29
+ __exportStar(require("./swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap"), exports);
28
30
  __exportStar(require("./swaps/escrow/tobtc_abstract/ToBtcAbs"), exports);
29
31
  __exportStar(require("./swaps/escrow/tobtc_abstract/ToBtcSwapAbs"), exports);
30
32
  __exportStar(require("./swaps/escrow/tobtcln_abstract/ToBtcLnAbs"), exports);
@@ -47,11 +47,8 @@ class InfoHandler {
47
47
  signature: await singleChain.swapContract.getDataSignature(singleChain.signer, envelopeBuffer)
48
48
  };
49
49
  }
50
- const defaults = chains[this.chainData.default];
51
50
  const response = {
52
51
  envelope,
53
- address: defaults.address,
54
- signature: defaults.signature,
55
52
  chains
56
53
  };
57
54
  res.status(200).json(response);
@@ -72,7 +72,7 @@ export interface IPlugin {
72
72
  onSwapStateChange?(swap: SwapHandlerSwap): Promise<void>;
73
73
  onSwapCreate?(swap: SwapHandlerSwap): Promise<void>;
74
74
  onSwapRemove?(swap: SwapHandlerSwap): Promise<void>;
75
- onHandlePreFromBtcQuote?(swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV, request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>, requestedAmount: {
75
+ onHandlePreFromBtcQuote?(swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV | SwapHandlerType.FROM_BTCLN_AUTO, request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>, requestedAmount: {
76
76
  input: boolean;
77
77
  amount: bigint;
78
78
  token: string;
@@ -87,7 +87,7 @@ export interface IPlugin {
87
87
  amount: bigint;
88
88
  token: string;
89
89
  }): Promise<QuoteThrow | QuoteSetFees | QuoteAmountTooLow | QuoteAmountTooHigh>;
90
- onHandlePostFromBtcQuote?(swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV, request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>, requestedAmount: {
90
+ onHandlePostFromBtcQuote?(swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV | SwapHandlerType.FROM_BTCLN_AUTO, request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>, requestedAmount: {
91
91
  input: boolean;
92
92
  amount: bigint;
93
93
  token: string;
@@ -41,7 +41,7 @@ export declare class PluginManager {
41
41
  static swapStateChange(swap: SwapHandlerSwap, oldState?: any): Promise<void>;
42
42
  static swapCreate(swap: SwapHandlerSwap): Promise<void>;
43
43
  static swapRemove(swap: SwapHandlerSwap): Promise<void>;
44
- static onHandlePostFromBtcQuote(swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV, request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>, requestedAmount: {
44
+ static onHandlePostFromBtcQuote(swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV | SwapHandlerType.FROM_BTCLN_AUTO, request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>, requestedAmount: {
45
45
  input: boolean;
46
46
  amount: bigint;
47
47
  token: string;
@@ -58,7 +58,7 @@ export declare class PluginManager {
58
58
  token: string;
59
59
  pricePrefetch?: Promise<bigint>;
60
60
  }): Promise<QuoteThrow | QuoteSetFees | QuoteAmountTooLow | QuoteAmountTooHigh | PluginQuote>;
61
- static onHandlePreFromBtcQuote(swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV, request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>, requestedAmount: {
61
+ static onHandlePreFromBtcQuote(swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV | SwapHandlerType.FROM_BTCLN_AUTO, request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>, requestedAmount: {
62
62
  input: boolean;
63
63
  amount: bigint;
64
64
  token: string;
@@ -4,6 +4,7 @@ export declare class IntermediaryStorageManager<T extends StorageObject> impleme
4
4
  private readonly directory;
5
5
  private type;
6
6
  private data;
7
+ private logger;
7
8
  constructor(directory: string);
8
9
  init(): Promise<void>;
9
10
  query(params: StorageQueryParam[]): Promise<{
@@ -2,10 +2,13 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.IntermediaryStorageManager = void 0;
4
4
  const fs = require("fs/promises");
5
+ const fsSync = require("fs");
6
+ const Utils_1 = require("../utils/Utils");
5
7
  class IntermediaryStorageManager {
6
8
  constructor(directory) {
7
9
  this.data = {};
8
10
  this.directory = directory;
11
+ this.logger = (0, Utils_1.getLogger)("IntermediaryStorageManager(" + directory + "): ");
9
12
  }
10
13
  async init() {
11
14
  try {
@@ -79,17 +82,21 @@ class IntermediaryStorageManager {
79
82
  await fs.rm(this.directory + "/" + identifier + ".json");
80
83
  }
81
84
  catch (e) {
82
- console.error(e);
85
+ this.logger.error("removeData(): Error when removing data: ", e);
83
86
  }
84
87
  }
85
88
  async loadData(type) {
86
89
  this.type = type;
90
+ if (!fsSync.existsSync(this.directory)) {
91
+ this.logger.debug("loadData(): Data directory not found!");
92
+ return;
93
+ }
87
94
  let files;
88
95
  try {
89
96
  files = await fs.readdir(this.directory);
90
97
  }
91
98
  catch (e) {
92
- console.error(e);
99
+ this.logger.error("loadData(): Error when checking directory: ", e);
93
100
  return;
94
101
  }
95
102
  for (let file of files) {
@@ -4,6 +4,7 @@ export declare class StorageManager<T extends StorageObject> implements IStorage
4
4
  data: {
5
5
  [key: string]: T;
6
6
  };
7
+ private logger;
7
8
  constructor(directory: string);
8
9
  init(): Promise<void>;
9
10
  saveData(hash: string, object: T): Promise<void>;
@@ -2,10 +2,13 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.StorageManager = void 0;
4
4
  const fs = require("fs/promises");
5
+ const Utils_1 = require("../utils/Utils");
6
+ const fsSync = require("fs");
5
7
  class StorageManager {
6
8
  constructor(directory) {
7
9
  this.data = {};
8
10
  this.directory = directory;
11
+ this.logger = (0, Utils_1.getLogger)("StorageManager(" + directory + "): ");
9
12
  }
10
13
  async init() {
11
14
  try {
@@ -30,16 +33,20 @@ class StorageManager {
30
33
  await fs.rm(this.directory + "/" + paymentHash + ".json");
31
34
  }
32
35
  catch (e) {
33
- console.error(e);
36
+ this.logger.error("removeData(): Error when removing data: ", e);
34
37
  }
35
38
  }
36
39
  async loadData(type) {
40
+ if (!fsSync.existsSync(this.directory)) {
41
+ this.logger.debug("loadData(): Data directory not found!");
42
+ return;
43
+ }
37
44
  let files;
38
45
  try {
39
46
  files = await fs.readdir(this.directory);
40
47
  }
41
48
  catch (e) {
42
- console.error(e);
49
+ this.logger.error("loadData(): Error when checking directory: ", e);
43
50
  return [];
44
51
  }
45
52
  const arr = [];
@@ -4,6 +4,7 @@ import { ChainType } from "@atomiqlabs/base";
4
4
  import { SwapHandlerSwap } from "./SwapHandlerSwap";
5
5
  import { IIntermediaryStorage } from "../storage/IIntermediaryStorage";
6
6
  import { IParamReader } from "../utils/paramcoders/IParamReader";
7
+ import { LoggerType } from "../utils/Utils";
7
8
  export declare enum SwapHandlerType {
8
9
  TO_BTC = "TO_BTC",
9
10
  FROM_BTC = "FROM_BTC",
@@ -11,14 +12,14 @@ export declare enum SwapHandlerType {
11
12
  FROM_BTCLN = "FROM_BTCLN",
12
13
  FROM_BTCLN_TRUSTED = "FROM_BTCLN_TRUSTED",
13
14
  FROM_BTC_TRUSTED = "FROM_BTC_TRUSTED",
14
- FROM_BTC_SPV = "FROM_BTC_SPV"
15
+ FROM_BTC_SPV = "FROM_BTC_SPV",
16
+ FROM_BTCLN_AUTO = "FROM_BTCLN_AUTO"
15
17
  }
16
18
  export type SwapHandlerInfoType = {
17
19
  swapFeePPM: number;
18
20
  swapBaseFee: number;
19
21
  min: number;
20
22
  max: number;
21
- tokens: string[];
22
23
  chainTokens: {
23
24
  [chainId: string]: string[];
24
25
  };
@@ -41,7 +42,6 @@ export type MultichainData = {
41
42
  chains: {
42
43
  [identifier: string]: ChainData;
43
44
  };
44
- default: string;
45
45
  };
46
46
  export type ChainData<T extends ChainType = ChainType> = {
47
47
  signer: T["Signer"];
@@ -77,12 +77,7 @@ export declare abstract class SwapHandler<V extends SwapHandlerSwap<S> = SwapHan
77
77
  };
78
78
  readonly swapPricing: ISwapPrice;
79
79
  abstract config: SwapBaseConfig;
80
- logger: {
81
- debug: (msg: string, ...args: any) => void;
82
- info: (msg: string, ...args: any) => void;
83
- warn: (msg: string, ...args: any) => void;
84
- error: (msg: string, ...args: any) => void;
85
- };
80
+ logger: LoggerType;
86
81
  protected swapLogger: {
87
82
  debug: (swap: SwapHandlerSwap, msg: string, ...args: any) => void;
88
83
  info: (swap: SwapHandlerSwap, msg: string, ...args: any) => void;
@@ -90,7 +85,6 @@ export declare abstract class SwapHandler<V extends SwapHandlerSwap<S> = SwapHan
90
85
  error: (swap: SwapHandlerSwap, msg: string, ...args: any) => void;
91
86
  };
92
87
  protected constructor(storageDirectory: IIntermediaryStorage<V>, path: string, chainsData: MultichainData, swapPricing: ISwapPrice);
93
- protected getDefaultChain(): ChainData;
94
88
  protected getChain(identifier: string): ChainData;
95
89
  protected abstract processPastSwaps(): Promise<void>;
96
90
  /**
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SwapHandler = exports.SwapHandlerType = void 0;
4
4
  const PluginManager_1 = require("../plugins/PluginManager");
5
+ const Utils_1 = require("../utils/Utils");
5
6
  var SwapHandlerType;
6
7
  (function (SwapHandlerType) {
7
8
  SwapHandlerType["TO_BTC"] = "TO_BTC";
@@ -11,18 +12,14 @@ var SwapHandlerType;
11
12
  SwapHandlerType["FROM_BTCLN_TRUSTED"] = "FROM_BTCLN_TRUSTED";
12
13
  SwapHandlerType["FROM_BTC_TRUSTED"] = "FROM_BTC_TRUSTED";
13
14
  SwapHandlerType["FROM_BTC_SPV"] = "FROM_BTC_SPV";
15
+ SwapHandlerType["FROM_BTCLN_AUTO"] = "FROM_BTCLN_AUTO";
14
16
  })(SwapHandlerType = exports.SwapHandlerType || (exports.SwapHandlerType = {}));
15
17
  /**
16
18
  * An abstract class defining a singular swap service
17
19
  */
18
20
  class SwapHandler {
19
21
  constructor(storageDirectory, path, chainsData, swapPricing) {
20
- this.logger = {
21
- debug: (msg, ...args) => console.debug("SwapHandler(" + this.type + "): " + msg, ...args),
22
- info: (msg, ...args) => console.info("SwapHandler(" + this.type + "): " + msg, ...args),
23
- warn: (msg, ...args) => console.warn("SwapHandler(" + this.type + "): " + msg, ...args),
24
- error: (msg, ...args) => console.error("SwapHandler(" + this.type + "): " + msg, ...args)
25
- };
22
+ this.logger = (0, Utils_1.getLogger)(() => "SwapHandler(" + this.type + "): ");
26
23
  this.swapLogger = {
27
24
  debug: (swap, msg, ...args) => this.logger.debug(swap.getIdentifier() + ": " + msg, ...args),
28
25
  info: (swap, msg, ...args) => this.logger.info(swap.getIdentifier() + ": " + msg, ...args),
@@ -31,8 +28,6 @@ class SwapHandler {
31
28
  };
32
29
  this.storageManager = storageDirectory;
33
30
  this.chains = chainsData;
34
- if (this.chains.chains[this.chains.default] == null)
35
- throw new Error("Invalid default chain specified");
36
31
  this.path = path;
37
32
  this.swapPricing = swapPricing;
38
33
  this.allowedTokens = {};
@@ -40,9 +35,6 @@ class SwapHandler {
40
35
  this.allowedTokens[chainId] = new Set(chainsData.chains[chainId].allowedTokens);
41
36
  }
42
37
  }
43
- getDefaultChain() {
44
- return this.chains.chains[this.chains.default];
45
- }
46
38
  getChain(identifier) {
47
39
  if (this.chains.chains[identifier] == null)
48
40
  throw {
@@ -57,7 +49,7 @@ class SwapHandler {
57
49
  async startWatchdog() {
58
50
  let rerun;
59
51
  rerun = async () => {
60
- await this.processPastSwaps().catch(e => console.error(e));
52
+ await this.processPastSwaps().catch(e => this.logger.error("startWatchdog(): Error when processing past swaps: ", e));
61
53
  setTimeout(rerun, this.config.swapCheckInterval);
62
54
  };
63
55
  await rerun();
@@ -152,7 +144,6 @@ class SwapHandler {
152
144
  min: Number(this.config.min),
153
145
  max: Number(this.config.max),
154
146
  data: this.getInfoData(),
155
- tokens: Array.from(this.allowedTokens[this.chains.default]),
156
147
  chainTokens
157
148
  };
158
149
  }
@@ -23,7 +23,7 @@ export declare class FromBtcAmountAssertions extends AmountAssertions {
23
23
  * @param gasAmount
24
24
  * @throws {DefinedRuntimeError} will throw an error if the amount is outside minimum/maximum bounds
25
25
  */
26
- preCheckFromBtcAmounts(swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV, request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>, requestedAmount: {
26
+ preCheckFromBtcAmounts(swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV | SwapHandlerType.FROM_BTCLN_AUTO, request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>, requestedAmount: {
27
27
  input: boolean;
28
28
  amount: bigint;
29
29
  token: string;
@@ -48,7 +48,7 @@ export declare class FromBtcAmountAssertions extends AmountAssertions {
48
48
  * @param gasTokenAmount
49
49
  * @throws {DefinedRuntimeError} will throw an error if the amount is outside minimum/maximum bounds
50
50
  */
51
- checkFromBtcAmount(swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV, request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>, requestedAmount: {
51
+ checkFromBtcAmount(swapType: SwapHandlerType.FROM_BTCLN | SwapHandlerType.FROM_BTC | SwapHandlerType.FROM_BTCLN_TRUSTED | SwapHandlerType.FROM_BTC_TRUSTED | SwapHandlerType.FROM_BTC_SPV | SwapHandlerType.FROM_BTCLN_AUTO, request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType | FromBtcTrustedRequestType | SpvVaultSwapRequestType>, requestedAmount: {
52
52
  input: boolean;
53
53
  amount: bigint;
54
54
  token: string;
@@ -98,16 +98,25 @@ class FromBtcAmountAssertions extends AmountAssertions_1.AmountAssertions {
98
98
  }
99
99
  }
100
100
  let amountBDgas = 0n;
101
+ let gasSwapFee = 0n;
101
102
  if (gasTokenAmount != null) {
102
103
  amountBDgas = await this.swapPricing.getToBtcSwapAmount(gasTokenAmount.amount, gasTokenAmount.token, chainIdentifier, true, gasTokenAmount.pricePrefetch);
104
+ signal.throwIfAborted();
105
+ const denominator = (1000000n - fees.feePPM);
106
+ const _amountBDgas = (amountBDgas * 1000000n + denominator - 1n) / denominator;
107
+ gasSwapFee = _amountBDgas - amountBDgas;
108
+ amountBDgas = _amountBDgas;
103
109
  }
104
110
  let amountBD;
111
+ let swapFee;
105
112
  if (!requestedAmount.input) {
106
113
  amountBD = await this.swapPricing.getToBtcSwapAmount(requestedAmount.amount, requestedAmount.token, chainIdentifier, true, requestedAmount.pricePrefetch);
107
114
  signal.throwIfAborted();
108
115
  // amt = (amt+base_fee)/(1-fee)
109
- amountBD = (amountBD + fees.baseFee) * 1000000n / (1000000n - fees.feePPM);
110
- amountBDgas = amountBDgas * 1000000n / (1000000n - fees.feePPM);
116
+ const denominator = (1000000n - fees.feePPM);
117
+ const _amountBD = ((amountBD + fees.baseFee) * 1000000n + denominator - 1n) / denominator;
118
+ swapFee = _amountBD - amountBD;
119
+ amountBD = _amountBD;
111
120
  const tooLow = amountBD < (this.config.min * 95n / 100n);
112
121
  const tooHigh = amountBD > (this.config.max * 105n / 100n);
113
122
  if (tooLow || tooHigh) {
@@ -128,6 +137,7 @@ class FromBtcAmountAssertions extends AmountAssertions_1.AmountAssertions {
128
137
  else {
129
138
  this.checkBtcAmountInBounds(requestedAmount.amount);
130
139
  amountBD = requestedAmount.amount - amountBDgas;
140
+ swapFee = fees.baseFee + ((amountBD * fees.feePPM + 999999n) / 1000000n);
131
141
  if (amountBD < 0n) {
132
142
  throw {
133
143
  code: 20003,
@@ -139,10 +149,8 @@ class FromBtcAmountAssertions extends AmountAssertions_1.AmountAssertions {
139
149
  };
140
150
  }
141
151
  }
142
- const swapFee = fees.baseFee + (amountBD * fees.feePPM / 1000000n);
143
152
  const swapFeeInToken = await this.swapPricing.getFromBtcSwapAmount(swapFee, requestedAmount.token, chainIdentifier, true, requestedAmount.pricePrefetch);
144
153
  signal.throwIfAborted();
145
- const gasSwapFee = ((amountBDgas * fees.feePPM) + 999999n) / 1000000n;
146
154
  const gasSwapFeeInToken = gasTokenAmount == null ?
147
155
  0n :
148
156
  await this.swapPricing.getFromBtcSwapAmount(gasSwapFee, gasTokenAmount.token, chainIdentifier, true, gasTokenAmount.pricePrefetch);
@@ -152,7 +160,7 @@ class FromBtcAmountAssertions extends AmountAssertions_1.AmountAssertions {
152
160
  totalInToken = requestedAmount.amount;
153
161
  }
154
162
  else {
155
- totalInToken = await this.swapPricing.getFromBtcSwapAmount(amountBD - swapFee - gasSwapFee, requestedAmount.token, chainIdentifier, null, requestedAmount.pricePrefetch);
163
+ totalInToken = await this.swapPricing.getFromBtcSwapAmount(amountBD - swapFee, requestedAmount.token, chainIdentifier, null, requestedAmount.pricePrefetch);
156
164
  signal.throwIfAborted();
157
165
  }
158
166
  return {
@@ -41,13 +41,13 @@ class EscrowHandlerSwap extends SwapHandlerSwap_1.SwapHandlerSwap {
41
41
  * Returns the escrow hash - i.e. hash of the escrow data
42
42
  */
43
43
  getEscrowHash() {
44
- return this.data.getEscrowHash();
44
+ return this.data?.getEscrowHash();
45
45
  }
46
46
  /**
47
47
  * Returns the claim data hash - i.e. hash passed to the claim handler
48
48
  */
49
49
  getClaimHash() {
50
- return this.data.getClaimHash();
50
+ return this.data?.getClaimHash();
51
51
  }
52
52
  /**
53
53
  * Returns the identification hash of the swap, usually claim data hash, but can be overriden, e.g. for
@@ -44,8 +44,9 @@ export declare abstract class FromBtcBaseSwapHandler<V extends FromBtcBaseSwap<S
44
44
  * @param chainIdentifier
45
45
  * @param useToken
46
46
  * @param abortController
47
+ * @param inContract
47
48
  */
48
- protected getBalancePrefetch(chainIdentifier: string, useToken: string, abortController: AbortController): Promise<bigint>;
49
+ protected getBalancePrefetch(chainIdentifier: string, useToken: string, abortController: AbortController, inContract?: boolean): Promise<bigint>;
49
50
  /**
50
51
  * Checks if we have enough balance of the token in the swap vault
51
52
  *
@@ -53,12 +53,12 @@ class FromBtcBaseSwapHandler extends EscrowHandler_1.EscrowHandler {
53
53
  */
54
54
  async getBaseSecurityDepositPrefetch(chainIdentifier, dummySwapData, depositToken, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise, abortController) {
55
55
  //Solana workaround
56
- const { swapContract, chainInterface } = this.getChain(chainIdentifier);
56
+ const { swapContract, chainInterface, signer } = this.getChain(chainIdentifier);
57
57
  let feeResult;
58
58
  const gasToken = chainInterface.getNativeCurrencyAddress();
59
59
  if (swapContract.getRawRefundFee != null) {
60
60
  try {
61
- feeResult = await swapContract.getRawRefundFee(dummySwapData);
61
+ feeResult = await swapContract.getRawRefundFee(signer.getAddress(), dummySwapData);
62
62
  }
63
63
  catch (e) {
64
64
  this.logger.error("getBaseSecurityDepositPrefetch(): pre-fetch error: ", e);
@@ -68,7 +68,7 @@ class FromBtcBaseSwapHandler extends EscrowHandler_1.EscrowHandler {
68
68
  }
69
69
  else {
70
70
  try {
71
- feeResult = await swapContract.getRefundFee(dummySwapData);
71
+ feeResult = await swapContract.getRefundFee(signer.getAddress(), dummySwapData);
72
72
  }
73
73
  catch (e1) {
74
74
  this.logger.error("getBaseSecurityDepositPrefetch(): pre-fetch error: ", e1);
@@ -88,11 +88,12 @@ class FromBtcBaseSwapHandler extends EscrowHandler_1.EscrowHandler {
88
88
  * @param chainIdentifier
89
89
  * @param useToken
90
90
  * @param abortController
91
+ * @param inContract
91
92
  */
92
- async getBalancePrefetch(chainIdentifier, useToken, abortController) {
93
+ async getBalancePrefetch(chainIdentifier, useToken, abortController, inContract = true) {
93
94
  const { swapContract, signer } = this.getChain(chainIdentifier);
94
95
  try {
95
- return await swapContract.getBalance(signer.getAddress(), useToken, true);
96
+ return await swapContract.getBalance(signer.getAddress(), useToken, inContract);
96
97
  }
97
98
  catch (e) {
98
99
  this.logger.error("getBalancePrefetch(): balancePrefetch error: ", e);
@@ -109,6 +110,8 @@ class FromBtcBaseSwapHandler extends EscrowHandler_1.EscrowHandler {
109
110
  * @throws {DefinedRuntimeError} will throw an error if there are not enough funds in the vault
110
111
  */
111
112
  async checkBalance(totalInToken, balancePrefetch, signal) {
113
+ if (totalInToken === 0n)
114
+ return;
112
115
  const balance = await balancePrefetch;
113
116
  if (signal != null)
114
117
  signal.throwIfAborted();
@@ -178,7 +178,7 @@ class FromBtcAbs extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapHandler {
178
178
  restServer.use(this.path + "/getAddress", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
179
179
  restServer.post(this.path + "/getAddress", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
180
180
  const metadata = { request: {}, times: {} };
181
- const chainIdentifier = req.query.chain ?? this.chains.default;
181
+ const chainIdentifier = req.query.chain;
182
182
  const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
183
183
  const depositToken = req.query.depositToken ?? chainInterface.getNativeCurrencyAddress();
184
184
  this.checkAllowedDepositToken(chainIdentifier, depositToken);
@@ -202,7 +202,7 @@ class FromBtcAbs extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapHandler {
202
202
  const parsedBody = await req.paramReader.getParams({
203
203
  address: (val) => val != null &&
204
204
  typeof (val) === "string" &&
205
- chainInterface.isValidAddress(val) ? val : null,
205
+ chainInterface.isValidAddress(val, true) ? val : null,
206
206
  amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
207
207
  token: (val) => val != null &&
208
208
  typeof (val) === "string" &&
@@ -412,18 +412,16 @@ class FromBtcLnAbs extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapHandler {
412
412
  msg: "Invoice expired/canceled"
413
413
  };
414
414
  const arr = invoice.description.split("-");
415
- let chainIdentifier;
416
- let address;
417
- if (arr.length > 1) {
418
- chainIdentifier = arr[0];
419
- address = arr[1];
420
- }
421
- else {
422
- chainIdentifier = this.chains.default;
423
- address = invoice.description;
424
- }
415
+ if (arr.length < 2)
416
+ throw {
417
+ _httpStatus: 200,
418
+ code: 10001,
419
+ msg: "Invoice expired/canceled"
420
+ };
421
+ const chainIdentifier = arr[0];
422
+ const address = arr[1];
425
423
  const { chainInterface } = this.getChain(chainIdentifier);
426
- if (!chainInterface.isValidAddress(address))
424
+ if (!chainInterface.isValidAddress(address, true))
427
425
  throw {
428
426
  _httpStatus: 200,
429
427
  code: 10001,
@@ -456,7 +454,7 @@ class FromBtcLnAbs extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapHandler {
456
454
  restServer.use(this.path + "/createInvoice", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
457
455
  restServer.post(this.path + "/createInvoice", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
458
456
  const metadata = { request: {}, times: {} };
459
- const chainIdentifier = req.query.chain ?? this.chains.default;
457
+ const chainIdentifier = req.query.chain;
460
458
  const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
461
459
  const depositToken = req.query.depositToken ?? chainInterface.getNativeCurrencyAddress();
462
460
  this.checkAllowedDepositToken(chainIdentifier, depositToken);
@@ -475,7 +473,7 @@ class FromBtcLnAbs extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapHandler {
475
473
  const parsedBody = await req.paramReader.getParams({
476
474
  address: (val) => val != null &&
477
475
  typeof (val) === "string" &&
478
- chainInterface.isValidAddress(val) ? val : null,
476
+ chainInterface.isValidAddress(val, true) ? val : null,
479
477
  paymentHash: (val) => val != null &&
480
478
  typeof (val) === "string" &&
481
479
  val.length === 64 &&
@@ -24,6 +24,7 @@ export declare class FromBtcLnSwapAbs<T extends SwapData = SwapData> extends Fro
24
24
  serialize(): any;
25
25
  getToken(): string;
26
26
  getOutputAmount(): bigint;
27
+ getClaimHash(): string;
27
28
  getIdentifierHash(): string;
28
29
  getSequence(): bigint;
29
30
  isInitiated(): boolean;
@@ -69,6 +69,9 @@ class FromBtcLnSwapAbs extends FromBtcBaseSwap_1.FromBtcBaseSwap {
69
69
  getOutputAmount() {
70
70
  return this.totalTokens;
71
71
  }
72
+ getClaimHash() {
73
+ return this.claimHash;
74
+ }
72
75
  getIdentifierHash() {
73
76
  return this.lnPaymentHash;
74
77
  }
@@ -0,0 +1,111 @@
1
+ import { Express } from "express";
2
+ import { FromBtcLnAutoSwap, FromBtcLnAutoSwapState } from "./FromBtcLnAutoSwap";
3
+ import { MultichainData, SwapHandlerType } from "../../SwapHandler";
4
+ import { ISwapPrice } from "../../../prices/ISwapPrice";
5
+ import { ChainSwapType, ClaimEvent, InitializeEvent, RefundEvent, SwapData } from "@atomiqlabs/base";
6
+ import { IIntermediaryStorage } from "../../../storage/IIntermediaryStorage";
7
+ import { FromBtcBaseConfig, FromBtcBaseSwapHandler } from "../FromBtcBaseSwapHandler";
8
+ import { ILightningWallet } from "../../../wallets/ILightningWallet";
9
+ import { LightningAssertions } from "../../assertions/LightningAssertions";
10
+ export type FromBtcLnAutoConfig = FromBtcBaseConfig & {
11
+ invoiceTimeoutSeconds?: number;
12
+ minCltv: bigint;
13
+ gracePeriod: bigint;
14
+ gasTokenMax: {
15
+ [chainId: string]: bigint;
16
+ };
17
+ };
18
+ export type FromBtcLnAutoRequestType = {
19
+ address: string;
20
+ paymentHash: string;
21
+ amount: bigint;
22
+ token: string;
23
+ gasToken: string;
24
+ gasAmount: bigint;
25
+ claimerBounty: bigint;
26
+ descriptionHash?: string;
27
+ exactOut?: boolean;
28
+ };
29
+ /**
30
+ * Swap handler handling from BTCLN swaps using submarine swaps
31
+ */
32
+ export declare class FromBtcLnAuto extends FromBtcBaseSwapHandler<FromBtcLnAutoSwap, FromBtcLnAutoSwapState> {
33
+ readonly type = SwapHandlerType.FROM_BTCLN_AUTO;
34
+ readonly swapType = ChainSwapType.HTLC;
35
+ activeSubscriptions: Set<string>;
36
+ readonly config: FromBtcLnAutoConfig;
37
+ readonly lightning: ILightningWallet;
38
+ readonly LightningAssertions: LightningAssertions;
39
+ constructor(storageDirectory: IIntermediaryStorage<FromBtcLnAutoSwap>, path: string, chains: MultichainData, lightning: ILightningWallet, swapPricing: ISwapPrice, config: FromBtcLnAutoConfig);
40
+ protected processPastSwap(swap: FromBtcLnAutoSwap): Promise<"REFUND" | "SETTLE" | null>;
41
+ protected refundSwaps(refundSwaps: FromBtcLnAutoSwap[]): Promise<void>;
42
+ protected settleInvoices(swaps: FromBtcLnAutoSwap[]): Promise<void>;
43
+ /**
44
+ * Checks past swaps, refunds and deletes ones that are already expired.
45
+ */
46
+ protected processPastSwaps(): Promise<void>;
47
+ protected processInitializeEvent(chainIdentifier: string, savedSwap: FromBtcLnAutoSwap, event: InitializeEvent<SwapData>): Promise<void>;
48
+ protected processClaimEvent(chainIdentifier: string, savedSwap: FromBtcLnAutoSwap, event: ClaimEvent<SwapData>): Promise<void>;
49
+ protected processRefundEvent(chainIdentifier: string, savedSwap: FromBtcLnAutoSwap, event: RefundEvent<SwapData>): Promise<void>;
50
+ /**
51
+ * Subscribe to a lightning network invoice
52
+ *
53
+ * @param swap
54
+ */
55
+ private subscribeToInvoice;
56
+ /**
57
+ * Called when lightning HTLC is received, also signs an init transaction on the smart chain side, expiry of the
58
+ * smart chain authorization starts ticking as soon as this HTLC is received
59
+ *
60
+ * @param invoiceData
61
+ * @param invoice
62
+ */
63
+ private htlcReceived;
64
+ private offerHtlc;
65
+ /**
66
+ * Checks invoice description hash
67
+ *
68
+ * @param descriptionHash
69
+ * @throws {DefinedRuntimeError} will throw an error if the description hash is invalid
70
+ */
71
+ private checkDescriptionHash;
72
+ /**
73
+ * Asynchronously sends the LN node's public key to the client, so he can pre-fetch the node's channels from 1ml api
74
+ *
75
+ * @param responseStream
76
+ */
77
+ private sendPublicKeyAsync;
78
+ /**
79
+ * Returns the CLTV timeout (blockheight) of the received HTLC corresponding to the invoice. If multiple HTLCs are
80
+ * received (MPP) it returns the lowest of the timeouts
81
+ *
82
+ * @param invoice
83
+ */
84
+ private getInvoicePaymentsTimeout;
85
+ /**
86
+ * Checks if the received HTLC's CLTV timeout is large enough to still process the swap
87
+ *
88
+ * @param invoice
89
+ * @throws {DefinedRuntimeError} Will throw if HTLC expires too soon and therefore cannot be processed
90
+ * @returns expiry timeout in seconds
91
+ */
92
+ private checkHtlcExpiry;
93
+ /**
94
+ * Cancels the swap (CANCELED state) & also cancels the LN invoice (including all pending HTLCs)
95
+ *
96
+ * @param invoiceData
97
+ */
98
+ private cancelSwapAndInvoice;
99
+ /**
100
+ *
101
+ * Checks if the lightning invoice is in HELD state (htlcs received but yet unclaimed)
102
+ *
103
+ * @param paymentHash
104
+ * @throws {DefinedRuntimeError} Will throw if the lightning invoice is not found, or if it isn't in the HELD state
105
+ * @returns the fetched lightning invoice
106
+ */
107
+ private checkInvoiceStatus;
108
+ startRestServer(restServer: Express): void;
109
+ init(): Promise<void>;
110
+ getInfoData(): any;
111
+ }