@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,13 +1,4 @@
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.FromBtcLnBaseSwapHandler = void 0;
13
4
  const FromBtcBaseSwapHandler_1 = require("./FromBtcBaseSwapHandler");
@@ -24,22 +15,20 @@ class FromBtcLnBaseSwapHandler extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapH
24
15
  * @param signal
25
16
  * @throws {DefinedRuntimeError} will throw an error if there isn't enough inbound liquidity to receive the LN payment
26
17
  */
27
- checkInboundLiquidity(amountBD, channelsPrefetch, signal) {
28
- return __awaiter(this, void 0, void 0, function* () {
29
- const channelsResponse = yield channelsPrefetch;
30
- signal.throwIfAborted();
31
- let hasEnoughInboundLiquidity = false;
32
- channelsResponse.forEach(channel => {
33
- if (channel.remoteBalance.gte(amountBD))
34
- hasEnoughInboundLiquidity = true;
35
- });
36
- if (!hasEnoughInboundLiquidity) {
37
- throw {
38
- code: 20050,
39
- msg: "Not enough LN inbound liquidity"
40
- };
41
- }
18
+ async checkInboundLiquidity(amountBD, channelsPrefetch, signal) {
19
+ const channelsResponse = await channelsPrefetch;
20
+ signal.throwIfAborted();
21
+ let hasEnoughInboundLiquidity = false;
22
+ channelsResponse.forEach(channel => {
23
+ if (channel.remoteBalance >= amountBD)
24
+ hasEnoughInboundLiquidity = true;
42
25
  });
26
+ if (!hasEnoughInboundLiquidity) {
27
+ throw {
28
+ code: 20050,
29
+ msg: "Not enough LN inbound liquidity"
30
+ };
31
+ }
43
32
  }
44
33
  /**
45
34
  * Starts LN channels pre-fetch
@@ -1,4 +1,3 @@
1
- import * as BN from "bn.js";
2
1
  export type ISwapPriceCoinsMap<T extends {
3
2
  decimals: number;
4
3
  }> = {
@@ -18,9 +17,9 @@ export declare abstract class ISwapPrice<T extends {
18
17
  *
19
18
  * @param tokenData
20
19
  */
21
- protected abstract getPrice(tokenData: T): Promise<BN>;
20
+ protected abstract getPrice(tokenData: T): Promise<bigint>;
22
21
  getTokenData(tokenAddress: string, chainId: string): T;
23
- preFetchPrice(token: string, chainId: string): Promise<BN>;
22
+ preFetchPrice(token: string, chainId: string): Promise<bigint>;
24
23
  /**
25
24
  * Returns amount of satoshis that are equivalent to {fromAmount} of {fromToken}
26
25
  *
@@ -30,7 +29,7 @@ export declare abstract class ISwapPrice<T extends {
30
29
  * @param roundUp Whether result should be rounded up
31
30
  * @param preFetch Price pre-fetch promise returned from preFetchPrice()
32
31
  */
33
- getToBtcSwapAmount(fromAmount: BN, fromToken: string, tokenChainIdentification: string, roundUp?: boolean, preFetch?: Promise<BN>): Promise<BN>;
32
+ getToBtcSwapAmount(fromAmount: bigint, fromToken: string, tokenChainIdentification: string, roundUp?: boolean, preFetch?: Promise<bigint>): Promise<bigint>;
34
33
  /**
35
34
  * Returns amount of {toToken} that are equivalent to {fromAmount} satoshis
36
35
  *
@@ -40,5 +39,5 @@ export declare abstract class ISwapPrice<T extends {
40
39
  * @param roundUp Whether result should be rounded up
41
40
  * @param preFetch Price pre-fetch promise returned from preFetchPrice()
42
41
  */
43
- getFromBtcSwapAmount(fromAmount: BN, toToken: string, tokenChainIdentification: string, roundUp?: boolean, preFetch?: Promise<BN>): Promise<BN>;
42
+ getFromBtcSwapAmount(fromAmount: bigint, toToken: string, tokenChainIdentification: string, roundUp?: boolean, preFetch?: Promise<bigint>): Promise<bigint>;
44
43
  }
@@ -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.ISwapPrice = void 0;
13
- const BN = require("bn.js");
14
4
  class ISwapPrice {
15
5
  constructor(coinsMap) {
16
6
  this.coinsMap = coinsMap;
@@ -38,16 +28,10 @@ class ISwapPrice {
38
28
  * @param roundUp Whether result should be rounded up
39
29
  * @param preFetch Price pre-fetch promise returned from preFetchPrice()
40
30
  */
41
- getToBtcSwapAmount(fromAmount, fromToken, tokenChainIdentification, roundUp, preFetch) {
42
- return __awaiter(this, void 0, void 0, function* () {
43
- const coin = this.getTokenData(fromToken, tokenChainIdentification);
44
- const price = (preFetch == null ? null : yield preFetch) || (yield this.getPrice(coin));
45
- return fromAmount
46
- .mul(price)
47
- .div(new BN(10).pow(new BN(coin.decimals)))
48
- .add(roundUp ? new BN(999999) : new BN(0))
49
- .div(new BN(1000000));
50
- });
31
+ async getToBtcSwapAmount(fromAmount, fromToken, tokenChainIdentification, roundUp, preFetch) {
32
+ const coin = this.getTokenData(fromToken, tokenChainIdentification);
33
+ const price = (preFetch == null ? null : await preFetch) || await this.getPrice(coin);
34
+ return ((fromAmount * price * (10n ** BigInt(coin.decimals))) + (roundUp ? 999999n : 0n)) / 1000000n;
51
35
  }
52
36
  /**
53
37
  * Returns amount of {toToken} that are equivalent to {fromAmount} satoshis
@@ -58,16 +42,10 @@ class ISwapPrice {
58
42
  * @param roundUp Whether result should be rounded up
59
43
  * @param preFetch Price pre-fetch promise returned from preFetchPrice()
60
44
  */
61
- getFromBtcSwapAmount(fromAmount, toToken, tokenChainIdentification, roundUp, preFetch) {
62
- return __awaiter(this, void 0, void 0, function* () {
63
- const coin = this.getTokenData(toToken, tokenChainIdentification);
64
- const price = (preFetch == null ? null : yield preFetch) || (yield this.getPrice(coin));
65
- return fromAmount
66
- .mul(new BN(10).pow(new BN(coin.decimals)))
67
- .mul(new BN(1000000)) //To usat
68
- .add(roundUp ? price.sub(new BN(1)) : new BN(0))
69
- .div(price);
70
- });
45
+ async getFromBtcSwapAmount(fromAmount, toToken, tokenChainIdentification, roundUp, preFetch) {
46
+ const coin = this.getTokenData(toToken, tokenChainIdentification);
47
+ const price = (preFetch == null ? null : await preFetch) || await this.getPrice(coin);
48
+ return ((fromAmount * (10n ** BigInt(coin.decimals)) * 1000000n) + (roundUp ? price - 1n : 0n)) / price;
71
49
  }
72
50
  }
73
51
  exports.ISwapPrice = ISwapPrice;
@@ -1,9 +1,8 @@
1
1
  import { Express, Request } from "express";
2
2
  import { ISwapPrice } from "./ISwapPrice";
3
- import { ChainType, ClaimEvent, InitializeEvent, RefundEvent, SwapData, SwapEvent } from "@atomiqlabs/base";
3
+ import { ChainSwapType, ChainType, ClaimEvent, InitializeEvent, RefundEvent, SwapData, SwapEvent } from "@atomiqlabs/base";
4
4
  import { SwapHandlerSwap } from "./SwapHandlerSwap";
5
5
  import { IIntermediaryStorage } from "../storage/IIntermediaryStorage";
6
- import * as BN from "bn.js";
7
6
  import { ServerParamEncoder } from "../utils/paramcoders/server/ServerParamEncoder";
8
7
  import { IParamReader } from "../utils/paramcoders/IParamReader";
9
8
  export declare enum SwapHandlerType {
@@ -26,13 +25,16 @@ export type SwapHandlerInfoType = {
26
25
  data?: any;
27
26
  };
28
27
  export type SwapBaseConfig = {
29
- authorizationTimeout: number;
30
- bitcoinBlocktime: BN;
31
- baseFee: BN;
32
- feePPM: BN;
33
- max: BN;
34
- min: BN;
35
- safetyFactor: BN;
28
+ initAuthorizationTimeout: number;
29
+ initAuthorizationTimeouts?: {
30
+ [chainId: string]: number;
31
+ };
32
+ bitcoinBlocktime: bigint;
33
+ baseFee: bigint;
34
+ feePPM: bigint;
35
+ max: bigint;
36
+ min: bigint;
37
+ safetyFactor: bigint;
36
38
  swapCheckInterval: number;
37
39
  };
38
40
  export type MultichainData = {
@@ -46,6 +48,7 @@ export type ChainData<T extends ChainType = ChainType> = {
46
48
  swapContract: T["Contract"];
47
49
  chainEvents: T["Events"];
48
50
  allowedTokens: string[];
51
+ allowedDepositTokens?: string[];
49
52
  btcRelay?: T["BtcRelay"];
50
53
  };
51
54
  export type RequestData<T> = {
@@ -61,7 +64,9 @@ export type RequestData<T> = {
61
64
  */
62
65
  export declare abstract class SwapHandler<V extends SwapHandlerSwap<SwapData, S> = SwapHandlerSwap, S = any> {
63
66
  abstract readonly type: SwapHandlerType;
67
+ abstract readonly swapType: ChainSwapType;
64
68
  readonly storageManager: IIntermediaryStorage<V>;
69
+ readonly escrowHashMap: Map<string, V>;
65
70
  readonly path: string;
66
71
  readonly chains: MultichainData;
67
72
  readonly allowedTokens: {
@@ -89,9 +94,9 @@ export declare abstract class SwapHandler<V extends SwapHandlerSwap<SwapData, S>
89
94
  * Starts the watchdog checking past swaps for expiry or claim eligibility.
90
95
  */
91
96
  startWatchdog(): Promise<void>;
92
- protected abstract processInitializeEvent(chainIdentifier: string, event: InitializeEvent<SwapData>): Promise<void>;
93
- protected abstract processClaimEvent(chainIdentifier: string, event: ClaimEvent<SwapData>): Promise<void>;
94
- protected abstract processRefundEvent(chainIdentifier: string, event: RefundEvent<SwapData>): Promise<void>;
97
+ protected abstract processInitializeEvent?(chainIdentifier: string, swap: V, event: InitializeEvent<SwapData>): Promise<void>;
98
+ protected abstract processClaimEvent?(chainIdentifier: string, swap: V, event: ClaimEvent<SwapData>): Promise<void>;
99
+ protected abstract processRefundEvent?(chainIdentifier: string, swap: V, event: RefundEvent<SwapData>): Promise<void>;
95
100
  /**
96
101
  * Chain event processor
97
102
  *
@@ -107,6 +112,7 @@ export declare abstract class SwapHandler<V extends SwapHandlerSwap<SwapData, S>
107
112
  * Initializes swap handler, loads data and subscribes to chain events
108
113
  */
109
114
  abstract init(): Promise<void>;
115
+ protected loadData(ctor: new (data: any) => V): Promise<void>;
110
116
  /**
111
117
  * Sets up required listeners for the REST server
112
118
  *
@@ -123,7 +129,7 @@ export declare abstract class SwapHandler<V extends SwapHandlerSwap<SwapData, S>
123
129
  * @param hash
124
130
  * @param sequence
125
131
  */
126
- protected removeSwapData(hash: string, sequence: BN): Promise<void>;
132
+ protected removeSwapData(hash: string, sequence: bigint): Promise<void>;
127
133
  /**
128
134
  * Remove swap data
129
135
  *
@@ -131,6 +137,10 @@ export declare abstract class SwapHandler<V extends SwapHandlerSwap<SwapData, S>
131
137
  * @param ultimateState set the ultimate state of the swap before removing
132
138
  */
133
139
  protected removeSwapData(swap: V, ultimateState?: S): Promise<void>;
140
+ protected saveSwapData(swap: V): Promise<void>;
141
+ protected saveSwapToEscrowHashMap(swap: V): void;
142
+ protected removeSwapFromEscrowHashMap(swap: V): void;
143
+ protected getSwapByEscrowHash(chainIdentifier: string, escrowHash: string): V;
134
144
  /**
135
145
  * Checks whether the bitcoin amount is within specified min/max bounds
136
146
  *
@@ -138,7 +148,7 @@ export declare abstract class SwapHandler<V extends SwapHandlerSwap<SwapData, S>
138
148
  * @protected
139
149
  * @throws {DefinedRuntimeError} will throw an error if the amount is outside minimum/maximum bounds
140
150
  */
141
- protected checkBtcAmountInBounds(amount: BN): void;
151
+ protected checkBtcAmountInBounds(amount: bigint): void;
142
152
  /**
143
153
  * Handles and throws plugin errors
144
154
  *
@@ -170,7 +180,7 @@ export declare abstract class SwapHandler<V extends SwapHandlerSwap<SwapData, S>
170
180
  * @param sequence
171
181
  * @throws {DefinedRuntimeError} will throw an error if sequence number is out of bounds
172
182
  */
173
- protected checkSequence(sequence: BN): void;
183
+ protected checkSequence(sequence: bigint): void;
174
184
  /**
175
185
  * Checks whether a given token is supported on a specified chain
176
186
  *
@@ -180,4 +190,5 @@ export declare abstract class SwapHandler<V extends SwapHandlerSwap<SwapData, S>
180
190
  */
181
191
  protected isTokenSupported(chainId: string, token: string): boolean;
182
192
  getInfo(): SwapHandlerInfoType;
193
+ protected getInitAuthorizationTimeout(chainIdentifier: string): number;
183
194
  }
@@ -1,19 +1,9 @@
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.SwapHandler = exports.SwapHandlerType = void 0;
13
4
  const base_1 = require("@atomiqlabs/base");
14
5
  const SwapHandlerSwap_1 = require("./SwapHandlerSwap");
15
6
  const PluginManager_1 = require("../plugins/PluginManager");
16
- const BN = require("bn.js");
17
7
  const IPlugin_1 = require("../plugins/IPlugin");
18
8
  var SwapHandlerType;
19
9
  (function (SwapHandlerType) {
@@ -29,6 +19,7 @@ var SwapHandlerType;
29
19
  */
30
20
  class SwapHandler {
31
21
  constructor(storageDirectory, path, chainsData, swapPricing) {
22
+ this.escrowHashMap = new Map();
32
23
  this.logger = {
33
24
  debug: (msg, ...args) => console.debug("SwapHandler(" + this.type + "): " + msg, ...args),
34
25
  info: (msg, ...args) => console.info("SwapHandler(" + this.type + "): " + msg, ...args),
@@ -66,15 +57,13 @@ class SwapHandler {
66
57
  /**
67
58
  * Starts the watchdog checking past swaps for expiry or claim eligibility.
68
59
  */
69
- startWatchdog() {
70
- return __awaiter(this, void 0, void 0, function* () {
71
- let rerun;
72
- rerun = () => __awaiter(this, void 0, void 0, function* () {
73
- yield this.processPastSwaps().catch(e => console.error(e));
74
- setTimeout(rerun, this.config.swapCheckInterval);
75
- });
76
- yield rerun();
77
- });
60
+ async startWatchdog() {
61
+ let rerun;
62
+ rerun = async () => {
63
+ await this.processPastSwaps().catch(e => console.error(e));
64
+ setTimeout(rerun, this.config.swapCheckInterval);
65
+ };
66
+ await rerun();
78
67
  }
79
68
  /**
80
69
  * Chain event processor
@@ -82,24 +71,41 @@ class SwapHandler {
82
71
  * @param chainIdentifier
83
72
  * @param eventData
84
73
  */
85
- processEvent(chainIdentifier, eventData) {
86
- return __awaiter(this, void 0, void 0, function* () {
87
- for (let event of eventData) {
88
- if (event instanceof base_1.InitializeEvent) {
89
- // this.swapLogger.debug(event, "SC: InitializeEvent: swap type: "+event.swapType);
90
- yield this.processInitializeEvent(chainIdentifier, event);
91
- }
92
- else if (event instanceof base_1.ClaimEvent) {
93
- // this.swapLogger.debug(event, "SC: ClaimEvent: swap secret: "+event.secret);
94
- yield this.processClaimEvent(chainIdentifier, event);
95
- }
96
- else if (event instanceof base_1.RefundEvent) {
97
- // this.swapLogger.debug(event, "SC: RefundEvent");
98
- yield this.processRefundEvent(chainIdentifier, event);
99
- }
100
- }
74
+ async processEvent(chainIdentifier, eventData) {
75
+ if (this.swapType == null)
101
76
  return true;
102
- });
77
+ for (let event of eventData) {
78
+ if (event instanceof base_1.InitializeEvent) {
79
+ if (event.swapType !== this.swapType)
80
+ continue;
81
+ const swap = this.getSwapByEscrowHash(chainIdentifier, event.escrowHash);
82
+ if (swap == null)
83
+ continue;
84
+ swap.txIds.init = event.meta?.txId;
85
+ if (swap.metadata != null)
86
+ swap.metadata.times.initTxReceived = Date.now();
87
+ await this.processInitializeEvent(chainIdentifier, swap, event);
88
+ }
89
+ else if (event instanceof base_1.ClaimEvent) {
90
+ const swap = this.getSwapByEscrowHash(chainIdentifier, event.escrowHash);
91
+ if (swap == null)
92
+ continue;
93
+ swap.txIds.claim = event.meta?.txId;
94
+ if (swap.metadata != null)
95
+ swap.metadata.times.claimTxReceived = Date.now();
96
+ await this.processClaimEvent(chainIdentifier, swap, event);
97
+ }
98
+ else if (event instanceof base_1.RefundEvent) {
99
+ const swap = this.getSwapByEscrowHash(chainIdentifier, event.escrowHash);
100
+ if (swap == null)
101
+ continue;
102
+ swap.txIds.refund = event.meta?.txId;
103
+ if (swap.metadata != null)
104
+ swap.metadata.times.refundTxReceived = Date.now();
105
+ await this.processRefundEvent(chainIdentifier, swap, event);
106
+ }
107
+ }
108
+ return true;
103
109
  }
104
110
  /**
105
111
  * Initializes chain events subscription
@@ -110,24 +116,52 @@ class SwapHandler {
110
116
  }
111
117
  this.logger.info("SC: Events: subscribed to smartchain events");
112
118
  }
113
- removeSwapData(hashOrSwap, sequenceOrUltimateState) {
114
- return __awaiter(this, void 0, void 0, function* () {
115
- let swap;
116
- if (typeof (hashOrSwap) === "string") {
117
- if (!BN.isBN(sequenceOrUltimateState))
118
- throw new Error("Sequence must be a BN instance!");
119
- swap = yield this.storageManager.getData(hashOrSwap, sequenceOrUltimateState);
120
- }
121
- else {
122
- swap = hashOrSwap;
123
- if (sequenceOrUltimateState != null && !BN.isBN(sequenceOrUltimateState))
124
- yield swap.setState(sequenceOrUltimateState);
119
+ async loadData(ctor) {
120
+ await this.storageManager.loadData(ctor);
121
+ //Check if all swaps contain a valid amount
122
+ for (let { obj: swap, hash, sequence } of await this.storageManager.query([])) {
123
+ if (hash !== swap.getIdentifierHash() || sequence !== (swap.getSequence() ?? 0n)) {
124
+ this.swapLogger.info(swap, "loadData(): Swap storage key or sequence mismatch, fixing," +
125
+ " old hash: " + hash + " new hash: " + swap.getIdentifierHash() +
126
+ " old seq: " + sequence.toString(10) + " new seq: " + (swap.getSequence() ?? 0n).toString(10));
127
+ await this.storageManager.removeData(hash, sequence);
128
+ await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
125
129
  }
126
- if (swap != null)
127
- yield PluginManager_1.PluginManager.swapRemove(swap);
128
- this.swapLogger.debug(swap, "removeSwapData(): removing swap final state: " + swap.state);
129
- yield this.storageManager.removeData(swap.getHash(), swap.getSequence());
130
- });
130
+ this.saveSwapToEscrowHashMap(swap);
131
+ }
132
+ }
133
+ async removeSwapData(hashOrSwap, sequenceOrUltimateState) {
134
+ let swap;
135
+ if (typeof (hashOrSwap) === "string") {
136
+ if (typeof (sequenceOrUltimateState) !== "bigint")
137
+ throw new Error("Sequence must be a BN instance!");
138
+ swap = await this.storageManager.getData(hashOrSwap, sequenceOrUltimateState);
139
+ }
140
+ else {
141
+ swap = hashOrSwap;
142
+ if (sequenceOrUltimateState != null && typeof (sequenceOrUltimateState) !== "bigint")
143
+ await swap.setState(sequenceOrUltimateState);
144
+ }
145
+ if (swap != null)
146
+ await PluginManager_1.PluginManager.swapRemove(swap);
147
+ this.swapLogger.debug(swap, "removeSwapData(): removing swap final state: " + swap.state);
148
+ this.removeSwapFromEscrowHashMap(swap);
149
+ await this.storageManager.removeData(swap.getIdentifierHash(), swap.getSequence());
150
+ }
151
+ async saveSwapData(swap) {
152
+ this.saveSwapToEscrowHashMap(swap);
153
+ await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
154
+ }
155
+ saveSwapToEscrowHashMap(swap) {
156
+ if (swap.data != null)
157
+ this.escrowHashMap.set(swap.chainIdentifier + "_" + swap.getEscrowHash(), swap);
158
+ }
159
+ removeSwapFromEscrowHashMap(swap) {
160
+ if (swap.data != null)
161
+ this.escrowHashMap.delete(swap.chainIdentifier + "_" + swap.data.getEscrowHash());
162
+ }
163
+ getSwapByEscrowHash(chainIdentifier, escrowHash) {
164
+ return this.escrowHashMap.get(chainIdentifier + "_" + escrowHash);
131
165
  }
132
166
  /**
133
167
  * Checks whether the bitcoin amount is within specified min/max bounds
@@ -137,7 +171,7 @@ class SwapHandler {
137
171
  * @throws {DefinedRuntimeError} will throw an error if the amount is outside minimum/maximum bounds
138
172
  */
139
173
  checkBtcAmountInBounds(amount) {
140
- if (amount.lt(this.config.min)) {
174
+ if (amount < this.config.min) {
141
175
  throw {
142
176
  code: 20003,
143
177
  msg: "Amount too low!",
@@ -147,7 +181,7 @@ class SwapHandler {
147
181
  }
148
182
  };
149
183
  }
150
- if (amount.gt(this.config.max)) {
184
+ if (amount > this.config.max) {
151
185
  throw {
152
186
  code: 20004,
153
187
  msg: "Amount too high!",
@@ -197,6 +231,8 @@ class SwapHandler {
197
231
  */
198
232
  getAbortController(responseStream) {
199
233
  const abortController = new AbortController();
234
+ if (responseStream == null || responseStream.getAbortSignal == null)
235
+ return abortController;
200
236
  const responseStreamAbortController = responseStream.getAbortSignal();
201
237
  responseStreamAbortController.addEventListener("abort", () => abortController.abort(responseStreamAbortController.reason));
202
238
  return abortController;
@@ -227,14 +263,16 @@ class SwapHandler {
227
263
  return signDataPrefetchPromise;
228
264
  }
229
265
  getIdentifierFromEvent(event) {
230
- if (event.sequence.isZero())
231
- return event.paymentHash;
232
- return event.paymentHash + "_" + event.sequence.toString(16);
266
+ const foundSwap = this.escrowHashMap.get(event.escrowHash);
267
+ if (foundSwap != null) {
268
+ return foundSwap.getIdentifier();
269
+ }
270
+ return "UNKNOWN_" + event.escrowHash;
233
271
  }
234
272
  getIdentifierFromSwapData(swapData) {
235
- if (swapData.getSequence().isZero())
236
- return swapData.getHash();
237
- return swapData.getHash() + "_" + swapData.getSequence().toString(16);
273
+ if (swapData.getSequence == null)
274
+ return swapData.getClaimHash();
275
+ return swapData.getClaimHash() + "_" + swapData.getSequence().toString(16);
238
276
  }
239
277
  getIdentifier(swap) {
240
278
  if (swap instanceof SwapHandlerSwap_1.SwapHandlerSwap) {
@@ -252,7 +290,7 @@ class SwapHandler {
252
290
  * @throws {DefinedRuntimeError} will throw an error if sequence number is out of bounds
253
291
  */
254
292
  checkSequence(sequence) {
255
- if (sequence.isNeg() || sequence.gte(new BN(2).pow(new BN(64)))) {
293
+ if (sequence < 0n || sequence >= 2n ** 64n) {
256
294
  throw {
257
295
  code: 20060,
258
296
  msg: "Invalid sequence"
@@ -278,14 +316,17 @@ class SwapHandler {
278
316
  chainTokens[chainId] = Array.from(this.allowedTokens[chainId]);
279
317
  }
280
318
  return {
281
- swapFeePPM: this.config.feePPM.toNumber(),
282
- swapBaseFee: this.config.baseFee.toNumber(),
283
- min: this.config.min.toNumber(),
284
- max: this.config.max.toNumber(),
319
+ swapFeePPM: Number(this.config.feePPM),
320
+ swapBaseFee: Number(this.config.baseFee),
321
+ min: Number(this.config.min),
322
+ max: Number(this.config.max),
285
323
  data: this.getInfoData(),
286
324
  tokens: Array.from(this.allowedTokens[this.chains.default]),
287
325
  chainTokens
288
326
  };
289
327
  }
328
+ getInitAuthorizationTimeout(chainIdentifier) {
329
+ return this.config.initAuthorizationTimeouts?.[chainIdentifier] ?? this.config.initAuthorizationTimeout;
330
+ }
290
331
  }
291
332
  exports.SwapHandler = SwapHandler;
@@ -1,6 +1,5 @@
1
1
  import { Lockable, StorageObject, SwapData } from "@atomiqlabs/base";
2
2
  import { SwapHandlerType } from "./SwapHandler";
3
- import * as BN from "bn.js";
4
3
  export declare abstract class SwapHandlerSwap<T extends SwapData = SwapData, S = any> extends Lockable implements StorageObject {
5
4
  chainIdentifier: string;
6
5
  state: S;
@@ -18,13 +17,13 @@ export declare abstract class SwapHandlerSwap<T extends SwapData = SwapData, S =
18
17
  claim?: string;
19
18
  refund?: string;
20
19
  };
21
- readonly swapFee: BN;
22
- readonly swapFeeInToken: BN;
20
+ readonly swapFee: bigint;
21
+ readonly swapFeeInToken: bigint;
23
22
  prefix: string;
24
23
  timeout: string;
25
24
  signature: string;
26
25
  feeRate: string;
27
- protected constructor(chainIdentifier: string, swapFee: BN, swapFeeInToken: BN);
26
+ protected constructor(chainIdentifier: string, swapFee: bigint, swapFeeInToken: bigint);
28
27
  protected constructor(obj: any);
29
28
  serialize(): any;
30
29
  /**
@@ -33,8 +32,20 @@ export declare abstract class SwapHandlerSwap<T extends SwapData = SwapData, S =
33
32
  * @param newState
34
33
  */
35
34
  setState(newState: S): Promise<void>;
36
- getHash(): string;
37
- getSequence(): BN;
35
+ /**
36
+ * Returns the escrow hash - i.e. hash of the escrow data
37
+ */
38
+ getEscrowHash(): string;
39
+ /**
40
+ * Returns the claim data hash - i.e. hash passed to the claim handler
41
+ */
42
+ getClaimHash(): string;
43
+ /**
44
+ * Returns the identification hash of the swap, usually claim data hash, but can be overriden, e.g. for
45
+ * lightning swaps the identifier hash is used instead of claim data hash
46
+ */
47
+ getIdentifierHash(): string;
48
+ getSequence(): bigint | null;
38
49
  /**
39
50
  * Returns unique identifier of the swap in the form <hash>_<sequence> or just <hash> if the swap type doesn't
40
51
  * use sequence number
@@ -59,21 +70,21 @@ export declare abstract class SwapHandlerSwap<T extends SwapData = SwapData, S =
59
70
  /**
60
71
  * Returns the input amount paid by the user (excluding fees)
61
72
  */
62
- abstract getInputAmount(): BN;
73
+ abstract getInputAmount(): bigint;
63
74
  /**
64
75
  * Returns the total input amount paid by the user (including all fees)
65
76
  */
66
- abstract getTotalInputAmount(): BN;
77
+ abstract getTotalInputAmount(): bigint;
67
78
  /**
68
79
  * Returns the actual output amount paid out to the user
69
80
  */
70
- abstract getOutputAmount(): BN;
81
+ abstract getOutputAmount(): bigint;
71
82
  /**
72
83
  * Returns swap fee, denominated in input & output tokens (the fee is paid only once, it is just represented here in
73
84
  * both denomination for ease of use)
74
85
  */
75
86
  abstract getSwapFee(): {
76
- inInputToken: BN;
77
- inOutputToken: BN;
87
+ inInputToken: bigint;
88
+ inOutputToken: bigint;
78
89
  };
79
90
  }
@@ -3,13 +3,21 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SwapHandlerSwap = void 0;
4
4
  const base_1 = require("@atomiqlabs/base");
5
5
  const PluginManager_1 = require("../plugins/PluginManager");
6
- const BN = require("bn.js");
7
6
  const Utils_1 = require("../utils/Utils");
7
+ function objectBigIntsToString(obj) {
8
+ for (let key in obj) {
9
+ if (typeof obj[key] === "bigint")
10
+ obj[key] = obj[key].toString(10);
11
+ if (typeof obj[key] === "object")
12
+ objectBigIntsToString(obj[key]);
13
+ }
14
+ return obj;
15
+ }
8
16
  class SwapHandlerSwap extends base_1.Lockable {
9
17
  constructor(obj, swapFee, swapFeeInToken) {
10
18
  super();
11
19
  this.txIds = {};
12
- if (typeof (obj) === "string" && BN.isBN(swapFee) && BN.isBN(swapFeeInToken)) {
20
+ if (typeof (obj) === "string" && typeof (swapFee) === "bigint" && typeof (swapFeeInToken) === "bigint") {
13
21
  this.chainIdentifier = obj;
14
22
  this.swapFee = swapFee;
15
23
  this.swapFeeInToken = swapFeeInToken;
@@ -34,7 +42,7 @@ class SwapHandlerSwap extends base_1.Lockable {
34
42
  state: this.state,
35
43
  data: this.data == null ? null : this.data.serialize(),
36
44
  chainIdentifier: this.chainIdentifier,
37
- metadata: this.metadata,
45
+ metadata: objectBigIntsToString(this.metadata),
38
46
  txIds: this.txIds,
39
47
  swapFee: (0, Utils_1.serializeBN)(this.swapFee),
40
48
  swapFeeInToken: (0, Utils_1.serializeBN)(this.swapFeeInToken),
@@ -54,11 +62,27 @@ class SwapHandlerSwap extends base_1.Lockable {
54
62
  this.state = newState;
55
63
  return PluginManager_1.PluginManager.swapStateChange(this, oldState);
56
64
  }
57
- getHash() {
58
- return this.data.getHash();
65
+ /**
66
+ * Returns the escrow hash - i.e. hash of the escrow data
67
+ */
68
+ getEscrowHash() {
69
+ return this.data.getEscrowHash();
70
+ }
71
+ /**
72
+ * Returns the claim data hash - i.e. hash passed to the claim handler
73
+ */
74
+ getClaimHash() {
75
+ return this.data.getClaimHash();
76
+ }
77
+ /**
78
+ * Returns the identification hash of the swap, usually claim data hash, but can be overriden, e.g. for
79
+ * lightning swaps the identifier hash is used instead of claim data hash
80
+ */
81
+ getIdentifierHash() {
82
+ return this.getClaimHash();
59
83
  }
60
84
  getSequence() {
61
- return this.data.getSequence();
85
+ return this.data?.getSequence == null ? null : this.data.getSequence();
62
86
  }
63
87
  /**
64
88
  * Returns unique identifier of the swap in the form <hash>_<sequence> or just <hash> if the swap type doesn't
@@ -66,9 +90,9 @@ class SwapHandlerSwap extends base_1.Lockable {
66
90
  */
67
91
  getIdentifier() {
68
92
  if (this.getSequence() != null) {
69
- return this.chainIdentifier + "_" + this.getHash() + "_" + this.getSequence().toString(16);
93
+ return this.chainIdentifier + "_" + this.getIdentifierHash() + "_" + this.getSequence().toString(16);
70
94
  }
71
- return this.getHash();
95
+ return this.chainIdentifier + "_" + this.getIdentifierHash();
72
96
  }
73
97
  /**
74
98
  * Checks whether the swap is finished, such that it is final and either successful or failed