@atomiqlabs/lp-lib 10.3.11

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 (138) hide show
  1. package/LICENSE +201 -0
  2. package/dist/fees/IBtcFeeEstimator.d.ts +3 -0
  3. package/dist/fees/IBtcFeeEstimator.js +2 -0
  4. package/dist/fees/OneDollarFeeEstimator.d.ts +16 -0
  5. package/dist/fees/OneDollarFeeEstimator.js +71 -0
  6. package/dist/index.d.ts +33 -0
  7. package/dist/index.js +52 -0
  8. package/dist/info/InfoHandler.d.ts +17 -0
  9. package/dist/info/InfoHandler.js +70 -0
  10. package/dist/plugins/IPlugin.d.ts +118 -0
  11. package/dist/plugins/IPlugin.js +33 -0
  12. package/dist/plugins/PluginManager.d.ts +89 -0
  13. package/dist/plugins/PluginManager.js +263 -0
  14. package/dist/prices/BinanceSwapPrice.d.ts +27 -0
  15. package/dist/prices/BinanceSwapPrice.js +106 -0
  16. package/dist/prices/CoinGeckoSwapPrice.d.ts +31 -0
  17. package/dist/prices/CoinGeckoSwapPrice.js +76 -0
  18. package/dist/storage/IIntermediaryStorage.d.ts +15 -0
  19. package/dist/storage/IIntermediaryStorage.js +2 -0
  20. package/dist/storagemanager/IntermediaryStorageManager.d.ts +15 -0
  21. package/dist/storagemanager/IntermediaryStorageManager.js +113 -0
  22. package/dist/storagemanager/StorageManager.d.ts +12 -0
  23. package/dist/storagemanager/StorageManager.js +74 -0
  24. package/dist/swaps/FromBtcBaseSwap.d.ts +12 -0
  25. package/dist/swaps/FromBtcBaseSwap.js +16 -0
  26. package/dist/swaps/FromBtcBaseSwapHandler.d.ts +118 -0
  27. package/dist/swaps/FromBtcBaseSwapHandler.js +294 -0
  28. package/dist/swaps/FromBtcLnBaseSwapHandler.d.ts +25 -0
  29. package/dist/swaps/FromBtcLnBaseSwapHandler.js +55 -0
  30. package/dist/swaps/ISwapPrice.d.ts +44 -0
  31. package/dist/swaps/ISwapPrice.js +73 -0
  32. package/dist/swaps/SwapHandler.d.ts +186 -0
  33. package/dist/swaps/SwapHandler.js +292 -0
  34. package/dist/swaps/SwapHandlerSwap.d.ts +75 -0
  35. package/dist/swaps/SwapHandlerSwap.js +72 -0
  36. package/dist/swaps/ToBtcBaseSwap.d.ts +35 -0
  37. package/dist/swaps/ToBtcBaseSwap.js +61 -0
  38. package/dist/swaps/ToBtcBaseSwapHandler.d.ts +94 -0
  39. package/dist/swaps/ToBtcBaseSwapHandler.js +233 -0
  40. package/dist/swaps/frombtc_abstract/FromBtcAbs.d.ts +92 -0
  41. package/dist/swaps/frombtc_abstract/FromBtcAbs.js +386 -0
  42. package/dist/swaps/frombtc_abstract/FromBtcSwapAbs.d.ts +26 -0
  43. package/dist/swaps/frombtc_abstract/FromBtcSwapAbs.js +63 -0
  44. package/dist/swaps/frombtc_trusted/FromBtcTrusted.d.ts +55 -0
  45. package/dist/swaps/frombtc_trusted/FromBtcTrusted.js +586 -0
  46. package/dist/swaps/frombtc_trusted/FromBtcTrustedSwap.d.ts +43 -0
  47. package/dist/swaps/frombtc_trusted/FromBtcTrustedSwap.js +99 -0
  48. package/dist/swaps/frombtcln_abstract/FromBtcLnAbs.d.ts +105 -0
  49. package/dist/swaps/frombtcln_abstract/FromBtcLnAbs.js +731 -0
  50. package/dist/swaps/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +29 -0
  51. package/dist/swaps/frombtcln_abstract/FromBtcLnSwapAbs.js +64 -0
  52. package/dist/swaps/frombtcln_trusted/FromBtcLnTrusted.d.ts +79 -0
  53. package/dist/swaps/frombtcln_trusted/FromBtcLnTrusted.js +514 -0
  54. package/dist/swaps/frombtcln_trusted/FromBtcLnTrustedSwap.d.ts +28 -0
  55. package/dist/swaps/frombtcln_trusted/FromBtcLnTrustedSwap.js +66 -0
  56. package/dist/swaps/tobtc_abstract/ToBtcAbs.d.ts +290 -0
  57. package/dist/swaps/tobtc_abstract/ToBtcAbs.js +1056 -0
  58. package/dist/swaps/tobtc_abstract/ToBtcSwapAbs.d.ts +29 -0
  59. package/dist/swaps/tobtc_abstract/ToBtcSwapAbs.js +70 -0
  60. package/dist/swaps/tobtcln_abstract/ToBtcLnAbs.d.ts +246 -0
  61. package/dist/swaps/tobtcln_abstract/ToBtcLnAbs.js +1169 -0
  62. package/dist/swaps/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +27 -0
  63. package/dist/swaps/tobtcln_abstract/ToBtcLnSwapAbs.js +65 -0
  64. package/dist/utils/Utils.d.ts +32 -0
  65. package/dist/utils/Utils.js +109 -0
  66. package/dist/utils/coinselect2/accumulative.d.ts +6 -0
  67. package/dist/utils/coinselect2/accumulative.js +44 -0
  68. package/dist/utils/coinselect2/blackjack.d.ts +6 -0
  69. package/dist/utils/coinselect2/blackjack.js +41 -0
  70. package/dist/utils/coinselect2/index.d.ts +16 -0
  71. package/dist/utils/coinselect2/index.js +40 -0
  72. package/dist/utils/coinselect2/utils.d.ts +64 -0
  73. package/dist/utils/coinselect2/utils.js +121 -0
  74. package/dist/utils/paramcoders/IParamReader.d.ts +5 -0
  75. package/dist/utils/paramcoders/IParamReader.js +2 -0
  76. package/dist/utils/paramcoders/IParamWriter.d.ts +4 -0
  77. package/dist/utils/paramcoders/IParamWriter.js +2 -0
  78. package/dist/utils/paramcoders/LegacyParamEncoder.d.ts +10 -0
  79. package/dist/utils/paramcoders/LegacyParamEncoder.js +33 -0
  80. package/dist/utils/paramcoders/ParamDecoder.d.ts +25 -0
  81. package/dist/utils/paramcoders/ParamDecoder.js +234 -0
  82. package/dist/utils/paramcoders/ParamEncoder.d.ts +9 -0
  83. package/dist/utils/paramcoders/ParamEncoder.js +22 -0
  84. package/dist/utils/paramcoders/SchemaVerifier.d.ts +22 -0
  85. package/dist/utils/paramcoders/SchemaVerifier.js +85 -0
  86. package/dist/utils/paramcoders/server/ServerParamDecoder.d.ts +8 -0
  87. package/dist/utils/paramcoders/server/ServerParamDecoder.js +105 -0
  88. package/dist/utils/paramcoders/server/ServerParamEncoder.d.ts +11 -0
  89. package/dist/utils/paramcoders/server/ServerParamEncoder.js +76 -0
  90. package/package.json +43 -0
  91. package/src/fees/IBtcFeeEstimator.ts +7 -0
  92. package/src/fees/OneDollarFeeEstimator.ts +95 -0
  93. package/src/index.ts +46 -0
  94. package/src/info/InfoHandler.ts +106 -0
  95. package/src/plugins/IPlugin.ts +155 -0
  96. package/src/plugins/PluginManager.ts +310 -0
  97. package/src/prices/BinanceSwapPrice.ts +114 -0
  98. package/src/prices/CoinGeckoSwapPrice.ts +88 -0
  99. package/src/storage/IIntermediaryStorage.ts +21 -0
  100. package/src/storagemanager/IntermediaryStorageManager.ts +101 -0
  101. package/src/storagemanager/StorageManager.ts +68 -0
  102. package/src/swaps/FromBtcBaseSwap.ts +21 -0
  103. package/src/swaps/FromBtcBaseSwapHandler.ts +375 -0
  104. package/src/swaps/FromBtcLnBaseSwapHandler.ts +48 -0
  105. package/src/swaps/ISwapPrice.ts +94 -0
  106. package/src/swaps/SwapHandler.ts +404 -0
  107. package/src/swaps/SwapHandlerSwap.ts +133 -0
  108. package/src/swaps/ToBtcBaseSwap.ts +76 -0
  109. package/src/swaps/ToBtcBaseSwapHandler.ts +309 -0
  110. package/src/swaps/frombtc_abstract/FromBtcAbs.ts +484 -0
  111. package/src/swaps/frombtc_abstract/FromBtcSwapAbs.ts +77 -0
  112. package/src/swaps/frombtc_trusted/FromBtcTrusted.ts +661 -0
  113. package/src/swaps/frombtc_trusted/FromBtcTrustedSwap.ts +158 -0
  114. package/src/swaps/frombtcln_abstract/FromBtcLnAbs.ts +864 -0
  115. package/src/swaps/frombtcln_abstract/FromBtcLnSwapAbs.ts +82 -0
  116. package/src/swaps/frombtcln_trusted/FromBtcLnTrusted.ts +592 -0
  117. package/src/swaps/frombtcln_trusted/FromBtcLnTrustedSwap.ts +90 -0
  118. package/src/swaps/tobtc_abstract/ToBtcAbs.ts +1249 -0
  119. package/src/swaps/tobtc_abstract/ToBtcSwapAbs.ts +112 -0
  120. package/src/swaps/tobtcln_abstract/ToBtcLnAbs.ts +1422 -0
  121. package/src/swaps/tobtcln_abstract/ToBtcLnSwapAbs.ts +87 -0
  122. package/src/utils/Utils.ts +108 -0
  123. package/src/utils/coinselect2/accumulative.js +32 -0
  124. package/src/utils/coinselect2/accumulative.ts +58 -0
  125. package/src/utils/coinselect2/blackjack.js +29 -0
  126. package/src/utils/coinselect2/blackjack.ts +54 -0
  127. package/src/utils/coinselect2/index.js +16 -0
  128. package/src/utils/coinselect2/index.ts +50 -0
  129. package/src/utils/coinselect2/utils.js +110 -0
  130. package/src/utils/coinselect2/utils.ts +183 -0
  131. package/src/utils/paramcoders/IParamReader.ts +8 -0
  132. package/src/utils/paramcoders/IParamWriter.ts +8 -0
  133. package/src/utils/paramcoders/LegacyParamEncoder.ts +28 -0
  134. package/src/utils/paramcoders/ParamDecoder.ts +219 -0
  135. package/src/utils/paramcoders/ParamEncoder.ts +30 -0
  136. package/src/utils/paramcoders/SchemaVerifier.ts +97 -0
  137. package/src/utils/paramcoders/server/ServerParamDecoder.ts +115 -0
  138. package/src/utils/paramcoders/server/ServerParamEncoder.ts +76 -0
@@ -0,0 +1,75 @@
1
+ import { Lockable, StorageObject, SwapData } from "@atomiqlabs/base";
2
+ import { SwapHandlerType } from "./SwapHandler";
3
+ import * as BN from "bn.js";
4
+ export declare abstract class SwapHandlerSwap<T extends SwapData = SwapData, S = any> extends Lockable implements StorageObject {
5
+ chainIdentifier: string;
6
+ state: S;
7
+ type: SwapHandlerType;
8
+ data: T;
9
+ metadata: {
10
+ request: any;
11
+ times: {
12
+ [key: string]: number;
13
+ };
14
+ [key: string]: any;
15
+ };
16
+ txIds: {
17
+ init?: string;
18
+ claim?: string;
19
+ refund?: string;
20
+ };
21
+ readonly swapFee: BN;
22
+ readonly swapFeeInToken: BN;
23
+ protected constructor(chainIdentifier: string, swapFee: BN, swapFeeInToken: BN);
24
+ protected constructor(obj: any);
25
+ serialize(): any;
26
+ /**
27
+ * Sets the state of the swap and also calls swap change listener on plugins
28
+ *
29
+ * @param newState
30
+ */
31
+ setState(newState: S): Promise<void>;
32
+ getHash(): string;
33
+ getSequence(): BN;
34
+ /**
35
+ * Returns unique identifier of the swap in the form <hash>_<sequence> or just <hash> if the swap type doesn't
36
+ * use sequence number
37
+ */
38
+ getIdentifier(): string;
39
+ /**
40
+ * Checks whether the swap is finished, such that it is final and either successful or failed
41
+ */
42
+ isFinished(): boolean;
43
+ /**
44
+ * Checks whether the swap was initiated by the user
45
+ */
46
+ abstract isInitiated(): boolean;
47
+ /**
48
+ * Checks whether the swap was finished and was successful
49
+ */
50
+ abstract isSuccess(): boolean;
51
+ /**
52
+ * Checks whether the swap was finished and was failed
53
+ */
54
+ abstract isFailed(): boolean;
55
+ /**
56
+ * Returns the input amount paid by the user (excluding fees)
57
+ */
58
+ abstract getInputAmount(): BN;
59
+ /**
60
+ * Returns the total input amount paid by the user (including all fees)
61
+ */
62
+ abstract getTotalInputAmount(): BN;
63
+ /**
64
+ * Returns the actual output amount paid out to the user
65
+ */
66
+ abstract getOutputAmount(): BN;
67
+ /**
68
+ * Returns swap fee, denominated in input & output tokens (the fee is paid only once, it is just represented here in
69
+ * both denomination for ease of use)
70
+ */
71
+ abstract getSwapFee(): {
72
+ inInputToken: BN;
73
+ inOutputToken: BN;
74
+ };
75
+ }
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SwapHandlerSwap = void 0;
4
+ const base_1 = require("@atomiqlabs/base");
5
+ const PluginManager_1 = require("../plugins/PluginManager");
6
+ const BN = require("bn.js");
7
+ const Utils_1 = require("../utils/Utils");
8
+ class SwapHandlerSwap extends base_1.Lockable {
9
+ constructor(obj, swapFee, swapFeeInToken) {
10
+ super();
11
+ this.txIds = {};
12
+ if (typeof (obj) === "string" && BN.isBN(swapFee) && BN.isBN(swapFeeInToken)) {
13
+ this.chainIdentifier = obj;
14
+ this.swapFee = swapFee;
15
+ this.swapFeeInToken = swapFeeInToken;
16
+ return;
17
+ }
18
+ else {
19
+ this.data = obj.data == null ? null : base_1.SwapData.deserialize(obj.data);
20
+ this.metadata = obj.metadata;
21
+ this.chainIdentifier = obj.chainIdentifier;
22
+ this.txIds = obj.txIds || {};
23
+ this.state = obj.state;
24
+ this.swapFee = (0, Utils_1.deserializeBN)(obj.swapFee);
25
+ this.swapFeeInToken = (0, Utils_1.deserializeBN)(obj.swapFeeInToken);
26
+ }
27
+ }
28
+ serialize() {
29
+ return {
30
+ state: this.state,
31
+ data: this.data == null ? null : this.data.serialize(),
32
+ chainIdentifier: this.chainIdentifier,
33
+ metadata: this.metadata,
34
+ txIds: this.txIds,
35
+ swapFee: (0, Utils_1.serializeBN)(this.swapFee),
36
+ swapFeeInToken: (0, Utils_1.serializeBN)(this.swapFeeInToken)
37
+ };
38
+ }
39
+ /**
40
+ * Sets the state of the swap and also calls swap change listener on plugins
41
+ *
42
+ * @param newState
43
+ */
44
+ setState(newState) {
45
+ const oldState = this.state;
46
+ this.state = newState;
47
+ return PluginManager_1.PluginManager.swapStateChange(this, oldState);
48
+ }
49
+ getHash() {
50
+ return this.data.getHash();
51
+ }
52
+ getSequence() {
53
+ return this.data.getSequence();
54
+ }
55
+ /**
56
+ * Returns unique identifier of the swap in the form <hash>_<sequence> or just <hash> if the swap type doesn't
57
+ * use sequence number
58
+ */
59
+ getIdentifier() {
60
+ if (this.getSequence() != null) {
61
+ return this.chainIdentifier + "_" + this.getHash() + "_" + this.getSequence().toString(16);
62
+ }
63
+ return this.getHash();
64
+ }
65
+ /**
66
+ * Checks whether the swap is finished, such that it is final and either successful or failed
67
+ */
68
+ isFinished() {
69
+ return this.isSuccess() || this.isFailed();
70
+ }
71
+ }
72
+ exports.SwapHandlerSwap = SwapHandlerSwap;
@@ -0,0 +1,35 @@
1
+ import { SwapHandlerSwap } from "./SwapHandlerSwap";
2
+ import { SwapData } from "@atomiqlabs/base";
3
+ import * as BN from "bn.js";
4
+ export declare abstract class ToBtcBaseSwap<T extends SwapData = SwapData, S = any> extends SwapHandlerSwap<T, S> {
5
+ quotedNetworkFee: BN;
6
+ readonly quotedNetworkFeeInToken: BN;
7
+ realNetworkFee: BN;
8
+ realNetworkFeeInToken: BN;
9
+ protected constructor(chainIdentifier: string, swapFee: BN, swapFeeInToken: BN, quotedNetworkFee: BN, quotedNetworkFeeInToken: BN);
10
+ protected constructor(obj: any);
11
+ serialize(): any;
12
+ setRealNetworkFee(networkFeeInBtc: BN): void;
13
+ getInputAmount(): BN;
14
+ getTotalInputAmount(): BN;
15
+ getSwapFee(): {
16
+ inInputToken: BN;
17
+ inOutputToken: BN;
18
+ };
19
+ /**
20
+ * Returns quoted (expected) network fee, denominated in input & output tokens (the fee is paid only once, it is
21
+ * just represented here in both denomination for ease of use)
22
+ */
23
+ getQuotedNetworkFee(): {
24
+ inInputToken: BN;
25
+ inOutputToken: BN;
26
+ };
27
+ /**
28
+ * Returns real network fee paid for the swap, denominated in input & output tokens (the fee is paid only once, it is
29
+ * just represented here in both denomination for ease of use)
30
+ */
31
+ getRealNetworkFee(): {
32
+ inInputToken: BN;
33
+ inOutputToken: BN;
34
+ };
35
+ }
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ToBtcBaseSwap = void 0;
4
+ const SwapHandlerSwap_1 = require("./SwapHandlerSwap");
5
+ const BN = require("bn.js");
6
+ const Utils_1 = require("../utils/Utils");
7
+ class ToBtcBaseSwap extends SwapHandlerSwap_1.SwapHandlerSwap {
8
+ constructor(obj, swapFee, swapFeeInToken, quotedNetworkFee, quotedNetworkFeeInToken) {
9
+ if (typeof (obj) === "string" && BN.isBN(swapFee) && BN.isBN(swapFeeInToken) && BN.isBN(quotedNetworkFee) && BN.isBN(quotedNetworkFeeInToken)) {
10
+ super(obj, swapFee, swapFeeInToken);
11
+ this.quotedNetworkFee = quotedNetworkFee;
12
+ this.quotedNetworkFeeInToken = quotedNetworkFeeInToken;
13
+ return;
14
+ }
15
+ else {
16
+ super(obj);
17
+ this.quotedNetworkFee = (0, Utils_1.deserializeBN)(obj.quotedNetworkFee);
18
+ this.quotedNetworkFeeInToken = (0, Utils_1.deserializeBN)(obj.quotedNetworkFeeInToken);
19
+ this.realNetworkFee = (0, Utils_1.deserializeBN)(obj.realNetworkFee);
20
+ this.realNetworkFeeInToken = (0, Utils_1.deserializeBN)(obj.realNetworkFeeInToken);
21
+ }
22
+ }
23
+ serialize() {
24
+ const obj = super.serialize();
25
+ obj.quotedNetworkFee = (0, Utils_1.serializeBN)(this.quotedNetworkFee);
26
+ obj.quotedNetworkFeeInToken = (0, Utils_1.serializeBN)(this.quotedNetworkFeeInToken);
27
+ obj.realNetworkFee = (0, Utils_1.serializeBN)(this.realNetworkFee);
28
+ obj.realNetworkFeeInToken = (0, Utils_1.serializeBN)(this.realNetworkFeeInToken);
29
+ return obj;
30
+ }
31
+ setRealNetworkFee(networkFeeInBtc) {
32
+ this.realNetworkFee = networkFeeInBtc;
33
+ if (this.quotedNetworkFee != null && this.quotedNetworkFeeInToken != null) {
34
+ this.realNetworkFeeInToken = this.realNetworkFee.mul(this.quotedNetworkFeeInToken).div(this.quotedNetworkFee);
35
+ }
36
+ }
37
+ getInputAmount() {
38
+ return this.data.getAmount().sub(this.getSwapFee().inInputToken).sub(this.getQuotedNetworkFee().inInputToken);
39
+ }
40
+ getTotalInputAmount() {
41
+ return this.data.getAmount();
42
+ }
43
+ getSwapFee() {
44
+ return { inInputToken: this.swapFeeInToken, inOutputToken: this.swapFee };
45
+ }
46
+ /**
47
+ * Returns quoted (expected) network fee, denominated in input & output tokens (the fee is paid only once, it is
48
+ * just represented here in both denomination for ease of use)
49
+ */
50
+ getQuotedNetworkFee() {
51
+ return { inInputToken: this.quotedNetworkFeeInToken, inOutputToken: this.quotedNetworkFee };
52
+ }
53
+ /**
54
+ * Returns real network fee paid for the swap, denominated in input & output tokens (the fee is paid only once, it is
55
+ * just represented here in both denomination for ease of use)
56
+ */
57
+ getRealNetworkFee() {
58
+ return { inInputToken: this.realNetworkFeeInToken, inOutputToken: this.realNetworkFee };
59
+ }
60
+ }
61
+ exports.ToBtcBaseSwap = ToBtcBaseSwap;
@@ -0,0 +1,94 @@
1
+ import { RequestData, SwapBaseConfig, SwapHandler } from "./SwapHandler";
2
+ import { SwapHandlerSwap } from "./SwapHandlerSwap";
3
+ import { SwapData } from "@atomiqlabs/base";
4
+ import * as BN from "bn.js";
5
+ import { ServerParamEncoder } from "../utils/paramcoders/server/ServerParamEncoder";
6
+ import { IParamReader } from "../utils/paramcoders/IParamReader";
7
+ import { ToBtcLnRequestType } from "./tobtcln_abstract/ToBtcLnAbs";
8
+ import { ToBtcRequestType } from "./tobtc_abstract/ToBtcAbs";
9
+ import { Request } from "express";
10
+ export type ToBtcBaseConfig = SwapBaseConfig & {
11
+ gracePeriod: BN;
12
+ };
13
+ export declare abstract class ToBtcBaseSwapHandler<V extends SwapHandlerSwap<SwapData, S>, S> extends SwapHandler<V, S> {
14
+ readonly pdaExistsForToken: {
15
+ [chainIdentifier: string]: {
16
+ [token: string]: boolean;
17
+ };
18
+ };
19
+ abstract config: ToBtcBaseConfig;
20
+ protected checkVaultInitialized(chainIdentifier: string, token: string): Promise<void>;
21
+ /**
22
+ * Checks minimums/maximums, calculates the fee & total amount
23
+ *
24
+ * @param request
25
+ * @param requestedAmount
26
+ * @param useToken
27
+ * @throws {DefinedRuntimeError} will throw an error if the amount is outside minimum/maximum bounds
28
+ */
29
+ protected preCheckAmounts(request: RequestData<ToBtcLnRequestType | ToBtcRequestType>, requestedAmount: {
30
+ input: boolean;
31
+ amount: BN;
32
+ }, useToken: string): Promise<{
33
+ baseFee: BN;
34
+ feePPM: BN;
35
+ }>;
36
+ /**
37
+ * Checks minimums/maximums, calculates network fee (based on the callback passed), swap fee & total amount
38
+ *
39
+ * @param request
40
+ * @param requestedAmount
41
+ * @param fees
42
+ * @param useToken
43
+ * @param getNetworkFee
44
+ * @param signal
45
+ * @param pricePrefetchPromise
46
+ * @throws {DefinedRuntimeError} will throw an error if the amount is outside minimum/maximum bounds,
47
+ * or if we don't have enough funds (getNetworkFee callback throws)
48
+ */
49
+ protected checkToBtcAmount<T extends {
50
+ networkFee: BN;
51
+ }>(request: RequestData<ToBtcLnRequestType | ToBtcRequestType>, requestedAmount: {
52
+ input: boolean;
53
+ amount: BN;
54
+ }, fees: {
55
+ baseFee: BN;
56
+ feePPM: BN;
57
+ }, useToken: string, getNetworkFee: (amount: BN) => Promise<T>, signal: AbortSignal, pricePrefetchPromise?: Promise<BN>): Promise<{
58
+ amountBD: BN;
59
+ networkFeeData: T;
60
+ swapFee: BN;
61
+ swapFeeInToken: BN;
62
+ networkFee: BN;
63
+ networkFeeInToken: BN;
64
+ totalInToken: BN;
65
+ }>;
66
+ /**
67
+ * Starts pre-fetches for swap pricing & signature data
68
+ *
69
+ * @param chainIdentifier
70
+ * @param token
71
+ * @param responseStream
72
+ * @param abortController
73
+ */
74
+ protected getToBtcPrefetches(chainIdentifier: string, token: string, responseStream: ServerParamEncoder, abortController: AbortController): {
75
+ pricePrefetchPromise?: Promise<BN>;
76
+ signDataPrefetchPromise?: Promise<any>;
77
+ };
78
+ /**
79
+ * Signs the created swap
80
+ *
81
+ * @param chainIdentifier
82
+ * @param swapObject
83
+ * @param req
84
+ * @param abortSignal
85
+ * @param signDataPrefetchPromise
86
+ */
87
+ protected getToBtcSignatureData(chainIdentifier: string, swapObject: SwapData, req: Request & {
88
+ paramReader: IParamReader;
89
+ }, abortSignal: AbortSignal, signDataPrefetchPromise?: Promise<any>): Promise<{
90
+ prefix: string;
91
+ timeout: string;
92
+ signature: string;
93
+ }>;
94
+ }
@@ -0,0 +1,233 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ToBtcBaseSwapHandler = void 0;
13
+ const SwapHandler_1 = require("./SwapHandler");
14
+ const BN = require("bn.js");
15
+ const SchemaVerifier_1 = require("../utils/paramcoders/SchemaVerifier");
16
+ const PluginManager_1 = require("../plugins/PluginManager");
17
+ const IPlugin_1 = require("../plugins/IPlugin");
18
+ class ToBtcBaseSwapHandler extends SwapHandler_1.SwapHandler {
19
+ constructor() {
20
+ super(...arguments);
21
+ this.pdaExistsForToken = {};
22
+ }
23
+ checkVaultInitialized(chainIdentifier, token) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ if (!this.pdaExistsForToken[chainIdentifier] || !this.pdaExistsForToken[chainIdentifier][token]) {
26
+ this.logger.debug("checkVaultInitialized(): checking vault exists for chain: " + chainIdentifier + " token: " + token);
27
+ const { swapContract, signer } = this.getChain(chainIdentifier);
28
+ const reputation = yield swapContract.getIntermediaryReputation(signer.getAddress(), token);
29
+ this.logger.debug("checkVaultInitialized(): vault state, chain: " + chainIdentifier + " token: " + token + " exists: " + (reputation != null));
30
+ if (reputation != null) {
31
+ if (this.pdaExistsForToken[chainIdentifier] == null)
32
+ this.pdaExistsForToken[chainIdentifier] = {};
33
+ this.pdaExistsForToken[chainIdentifier][token] = true;
34
+ }
35
+ else {
36
+ throw {
37
+ code: 20201,
38
+ msg: "Token not supported!"
39
+ };
40
+ }
41
+ }
42
+ });
43
+ }
44
+ /**
45
+ * Checks minimums/maximums, calculates the fee & total amount
46
+ *
47
+ * @param request
48
+ * @param requestedAmount
49
+ * @param useToken
50
+ * @throws {DefinedRuntimeError} will throw an error if the amount is outside minimum/maximum bounds
51
+ */
52
+ preCheckAmounts(request, requestedAmount, useToken) {
53
+ return __awaiter(this, void 0, void 0, function* () {
54
+ const res = yield PluginManager_1.PluginManager.onHandlePreToBtcQuote(request, requestedAmount, request.chainIdentifier, useToken, { minInBtc: this.config.min, maxInBtc: this.config.max }, { baseFeeInBtc: this.config.baseFee, feePPM: this.config.feePPM });
55
+ if (res != null) {
56
+ this.handlePluginErrorResponses(res);
57
+ if ((0, IPlugin_1.isQuoteSetFees)(res)) {
58
+ return {
59
+ baseFee: res.baseFee || this.config.baseFee,
60
+ feePPM: res.feePPM || this.config.feePPM
61
+ };
62
+ }
63
+ }
64
+ if (!requestedAmount.input) {
65
+ this.checkBtcAmountInBounds(requestedAmount.amount);
66
+ }
67
+ return {
68
+ baseFee: this.config.baseFee,
69
+ feePPM: this.config.feePPM
70
+ };
71
+ });
72
+ }
73
+ /**
74
+ * Checks minimums/maximums, calculates network fee (based on the callback passed), swap fee & total amount
75
+ *
76
+ * @param request
77
+ * @param requestedAmount
78
+ * @param fees
79
+ * @param useToken
80
+ * @param getNetworkFee
81
+ * @param signal
82
+ * @param pricePrefetchPromise
83
+ * @throws {DefinedRuntimeError} will throw an error if the amount is outside minimum/maximum bounds,
84
+ * or if we don't have enough funds (getNetworkFee callback throws)
85
+ */
86
+ checkToBtcAmount(request, requestedAmount, fees, useToken, getNetworkFee, signal, pricePrefetchPromise) {
87
+ return __awaiter(this, void 0, void 0, function* () {
88
+ const chainIdentifier = request.chainIdentifier;
89
+ const res = yield PluginManager_1.PluginManager.onHandlePostToBtcQuote(request, requestedAmount, request.chainIdentifier, useToken, { minInBtc: this.config.min, maxInBtc: this.config.max }, { baseFeeInBtc: fees.baseFee, feePPM: fees.feePPM, networkFeeGetter: getNetworkFee }, pricePrefetchPromise);
90
+ signal.throwIfAborted();
91
+ if (res != null) {
92
+ this.handlePluginErrorResponses(res);
93
+ if ((0, IPlugin_1.isQuoteSetFees)(res)) {
94
+ if (res.baseFee != null)
95
+ fees.baseFee = res.baseFee;
96
+ if (res.feePPM != null)
97
+ fees.feePPM = res.feePPM;
98
+ }
99
+ if ((0, IPlugin_1.isToBtcPluginQuote)(res)) {
100
+ if (requestedAmount.input) {
101
+ return {
102
+ amountBD: res.amount.amount,
103
+ swapFee: res.swapFee.inOutputTokens,
104
+ swapFeeInToken: res.swapFee.inInputTokens,
105
+ networkFee: res.networkFee.inOutputTokens,
106
+ networkFeeInToken: res.networkFee.inInputTokens,
107
+ networkFeeData: res.networkFeeData,
108
+ totalInToken: requestedAmount.amount
109
+ };
110
+ }
111
+ else {
112
+ return {
113
+ amountBD: requestedAmount.amount,
114
+ swapFee: res.swapFee.inOutputTokens,
115
+ swapFeeInToken: res.swapFee.inInputTokens,
116
+ networkFee: res.networkFee.inOutputTokens,
117
+ networkFeeInToken: res.networkFee.inInputTokens,
118
+ networkFeeData: res.networkFeeData,
119
+ totalInToken: res.amount.amount.add(res.swapFee.inInputTokens).add(res.networkFee.inInputTokens)
120
+ };
121
+ }
122
+ }
123
+ }
124
+ let amountBD;
125
+ let tooLow = false;
126
+ if (requestedAmount.input) {
127
+ amountBD = yield this.swapPricing.getToBtcSwapAmount(requestedAmount.amount, useToken, chainIdentifier, null, pricePrefetchPromise);
128
+ signal.throwIfAborted();
129
+ //Decrease by base fee
130
+ amountBD = amountBD.sub(fees.baseFee);
131
+ //If it's already smaller than minimum, set it to minimum so we can calculate the network fee
132
+ if (amountBD.lt(this.config.min)) {
133
+ amountBD = this.config.min;
134
+ tooLow = true;
135
+ }
136
+ }
137
+ else {
138
+ amountBD = requestedAmount.amount;
139
+ this.checkBtcAmountInBounds(amountBD);
140
+ }
141
+ const resp = yield getNetworkFee(amountBD);
142
+ this.logger.debug("checkToBtcAmount(): network fee calculated, amount: " + amountBD.toString(10) + " fee: " + resp.networkFee.toString(10));
143
+ signal.throwIfAborted();
144
+ if (requestedAmount.input) {
145
+ //Decrease by network fee
146
+ amountBD = amountBD.sub(resp.networkFee);
147
+ //Decrease by percentage fee
148
+ amountBD = amountBD.mul(new BN(1000000)).div(fees.feePPM.add(new BN(1000000)));
149
+ const tooHigh = amountBD.gt(this.config.max.mul(new BN(105)).div(new BN(100)));
150
+ tooLow || (tooLow = amountBD.lt(this.config.min.mul(new BN(95)).div(new BN(100))));
151
+ if (tooLow || tooHigh) {
152
+ //Compute min/max
153
+ let adjustedMin = this.config.min.mul(fees.feePPM.add(new BN(1000000))).div(new BN(1000000));
154
+ let adjustedMax = this.config.max.mul(fees.feePPM.add(new BN(1000000))).div(new BN(1000000));
155
+ adjustedMin = adjustedMin.add(fees.baseFee).add(resp.networkFee);
156
+ adjustedMax = adjustedMax.add(fees.baseFee).add(resp.networkFee);
157
+ const minIn = yield this.swapPricing.getFromBtcSwapAmount(adjustedMin, useToken, chainIdentifier, null, pricePrefetchPromise);
158
+ const maxIn = yield this.swapPricing.getFromBtcSwapAmount(adjustedMax, useToken, chainIdentifier, null, pricePrefetchPromise);
159
+ throw {
160
+ code: tooLow ? 20003 : 2004,
161
+ msg: tooLow ? "Amount too low!" : "Amount too high!",
162
+ data: {
163
+ min: minIn.toString(10),
164
+ max: maxIn.toString(10)
165
+ }
166
+ };
167
+ }
168
+ }
169
+ const swapFee = fees.baseFee.add(amountBD.mul(fees.feePPM).div(new BN(1000000)));
170
+ const networkFeeInToken = yield this.swapPricing.getFromBtcSwapAmount(resp.networkFee, useToken, chainIdentifier, true, pricePrefetchPromise);
171
+ const swapFeeInToken = yield this.swapPricing.getFromBtcSwapAmount(swapFee, useToken, chainIdentifier, true, pricePrefetchPromise);
172
+ signal.throwIfAborted();
173
+ let total;
174
+ if (requestedAmount.input) {
175
+ total = requestedAmount.amount;
176
+ }
177
+ else {
178
+ const amountInToken = yield this.swapPricing.getFromBtcSwapAmount(requestedAmount.amount, useToken, chainIdentifier, true, pricePrefetchPromise);
179
+ signal.throwIfAborted();
180
+ total = amountInToken.add(swapFeeInToken).add(networkFeeInToken);
181
+ }
182
+ return { amountBD, networkFeeData: resp, swapFee, swapFeeInToken, networkFee: resp.networkFee, networkFeeInToken, totalInToken: total };
183
+ });
184
+ }
185
+ /**
186
+ * Starts pre-fetches for swap pricing & signature data
187
+ *
188
+ * @param chainIdentifier
189
+ * @param token
190
+ * @param responseStream
191
+ * @param abortController
192
+ */
193
+ getToBtcPrefetches(chainIdentifier, token, responseStream, abortController) {
194
+ //Fetch pricing & signature data in parallel
195
+ const pricePrefetchPromise = this.swapPricing.preFetchPrice(token, chainIdentifier).catch(e => {
196
+ this.logger.error("getToBtcPrefetches(): pricePrefetch error", e);
197
+ abortController.abort(e);
198
+ return null;
199
+ });
200
+ return {
201
+ pricePrefetchPromise,
202
+ signDataPrefetchPromise: this.getSignDataPrefetch(chainIdentifier, abortController, responseStream)
203
+ };
204
+ }
205
+ /**
206
+ * Signs the created swap
207
+ *
208
+ * @param chainIdentifier
209
+ * @param swapObject
210
+ * @param req
211
+ * @param abortSignal
212
+ * @param signDataPrefetchPromise
213
+ */
214
+ getToBtcSignatureData(chainIdentifier, swapObject, req, abortSignal, signDataPrefetchPromise) {
215
+ return __awaiter(this, void 0, void 0, function* () {
216
+ const prefetchedSignData = signDataPrefetchPromise != null ? yield signDataPrefetchPromise : null;
217
+ if (prefetchedSignData != null)
218
+ this.logger.debug("getToBtcSignatureData(): pre-fetched signature data: ", prefetchedSignData);
219
+ abortSignal.throwIfAborted();
220
+ const feeRateObj = yield req.paramReader.getParams({
221
+ feeRate: SchemaVerifier_1.FieldTypeEnum.String
222
+ }).catch(() => null);
223
+ abortSignal.throwIfAborted();
224
+ const feeRate = (feeRateObj === null || feeRateObj === void 0 ? void 0 : feeRateObj.feeRate) != null && typeof (feeRateObj.feeRate) === "string" ? feeRateObj.feeRate : null;
225
+ this.logger.debug("getToBtcSignatureData(): using fee rate from client: ", feeRate);
226
+ const { swapContract, signer } = this.getChain(chainIdentifier);
227
+ const sigData = yield swapContract.getInitSignature(signer, swapObject, this.config.authorizationTimeout, prefetchedSignData, feeRate);
228
+ abortSignal.throwIfAborted();
229
+ return sigData;
230
+ });
231
+ }
232
+ }
233
+ exports.ToBtcBaseSwapHandler = ToBtcBaseSwapHandler;
@@ -0,0 +1,92 @@
1
+ import * as BN from "bn.js";
2
+ import { Express } from "express";
3
+ import { FromBtcSwapAbs, FromBtcSwapState } from "./FromBtcSwapAbs";
4
+ import { MultichainData, SwapHandlerType } from "../SwapHandler";
5
+ import { ISwapPrice } from "../ISwapPrice";
6
+ import { ClaimEvent, InitializeEvent, RefundEvent, SwapData } from "@atomiqlabs/base";
7
+ import { AuthenticatedLnd } from "lightning";
8
+ import * as bitcoin from "bitcoinjs-lib";
9
+ import { IIntermediaryStorage } from "../../storage/IIntermediaryStorage";
10
+ import { FromBtcBaseConfig, FromBtcBaseSwapHandler } from "../FromBtcBaseSwapHandler";
11
+ export type FromBtcConfig = FromBtcBaseConfig & {
12
+ bitcoinNetwork: bitcoin.networks.Network;
13
+ confirmations: number;
14
+ swapCsvDelta: number;
15
+ };
16
+ export type FromBtcRequestType = {
17
+ address: string;
18
+ amount: BN;
19
+ token: string;
20
+ sequence: BN;
21
+ exactOut?: boolean;
22
+ };
23
+ /**
24
+ * Swap handler handling from BTC swaps using PTLCs (proof-time locked contracts) and btc relay (on-chain bitcoin SPV)
25
+ */
26
+ export declare class FromBtcAbs extends FromBtcBaseSwapHandler<FromBtcSwapAbs, FromBtcSwapState> {
27
+ readonly type = SwapHandlerType.FROM_BTC;
28
+ readonly config: FromBtcConfig & {
29
+ swapTsCsvDelta: BN;
30
+ };
31
+ constructor(storageDirectory: IIntermediaryStorage<FromBtcSwapAbs>, path: string, chains: MultichainData, lnd: AuthenticatedLnd, swapPricing: ISwapPrice, config: FromBtcConfig);
32
+ /**
33
+ * Returns the TXO hash of the specific address and amount - sha256(u64le(amount) + outputScript(address))
34
+ *
35
+ * @param address
36
+ * @param amount
37
+ * @param bitcoinNetwork
38
+ */
39
+ private getTxoHash;
40
+ /**
41
+ * Returns the payment hash of the swap, takes swap nonce into account. Payment hash is chain-specific.
42
+ *
43
+ * @param chainIdentifier
44
+ * @param address
45
+ * @param amount
46
+ */
47
+ private getHash;
48
+ /**
49
+ * Processes past swap
50
+ *
51
+ * @param swap
52
+ * @protected
53
+ * @returns true if the swap should be refunded, false if nothing should be done
54
+ */
55
+ protected processPastSwap(swap: FromBtcSwapAbs): Promise<boolean>;
56
+ /**
57
+ * Checks past swaps, refunds and deletes ones that are already expired.
58
+ */
59
+ protected processPastSwaps(): Promise<void>;
60
+ /**
61
+ * Refunds all swaps (calls SC on-chain refund function)
62
+ *
63
+ * @param refundSwaps
64
+ * @protected
65
+ */
66
+ protected refundSwaps(refundSwaps: FromBtcSwapAbs[]): Promise<void>;
67
+ protected processInitializeEvent(chainIdentifier: string, event: InitializeEvent<SwapData>): Promise<void>;
68
+ protected processClaimEvent(chainIdentifier: string, event: ClaimEvent<SwapData>): Promise<void>;
69
+ protected processRefundEvent(chainIdentifier: string, event: RefundEvent<SwapData>): Promise<void>;
70
+ /**
71
+ * Calculates the requested claimer bounty, based on client's request
72
+ *
73
+ * @param req
74
+ * @param expiry
75
+ * @param signal
76
+ * @throws {DefinedRuntimeError} will throw an error if the plugin cancelled the request
77
+ * @returns {Promise<BN>} resulting claimer bounty to be used with the swap
78
+ */
79
+ private getClaimerBounty;
80
+ private getDummySwapData;
81
+ /**
82
+ * Sets up required listeners for the REST server
83
+ *
84
+ * @param restServer
85
+ */
86
+ startRestServer(restServer: Express): void;
87
+ /**
88
+ * Initializes swap handler, loads data and subscribes to chain events
89
+ */
90
+ init(): Promise<void>;
91
+ getInfoData(): any;
92
+ }