@atomiqlabs/lp-lib 12.1.0 → 13.0.0-beta.1

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 (119) hide show
  1. package/dist/index.d.ts +18 -13
  2. package/dist/index.js +18 -13
  3. package/dist/plugins/IPlugin.d.ts +35 -12
  4. package/dist/plugins/PluginManager.d.ts +38 -15
  5. package/dist/plugins/PluginManager.js +33 -9
  6. package/dist/prices/BinanceSwapPrice.d.ts +1 -1
  7. package/dist/prices/BinanceSwapPrice.js +1 -1
  8. package/dist/prices/CoinGeckoSwapPrice.d.ts +1 -1
  9. package/dist/prices/CoinGeckoSwapPrice.js +1 -1
  10. package/dist/{swaps → prices}/ISwapPrice.js +4 -0
  11. package/dist/prices/OKXSwapPrice.d.ts +1 -1
  12. package/dist/prices/OKXSwapPrice.js +1 -1
  13. package/dist/swaps/SwapHandler.d.ts +20 -58
  14. package/dist/swaps/SwapHandler.js +17 -186
  15. package/dist/swaps/SwapHandlerSwap.d.ts +8 -23
  16. package/dist/swaps/SwapHandlerSwap.js +7 -39
  17. package/dist/swaps/assertions/AmountAssertions.d.ts +28 -0
  18. package/dist/swaps/assertions/AmountAssertions.js +72 -0
  19. package/dist/swaps/assertions/FromBtcAmountAssertions.d.ts +76 -0
  20. package/dist/swaps/assertions/FromBtcAmountAssertions.js +162 -0
  21. package/dist/swaps/assertions/LightningAssertions.d.ts +44 -0
  22. package/dist/swaps/assertions/LightningAssertions.js +86 -0
  23. package/dist/swaps/assertions/ToBtcAmountAssertions.d.ts +53 -0
  24. package/dist/swaps/{ToBtcBaseSwapHandler.js → assertions/ToBtcAmountAssertions.js} +20 -94
  25. package/dist/swaps/escrow/EscrowHandler.d.ts +51 -0
  26. package/dist/swaps/escrow/EscrowHandler.js +158 -0
  27. package/dist/swaps/escrow/EscrowHandlerSwap.d.ts +35 -0
  28. package/dist/swaps/escrow/EscrowHandlerSwap.js +69 -0
  29. package/dist/swaps/{FromBtcBaseSwap.d.ts → escrow/FromBtcBaseSwap.d.ts} +2 -3
  30. package/dist/swaps/{FromBtcBaseSwap.js → escrow/FromBtcBaseSwap.js} +4 -7
  31. package/dist/swaps/{FromBtcBaseSwapHandler.d.ts → escrow/FromBtcBaseSwapHandler.d.ts} +10 -49
  32. package/dist/swaps/{FromBtcBaseSwapHandler.js → escrow/FromBtcBaseSwapHandler.js} +16 -137
  33. package/dist/swaps/{ToBtcBaseSwap.d.ts → escrow/ToBtcBaseSwap.d.ts} +2 -2
  34. package/dist/swaps/{ToBtcBaseSwap.js → escrow/ToBtcBaseSwap.js} +4 -4
  35. package/dist/swaps/escrow/ToBtcBaseSwapHandler.d.ts +53 -0
  36. package/dist/swaps/escrow/ToBtcBaseSwapHandler.js +81 -0
  37. package/dist/swaps/{frombtc_abstract → escrow/frombtc_abstract}/FromBtcAbs.d.ts +4 -4
  38. package/dist/swaps/{frombtc_abstract → escrow/frombtc_abstract}/FromBtcAbs.js +15 -15
  39. package/dist/swaps/{frombtc_abstract → escrow/frombtc_abstract}/FromBtcSwapAbs.js +1 -1
  40. package/dist/swaps/{frombtcln_abstract → escrow/frombtcln_abstract}/FromBtcLnAbs.d.ts +9 -7
  41. package/dist/swaps/{frombtcln_abstract → escrow/frombtcln_abstract}/FromBtcLnAbs.js +22 -19
  42. package/dist/swaps/{frombtcln_abstract → escrow/frombtcln_abstract}/FromBtcLnSwapAbs.js +3 -3
  43. package/dist/swaps/{tobtc_abstract → escrow/tobtc_abstract}/ToBtcAbs.d.ts +4 -4
  44. package/dist/swaps/{tobtc_abstract → escrow/tobtc_abstract}/ToBtcAbs.js +14 -13
  45. package/dist/swaps/{tobtc_abstract → escrow/tobtc_abstract}/ToBtcSwapAbs.js +3 -3
  46. package/dist/swaps/{tobtcln_abstract → escrow/tobtcln_abstract}/ToBtcLnAbs.d.ts +6 -26
  47. package/dist/swaps/{tobtcln_abstract → escrow/tobtcln_abstract}/ToBtcLnAbs.js +20 -57
  48. package/dist/swaps/{tobtcln_abstract → escrow/tobtcln_abstract}/ToBtcLnSwapAbs.js +3 -3
  49. package/dist/swaps/spv_vault_swap/SpvVault.d.ts +41 -0
  50. package/dist/swaps/spv_vault_swap/SpvVault.js +111 -0
  51. package/dist/swaps/spv_vault_swap/SpvVaultSwap.d.ts +63 -0
  52. package/dist/swaps/spv_vault_swap/SpvVaultSwap.js +145 -0
  53. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.d.ts +68 -0
  54. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.js +469 -0
  55. package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +57 -0
  56. package/dist/swaps/spv_vault_swap/SpvVaults.js +369 -0
  57. package/dist/swaps/{frombtc_trusted → trusted/frombtc_trusted}/FromBtcTrusted.d.ts +10 -13
  58. package/dist/swaps/{frombtc_trusted → trusted/frombtc_trusted}/FromBtcTrusted.js +25 -30
  59. package/dist/swaps/{frombtc_trusted → trusted/frombtc_trusted}/FromBtcTrustedSwap.d.ts +9 -4
  60. package/dist/swaps/{frombtc_trusted → trusted/frombtc_trusted}/FromBtcTrustedSwap.js +15 -7
  61. package/dist/swaps/{frombtcln_trusted → trusted/frombtcln_trusted}/FromBtcLnTrusted.d.ts +12 -14
  62. package/dist/swaps/{frombtcln_trusted → trusted/frombtcln_trusted}/FromBtcLnTrusted.js +33 -35
  63. package/dist/swaps/{frombtcln_trusted → trusted/frombtcln_trusted}/FromBtcLnTrustedSwap.d.ts +9 -4
  64. package/dist/swaps/{frombtcln_trusted → trusted/frombtcln_trusted}/FromBtcLnTrustedSwap.js +17 -7
  65. package/dist/utils/Utils.d.ts +13 -5
  66. package/dist/utils/Utils.js +23 -1
  67. package/dist/wallets/IBitcoinWallet.d.ts +6 -0
  68. package/dist/wallets/ISpvVaultSigner.d.ts +7 -0
  69. package/dist/wallets/ISpvVaultSigner.js +2 -0
  70. package/dist/wallets/ISpvVaultWallet.d.ts +42 -0
  71. package/dist/wallets/ISpvVaultWallet.js +2 -0
  72. package/package.json +2 -2
  73. package/src/index.ts +21 -15
  74. package/src/plugins/IPlugin.ts +27 -19
  75. package/src/plugins/PluginManager.ts +51 -26
  76. package/src/prices/BinanceSwapPrice.ts +1 -1
  77. package/src/prices/CoinGeckoSwapPrice.ts +1 -1
  78. package/src/{swaps → prices}/ISwapPrice.ts +4 -0
  79. package/src/prices/OKXSwapPrice.ts +1 -1
  80. package/src/swaps/SwapHandler.ts +22 -205
  81. package/src/swaps/SwapHandlerSwap.ts +10 -46
  82. package/src/swaps/assertions/AmountAssertions.ts +77 -0
  83. package/src/swaps/assertions/FromBtcAmountAssertions.ts +228 -0
  84. package/src/swaps/assertions/LightningAssertions.ts +103 -0
  85. package/src/swaps/{ToBtcBaseSwapHandler.ts → assertions/ToBtcAmountAssertions.ts} +27 -142
  86. package/src/swaps/escrow/EscrowHandler.ts +179 -0
  87. package/src/swaps/escrow/EscrowHandlerSwap.ts +87 -0
  88. package/src/swaps/{FromBtcBaseSwap.ts → escrow/FromBtcBaseSwap.ts} +4 -8
  89. package/src/swaps/{FromBtcBaseSwapHandler.ts → escrow/FromBtcBaseSwapHandler.ts} +30 -190
  90. package/src/swaps/{ToBtcBaseSwap.ts → escrow/ToBtcBaseSwap.ts} +4 -5
  91. package/src/swaps/escrow/ToBtcBaseSwapHandler.ts +130 -0
  92. package/src/swaps/{frombtc_abstract → escrow/frombtc_abstract}/FromBtcAbs.ts +20 -20
  93. package/src/swaps/{frombtc_abstract → escrow/frombtc_abstract}/FromBtcSwapAbs.ts +1 -1
  94. package/src/swaps/{frombtcln_abstract → escrow/frombtcln_abstract}/FromBtcLnAbs.ts +29 -25
  95. package/src/swaps/{frombtcln_abstract → escrow/frombtcln_abstract}/FromBtcLnSwapAbs.ts +2 -2
  96. package/src/swaps/{tobtc_abstract → escrow/tobtc_abstract}/ToBtcAbs.ts +19 -18
  97. package/src/swaps/{tobtc_abstract → escrow/tobtc_abstract}/ToBtcSwapAbs.ts +2 -2
  98. package/src/swaps/{tobtcln_abstract → escrow/tobtcln_abstract}/ToBtcLnAbs.ts +26 -66
  99. package/src/swaps/{tobtcln_abstract → escrow/tobtcln_abstract}/ToBtcLnSwapAbs.ts +2 -2
  100. package/src/swaps/spv_vault_swap/SpvVault.ts +143 -0
  101. package/src/swaps/spv_vault_swap/SpvVaultSwap.ts +207 -0
  102. package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +606 -0
  103. package/src/swaps/spv_vault_swap/SpvVaults.ts +441 -0
  104. package/src/swaps/{frombtc_trusted → trusted/frombtc_trusted}/FromBtcTrusted.ts +36 -51
  105. package/src/swaps/{frombtc_trusted → trusted/frombtc_trusted}/FromBtcTrustedSwap.ts +18 -8
  106. package/src/swaps/{frombtcln_trusted → trusted/frombtcln_trusted}/FromBtcLnTrusted.ts +43 -52
  107. package/src/swaps/{frombtcln_trusted → trusted/frombtcln_trusted}/FromBtcLnTrustedSwap.ts +20 -8
  108. package/src/utils/Utils.ts +27 -1
  109. package/src/wallets/IBitcoinWallet.ts +4 -0
  110. package/src/wallets/ISpvVaultSigner.ts +11 -0
  111. package/dist/swaps/FromBtcLnBaseSwapHandler.d.ts +0 -26
  112. package/dist/swaps/FromBtcLnBaseSwapHandler.js +0 -46
  113. package/dist/swaps/ToBtcBaseSwapHandler.d.ts +0 -95
  114. package/src/swaps/FromBtcLnBaseSwapHandler.ts +0 -63
  115. /package/dist/{swaps → prices}/ISwapPrice.d.ts +0 -0
  116. /package/dist/swaps/{frombtc_abstract → escrow/frombtc_abstract}/FromBtcSwapAbs.d.ts +0 -0
  117. /package/dist/swaps/{frombtcln_abstract → escrow/frombtcln_abstract}/FromBtcLnSwapAbs.d.ts +0 -0
  118. /package/dist/swaps/{tobtc_abstract → escrow/tobtc_abstract}/ToBtcSwapAbs.d.ts +0 -0
  119. /package/dist/swaps/{tobtcln_abstract → escrow/tobtcln_abstract}/ToBtcLnSwapAbs.d.ts +0 -0
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EscrowHandler = void 0;
4
+ const SwapHandler_1 = require("../SwapHandler");
5
+ const base_1 = require("@atomiqlabs/base");
6
+ const PluginManager_1 = require("../../plugins/PluginManager");
7
+ const SwapHandlerSwap_1 = require("../SwapHandlerSwap");
8
+ class EscrowHandler extends SwapHandler_1.SwapHandler {
9
+ constructor() {
10
+ super(...arguments);
11
+ this.escrowHashMap = new Map();
12
+ this.swapLogger = {
13
+ debug: (swap, msg, ...args) => this.logger.debug(this.getIdentifier(swap) + ": " + msg, ...args),
14
+ info: (swap, msg, ...args) => this.logger.info(this.getIdentifier(swap) + ": " + msg, ...args),
15
+ warn: (swap, msg, ...args) => this.logger.warn(this.getIdentifier(swap) + ": " + msg, ...args),
16
+ error: (swap, msg, ...args) => this.logger.error(this.getIdentifier(swap) + ": " + msg, ...args)
17
+ };
18
+ }
19
+ /**
20
+ * Chain event processor
21
+ *
22
+ * @param chainIdentifier
23
+ * @param eventData
24
+ */
25
+ async processEvent(chainIdentifier, eventData) {
26
+ if (this.swapType == null)
27
+ return true;
28
+ for (let event of eventData) {
29
+ if (event instanceof base_1.InitializeEvent) {
30
+ if (event.swapType !== this.swapType)
31
+ continue;
32
+ const swap = this.getSwapByEscrowHash(chainIdentifier, event.escrowHash);
33
+ if (swap == null)
34
+ continue;
35
+ swap.txIds.init = event.meta?.txId;
36
+ if (swap.metadata != null)
37
+ swap.metadata.times.initTxReceived = Date.now();
38
+ await this.processInitializeEvent(chainIdentifier, swap, event);
39
+ }
40
+ else if (event instanceof base_1.ClaimEvent) {
41
+ const swap = this.getSwapByEscrowHash(chainIdentifier, event.escrowHash);
42
+ if (swap == null)
43
+ continue;
44
+ swap.txIds.claim = event.meta?.txId;
45
+ if (swap.metadata != null)
46
+ swap.metadata.times.claimTxReceived = Date.now();
47
+ await this.processClaimEvent(chainIdentifier, swap, event);
48
+ }
49
+ else if (event instanceof base_1.RefundEvent) {
50
+ const swap = this.getSwapByEscrowHash(chainIdentifier, event.escrowHash);
51
+ if (swap == null)
52
+ continue;
53
+ swap.txIds.refund = event.meta?.txId;
54
+ if (swap.metadata != null)
55
+ swap.metadata.times.refundTxReceived = Date.now();
56
+ await this.processRefundEvent(chainIdentifier, swap, event);
57
+ }
58
+ }
59
+ return true;
60
+ }
61
+ /**
62
+ * Initializes chain events subscription
63
+ */
64
+ subscribeToEvents() {
65
+ for (let key in this.chains.chains) {
66
+ this.chains.chains[key].chainEvents.registerListener((events) => this.processEvent(key, events));
67
+ }
68
+ this.logger.info("SC: Events: subscribed to smartchain events");
69
+ }
70
+ async loadData(ctor) {
71
+ await super.loadData(ctor);
72
+ for (let { obj: swap, hash, sequence } of await this.storageManager.query([])) {
73
+ this.saveSwapToEscrowHashMap(swap);
74
+ }
75
+ }
76
+ async removeSwapData(hashOrSwap, sequenceOrUltimateState) {
77
+ let swap;
78
+ if (typeof (hashOrSwap) === "string") {
79
+ if (typeof (sequenceOrUltimateState) !== "bigint")
80
+ throw new Error("Sequence must be a BN instance!");
81
+ swap = await this.storageManager.getData(hashOrSwap, sequenceOrUltimateState);
82
+ }
83
+ else {
84
+ swap = hashOrSwap;
85
+ if (sequenceOrUltimateState != null && typeof (sequenceOrUltimateState) !== "bigint")
86
+ await swap.setState(sequenceOrUltimateState);
87
+ }
88
+ if (swap != null)
89
+ await PluginManager_1.PluginManager.swapRemove(swap);
90
+ this.swapLogger.debug(swap, "removeSwapData(): removing swap final state: " + swap.state);
91
+ this.removeSwapFromEscrowHashMap(swap);
92
+ await this.storageManager.removeData(swap.getIdentifierHash(), swap.getSequence());
93
+ }
94
+ async saveSwapData(swap) {
95
+ this.saveSwapToEscrowHashMap(swap);
96
+ return super.saveSwapData(swap);
97
+ }
98
+ saveSwapToEscrowHashMap(swap) {
99
+ if (swap.data != null)
100
+ this.escrowHashMap.set(swap.chainIdentifier + "_" + swap.getEscrowHash(), swap);
101
+ }
102
+ removeSwapFromEscrowHashMap(swap) {
103
+ if (swap.data != null)
104
+ this.escrowHashMap.delete(swap.chainIdentifier + "_" + swap.getEscrowHash());
105
+ }
106
+ getSwapByEscrowHash(chainIdentifier, escrowHash) {
107
+ return this.escrowHashMap.get(chainIdentifier + "_" + escrowHash);
108
+ }
109
+ getIdentifierFromEvent(event) {
110
+ if (event instanceof base_1.SwapEvent) {
111
+ const foundSwap = this.escrowHashMap.get(event.escrowHash);
112
+ if (foundSwap != null) {
113
+ return foundSwap.getIdentifier();
114
+ }
115
+ return "UNKNOWN_" + event.escrowHash;
116
+ }
117
+ }
118
+ getIdentifierFromSwapData(swapData) {
119
+ if (swapData.getSequence == null)
120
+ return swapData.getClaimHash();
121
+ return swapData.getClaimHash() + "_" + swapData.getSequence().toString(16);
122
+ }
123
+ getIdentifier(swap) {
124
+ if (swap instanceof SwapHandlerSwap_1.SwapHandlerSwap) {
125
+ return swap.getIdentifier();
126
+ }
127
+ if (swap instanceof base_1.ChainEvent) {
128
+ return this.getIdentifierFromEvent(swap);
129
+ }
130
+ return this.getIdentifierFromSwapData(swap);
131
+ }
132
+ /**
133
+ * Starts a pre-fetch for signature data
134
+ *
135
+ * @param chainIdentifier
136
+ * @param abortController
137
+ * @param responseStream
138
+ */
139
+ getSignDataPrefetch(chainIdentifier, abortController, responseStream) {
140
+ const { swapContract } = this.getChain(chainIdentifier);
141
+ let signDataPrefetchPromise = swapContract.preFetchBlockDataForSignatures != null ? swapContract.preFetchBlockDataForSignatures().catch(e => {
142
+ this.logger.error("getSignDataPrefetch(): signDataPrefetch: ", e);
143
+ abortController.abort(e);
144
+ return null;
145
+ }) : null;
146
+ if (signDataPrefetchPromise != null && responseStream != null) {
147
+ signDataPrefetchPromise = signDataPrefetchPromise.then(val => val == null || abortController.signal.aborted ? null : responseStream.writeParams({
148
+ signDataPrefetch: val
149
+ }).then(() => val).catch(e => {
150
+ this.logger.error("getSignDataPrefetch(): signDataPreFetch: error when sending sign data to the client: ", e);
151
+ abortController.abort(e);
152
+ return null;
153
+ }));
154
+ }
155
+ return signDataPrefetchPromise;
156
+ }
157
+ }
158
+ exports.EscrowHandler = EscrowHandler;
@@ -0,0 +1,35 @@
1
+ import { SwapData } from "@atomiqlabs/base";
2
+ import { SwapHandlerSwap } from "../SwapHandlerSwap";
3
+ export declare abstract class EscrowHandlerSwap<T extends SwapData = SwapData, S = any> extends SwapHandlerSwap<S> {
4
+ data: T;
5
+ txIds: {
6
+ init?: string;
7
+ claim?: string;
8
+ refund?: string;
9
+ };
10
+ prefix: string;
11
+ timeout: string;
12
+ signature: string;
13
+ feeRate: string;
14
+ protected constructor(chainIdentifier: string, swapFee: bigint, swapFeeInToken: bigint);
15
+ protected constructor(obj: any);
16
+ serialize(): any;
17
+ /**
18
+ * Returns the escrow hash - i.e. hash of the escrow data
19
+ */
20
+ getEscrowHash(): string;
21
+ /**
22
+ * Returns the claim data hash - i.e. hash passed to the claim handler
23
+ */
24
+ getClaimHash(): string;
25
+ /**
26
+ * Returns the identification hash of the swap, usually claim data hash, but can be overriden, e.g. for
27
+ * lightning swaps the identifier hash is used instead of claim data hash
28
+ */
29
+ getIdentifierHash(): string;
30
+ getSequence(): bigint | null;
31
+ /**
32
+ * Returns the smart chain token used for the swap
33
+ */
34
+ getToken(): string;
35
+ }
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EscrowHandlerSwap = void 0;
4
+ const base_1 = require("@atomiqlabs/base");
5
+ const SwapHandlerSwap_1 = require("../SwapHandlerSwap");
6
+ function objectBigIntsToString(obj) {
7
+ for (let key in obj) {
8
+ if (typeof obj[key] === "bigint")
9
+ obj[key] = obj[key].toString(10);
10
+ if (typeof obj[key] === "object")
11
+ objectBigIntsToString(obj[key]);
12
+ }
13
+ return obj;
14
+ }
15
+ class EscrowHandlerSwap extends SwapHandlerSwap_1.SwapHandlerSwap {
16
+ constructor(obj, swapFee, swapFeeInToken) {
17
+ super(obj, swapFee, swapFeeInToken);
18
+ this.txIds = {};
19
+ if (typeof (obj) === "string" && typeof (swapFee) === "bigint" && typeof (swapFeeInToken) === "bigint") {
20
+ return;
21
+ }
22
+ else {
23
+ this.data = obj.data == null ? null : base_1.SwapData.deserialize(obj.data);
24
+ this.prefix = obj.prefix;
25
+ this.timeout = obj.timeout;
26
+ this.signature = obj.signature;
27
+ this.feeRate = obj.feeRate;
28
+ }
29
+ }
30
+ serialize() {
31
+ return {
32
+ ...super.serialize(),
33
+ data: this.data == null ? null : this.data.serialize(),
34
+ prefix: this.prefix,
35
+ timeout: this.timeout,
36
+ signature: this.signature,
37
+ feeRate: this.feeRate
38
+ };
39
+ }
40
+ /**
41
+ * Returns the escrow hash - i.e. hash of the escrow data
42
+ */
43
+ getEscrowHash() {
44
+ return this.data.getEscrowHash();
45
+ }
46
+ /**
47
+ * Returns the claim data hash - i.e. hash passed to the claim handler
48
+ */
49
+ getClaimHash() {
50
+ return this.data.getClaimHash();
51
+ }
52
+ /**
53
+ * Returns the identification hash of the swap, usually claim data hash, but can be overriden, e.g. for
54
+ * lightning swaps the identifier hash is used instead of claim data hash
55
+ */
56
+ getIdentifierHash() {
57
+ return this.getClaimHash();
58
+ }
59
+ getSequence() {
60
+ return this.data?.getSequence == null ? null : this.data.getSequence();
61
+ }
62
+ /**
63
+ * Returns the smart chain token used for the swap
64
+ */
65
+ getToken() {
66
+ return this.data?.getToken();
67
+ }
68
+ }
69
+ exports.EscrowHandlerSwap = EscrowHandlerSwap;
@@ -1,10 +1,9 @@
1
+ import { EscrowHandlerSwap } from "./EscrowHandlerSwap";
1
2
  import { SwapData } from "@atomiqlabs/base";
2
- import { SwapHandlerSwap } from "./SwapHandlerSwap";
3
- export declare abstract class FromBtcBaseSwap<T extends SwapData, S = any> extends SwapHandlerSwap<T, S> {
3
+ export declare abstract class FromBtcBaseSwap<T extends SwapData = SwapData, S = any> extends EscrowHandlerSwap<T, S> {
4
4
  amount: bigint;
5
5
  protected constructor(chainIdentifier: string, amount: bigint, swapFee: bigint, swapFeeInToken: bigint);
6
6
  protected constructor(obj: any);
7
- getInputAmount(): bigint;
8
7
  getTotalInputAmount(): bigint;
9
8
  getOutputAmount(): bigint;
10
9
  getSwapFee(): {
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FromBtcBaseSwap = void 0;
4
- const SwapHandlerSwap_1 = require("./SwapHandlerSwap");
5
- const Utils_1 = require("../utils/Utils");
6
- class FromBtcBaseSwap extends SwapHandlerSwap_1.SwapHandlerSwap {
4
+ const Utils_1 = require("../../utils/Utils");
5
+ const EscrowHandlerSwap_1 = require("./EscrowHandlerSwap");
6
+ class FromBtcBaseSwap extends EscrowHandlerSwap_1.EscrowHandlerSwap {
7
7
  constructor(obj, amount, swapFee, swapFeeInToken) {
8
8
  super(obj, swapFee, swapFeeInToken);
9
9
  if (typeof (obj) === "string" && typeof (amount) === "bigint" && typeof (swapFee) === "bigint" && typeof (swapFeeInToken) === "bigint") {
@@ -14,14 +14,11 @@ class FromBtcBaseSwap extends SwapHandlerSwap_1.SwapHandlerSwap {
14
14
  }
15
15
  }
16
16
  ;
17
- getInputAmount() {
18
- return this.getTotalInputAmount() - this.getSwapFee().inInputToken;
19
- }
20
17
  getTotalInputAmount() {
21
18
  return this.amount;
22
19
  }
23
20
  getOutputAmount() {
24
- return this.data.getAmount();
21
+ return this.data?.getAmount();
25
22
  }
26
23
  getSwapFee() {
27
24
  return { inInputToken: this.swapFee, inOutputToken: this.swapFeeInToken };
@@ -1,16 +1,19 @@
1
- import { SwapHandlerSwap } from "./SwapHandlerSwap";
2
1
  import { SwapData } from "@atomiqlabs/base";
3
- import { RequestData, SwapBaseConfig, SwapHandler } from "./SwapHandler";
4
- import { IParamReader } from "../utils/paramcoders/IParamReader";
5
- import { FromBtcLnRequestType } from "./frombtcln_abstract/FromBtcLnAbs";
6
- import { FromBtcRequestType } from "./frombtc_abstract/FromBtcAbs";
2
+ import { MultichainData, SwapBaseConfig } from "../SwapHandler";
3
+ import { IParamReader } from "../../utils/paramcoders/IParamReader";
7
4
  import { Request } from "express";
8
- import { FromBtcLnTrustedRequestType } from "./frombtcln_trusted/FromBtcLnTrusted";
5
+ import { EscrowHandler } from "./EscrowHandler";
6
+ import { FromBtcBaseSwap } from "./FromBtcBaseSwap";
7
+ import { FromBtcAmountAssertions } from "../assertions/FromBtcAmountAssertions";
8
+ import { IIntermediaryStorage } from "../../storage/IIntermediaryStorage";
9
+ import { ISwapPrice } from "../../prices/ISwapPrice";
9
10
  export type FromBtcBaseConfig = SwapBaseConfig & {
10
11
  securityDepositAPY: number;
11
12
  };
12
- export declare abstract class FromBtcBaseSwapHandler<V extends SwapHandlerSwap<SwapData, S>, S> extends SwapHandler<V, S> {
13
+ export declare abstract class FromBtcBaseSwapHandler<V extends FromBtcBaseSwap<SwapData, S>, S> extends EscrowHandler<V, S> {
13
14
  abstract config: FromBtcBaseConfig;
15
+ readonly AmountAssertions: FromBtcAmountAssertions;
16
+ constructor(storageDirectory: IIntermediaryStorage<V>, path: string, chainsData: MultichainData, swapPricing: ISwapPrice, config: FromBtcBaseConfig);
14
17
  /**
15
18
  * Starts a pre-fetch for swap price & security deposit price
16
19
  *
@@ -60,48 +63,6 @@ export declare abstract class FromBtcBaseSwapHandler<V extends SwapHandlerSwap<S
60
63
  * @throws {DefinedRuntimeError} will throw an error if there are not enough funds in the vault
61
64
  */
62
65
  protected checkAllowedDepositToken(chainIdentifier: string, depositToken: string): void;
63
- /**
64
- * Checks minimums/maximums, calculates the fee & total amount
65
- *
66
- * @param request
67
- * @param requestedAmount
68
- * @param useToken
69
- * @throws {DefinedRuntimeError} will throw an error if the amount is outside minimum/maximum bounds
70
- */
71
- protected preCheckAmounts(request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType>, requestedAmount: {
72
- input: boolean;
73
- amount: bigint;
74
- }, useToken: string): Promise<{
75
- baseFee: bigint;
76
- feePPM: bigint;
77
- securityDepositApyPPM?: bigint;
78
- securityDepositBaseMultiplierPPM?: bigint;
79
- }>;
80
- /**
81
- * Checks minimums/maximums, calculates the fee & total amount
82
- *
83
- * @param request
84
- * @param requestedAmount
85
- * @param fees
86
- * @param useToken
87
- * @param signal
88
- * @param pricePrefetchPromise
89
- * @throws {DefinedRuntimeError} will throw an error if the amount is outside minimum/maximum bounds
90
- */
91
- protected checkFromBtcAmount(request: RequestData<FromBtcLnRequestType | FromBtcRequestType | FromBtcLnTrustedRequestType>, requestedAmount: {
92
- input: boolean;
93
- amount: bigint;
94
- }, fees: {
95
- baseFee: bigint;
96
- feePPM: bigint;
97
- }, useToken: string, signal: AbortSignal, pricePrefetchPromise?: Promise<bigint>): Promise<{
98
- amountBD: bigint;
99
- swapFee: bigint;
100
- swapFeeInToken: bigint;
101
- totalInToken: bigint;
102
- securityDepositApyPPM?: bigint;
103
- securityDepositBaseMultiplierPPM?: bigint;
104
- }>;
105
66
  /**
106
67
  * Signs the created swap
107
68
  *
@@ -1,12 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FromBtcBaseSwapHandler = void 0;
4
- const SwapHandler_1 = require("./SwapHandler");
5
- const SchemaVerifier_1 = require("../utils/paramcoders/SchemaVerifier");
6
- const PluginManager_1 = require("../plugins/PluginManager");
7
- const IPlugin_1 = require("../plugins/IPlugin");
4
+ const SchemaVerifier_1 = require("../../utils/paramcoders/SchemaVerifier");
5
+ const EscrowHandler_1 = require("./EscrowHandler");
6
+ const FromBtcAmountAssertions_1 = require("../assertions/FromBtcAmountAssertions");
8
7
  const secondsInYear = BigInt(365 * 24 * 60 * 60);
9
- class FromBtcBaseSwapHandler extends SwapHandler_1.SwapHandler {
8
+ class FromBtcBaseSwapHandler extends EscrowHandler_1.EscrowHandler {
9
+ constructor(storageDirectory, path, chainsData, swapPricing, config) {
10
+ super(storageDirectory, path, chainsData, swapPricing);
11
+ this.AmountAssertions = new FromBtcAmountAssertions_1.FromBtcAmountAssertions(config, swapPricing);
12
+ }
10
13
  /**
11
14
  * Starts a pre-fetch for swap price & security deposit price
12
15
  *
@@ -21,15 +24,15 @@ class FromBtcBaseSwapHandler extends SwapHandler_1.SwapHandler {
21
24
  abortController.abort(e);
22
25
  return null;
23
26
  });
24
- const { swapContract } = this.getChain(chainIdentifier);
25
- const gasTokenPricePrefetchPromise = useToken.toString() === swapContract.getNativeCurrencyAddress().toString() ?
27
+ const { chainInterface } = this.getChain(chainIdentifier);
28
+ const gasTokenPricePrefetchPromise = useToken.toString() === chainInterface.getNativeCurrencyAddress().toString() ?
26
29
  pricePrefetchPromise :
27
- this.swapPricing.preFetchPrice(swapContract.getNativeCurrencyAddress(), chainIdentifier).catch(e => {
30
+ this.swapPricing.preFetchPrice(chainInterface.getNativeCurrencyAddress(), chainIdentifier).catch(e => {
28
31
  this.logger.error("getFromBtcPricePrefetches(): gasTokenPricePrefetchPromise error: ", e);
29
32
  abortController.abort(e);
30
33
  return null;
31
34
  });
32
- const depositTokenPricePrefetchPromise = depositToken === swapContract.getNativeCurrencyAddress() ?
35
+ const depositTokenPricePrefetchPromise = depositToken === chainInterface.getNativeCurrencyAddress() ?
33
36
  gasTokenPricePrefetchPromise :
34
37
  this.swapPricing.preFetchPrice(depositToken, chainIdentifier).catch(e => {
35
38
  this.logger.error("getFromBtcPricePrefetches(): depositTokenPricePrefetchPromise error: ", e);
@@ -50,9 +53,9 @@ class FromBtcBaseSwapHandler extends SwapHandler_1.SwapHandler {
50
53
  */
51
54
  async getBaseSecurityDepositPrefetch(chainIdentifier, dummySwapData, depositToken, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise, abortController) {
52
55
  //Solana workaround
53
- const { swapContract } = this.getChain(chainIdentifier);
56
+ const { swapContract, chainInterface } = this.getChain(chainIdentifier);
54
57
  let feeResult;
55
- const gasToken = swapContract.getNativeCurrencyAddress();
58
+ const gasToken = chainInterface.getNativeCurrencyAddress();
56
59
  if (swapContract.getRawRefundFee != null) {
57
60
  try {
58
61
  feeResult = await swapContract.getRawRefundFee(dummySwapData);
@@ -124,9 +127,9 @@ class FromBtcBaseSwapHandler extends SwapHandler_1.SwapHandler {
124
127
  * @throws {DefinedRuntimeError} will throw an error if there are not enough funds in the vault
125
128
  */
126
129
  checkAllowedDepositToken(chainIdentifier, depositToken) {
127
- const { swapContract, allowedDepositTokens } = this.getChain(chainIdentifier);
130
+ const { chainInterface, allowedDepositTokens } = this.getChain(chainIdentifier);
128
131
  if (allowedDepositTokens == null) {
129
- if (depositToken !== swapContract.getNativeCurrencyAddress())
132
+ if (depositToken !== chainInterface.getNativeCurrencyAddress())
130
133
  throw {
131
134
  code: 20190,
132
135
  msg: "Unsupported deposit token"
@@ -140,130 +143,6 @@ class FromBtcBaseSwapHandler extends SwapHandler_1.SwapHandler {
140
143
  };
141
144
  }
142
145
  }
143
- /**
144
- * Checks minimums/maximums, calculates the fee & total amount
145
- *
146
- * @param request
147
- * @param requestedAmount
148
- * @param useToken
149
- * @throws {DefinedRuntimeError} will throw an error if the amount is outside minimum/maximum bounds
150
- */
151
- async preCheckAmounts(request, requestedAmount, useToken) {
152
- const res = await PluginManager_1.PluginManager.onHandlePreFromBtcQuote(request, requestedAmount, request.chainIdentifier, useToken, { minInBtc: this.config.min, maxInBtc: this.config.max }, { baseFeeInBtc: this.config.baseFee, feePPM: this.config.feePPM });
153
- if (res != null) {
154
- this.handlePluginErrorResponses(res);
155
- if ((0, IPlugin_1.isQuoteSetFees)(res)) {
156
- return {
157
- baseFee: res.baseFee || this.config.baseFee,
158
- feePPM: res.feePPM || this.config.feePPM,
159
- securityDepositApyPPM: res.securityDepositApyPPM,
160
- securityDepositBaseMultiplierPPM: res.securityDepositBaseMultiplierPPM
161
- };
162
- }
163
- }
164
- if (requestedAmount.input)
165
- this.checkBtcAmountInBounds(requestedAmount.amount);
166
- return {
167
- baseFee: this.config.baseFee,
168
- feePPM: this.config.feePPM
169
- };
170
- }
171
- /**
172
- * Checks minimums/maximums, calculates the fee & total amount
173
- *
174
- * @param request
175
- * @param requestedAmount
176
- * @param fees
177
- * @param useToken
178
- * @param signal
179
- * @param pricePrefetchPromise
180
- * @throws {DefinedRuntimeError} will throw an error if the amount is outside minimum/maximum bounds
181
- */
182
- async checkFromBtcAmount(request, requestedAmount, fees, useToken, signal, pricePrefetchPromise = Promise.resolve(null)) {
183
- const chainIdentifier = request.chainIdentifier;
184
- let securityDepositApyPPM;
185
- let securityDepositBaseMultiplierPPM;
186
- const res = await PluginManager_1.PluginManager.onHandlePostFromBtcQuote(request, requestedAmount, chainIdentifier, useToken, { minInBtc: this.config.min, maxInBtc: this.config.max }, { baseFeeInBtc: fees.baseFee, feePPM: fees.feePPM }, pricePrefetchPromise);
187
- signal.throwIfAborted();
188
- if (res != null) {
189
- this.handlePluginErrorResponses(res);
190
- if ((0, IPlugin_1.isQuoteSetFees)(res)) {
191
- if (res.baseFee != null)
192
- fees.baseFee = res.baseFee;
193
- if (res.feePPM != null)
194
- fees.feePPM = res.feePPM;
195
- if (res.securityDepositApyPPM != null)
196
- securityDepositApyPPM = res.securityDepositApyPPM;
197
- if (res.securityDepositBaseMultiplierPPM != null)
198
- securityDepositBaseMultiplierPPM = res.securityDepositBaseMultiplierPPM;
199
- }
200
- if ((0, IPlugin_1.isPluginQuote)(res)) {
201
- if (!requestedAmount.input) {
202
- return {
203
- amountBD: res.amount.amount + res.swapFee.inInputTokens,
204
- swapFee: res.swapFee.inInputTokens,
205
- swapFeeInToken: res.swapFee.inOutputTokens,
206
- totalInToken: requestedAmount.amount
207
- };
208
- }
209
- else {
210
- return {
211
- amountBD: requestedAmount.amount,
212
- swapFee: res.swapFee.inInputTokens,
213
- swapFeeInToken: res.swapFee.inOutputTokens,
214
- totalInToken: res.amount.amount
215
- };
216
- }
217
- }
218
- }
219
- let amountBD;
220
- if (!requestedAmount.input) {
221
- amountBD = await this.swapPricing.getToBtcSwapAmount(requestedAmount.amount, useToken, chainIdentifier, true, pricePrefetchPromise);
222
- signal.throwIfAborted();
223
- // amt = (amt+base_fee)/(1-fee)
224
- amountBD = (amountBD + fees.baseFee) * 1000000n / (1000000n - fees.feePPM);
225
- const tooLow = amountBD < (this.config.min * 95n / 100n);
226
- const tooHigh = amountBD > (this.config.max * 105n / 100n);
227
- if (tooLow || tooHigh) {
228
- const adjustedMin = this.config.min * (1000000n - fees.feePPM) / (1000000n - fees.baseFee);
229
- const adjustedMax = this.config.max * (1000000n - fees.feePPM) / (1000000n - fees.baseFee);
230
- const minIn = await this.swapPricing.getFromBtcSwapAmount(adjustedMin, useToken, chainIdentifier, null, pricePrefetchPromise);
231
- const maxIn = await this.swapPricing.getFromBtcSwapAmount(adjustedMax, useToken, chainIdentifier, null, pricePrefetchPromise);
232
- throw {
233
- code: tooLow ? 20003 : 20004,
234
- msg: tooLow ? "Amount too low!" : "Amount too high!",
235
- data: {
236
- min: minIn.toString(10),
237
- max: maxIn.toString(10)
238
- }
239
- };
240
- }
241
- }
242
- else {
243
- amountBD = requestedAmount.amount;
244
- this.checkBtcAmountInBounds(amountBD);
245
- }
246
- const swapFee = fees.baseFee + (amountBD * fees.feePPM / 1000000n);
247
- const swapFeeInToken = await this.swapPricing.getFromBtcSwapAmount(swapFee, useToken, chainIdentifier, true, pricePrefetchPromise);
248
- signal.throwIfAborted();
249
- let totalInToken;
250
- if (!requestedAmount.input) {
251
- totalInToken = requestedAmount.amount;
252
- }
253
- else {
254
- const amountInToken = await this.swapPricing.getFromBtcSwapAmount(requestedAmount.amount, useToken, chainIdentifier, null, pricePrefetchPromise);
255
- totalInToken = amountInToken - swapFeeInToken;
256
- signal.throwIfAborted();
257
- }
258
- return {
259
- amountBD,
260
- swapFee,
261
- swapFeeInToken,
262
- totalInToken,
263
- securityDepositApyPPM,
264
- securityDepositBaseMultiplierPPM
265
- };
266
- }
267
146
  /**
268
147
  * Signs the created swap
269
148
  *
@@ -1,6 +1,6 @@
1
- import { SwapHandlerSwap } from "./SwapHandlerSwap";
2
1
  import { SwapData } from "@atomiqlabs/base";
3
- export declare abstract class ToBtcBaseSwap<T extends SwapData = SwapData, S = any> extends SwapHandlerSwap<T, S> {
2
+ import { EscrowHandlerSwap } from "./EscrowHandlerSwap";
3
+ export declare abstract class ToBtcBaseSwap<T extends SwapData = SwapData, S = any> extends EscrowHandlerSwap<T, S> {
4
4
  amount: bigint;
5
5
  quotedNetworkFee: bigint;
6
6
  readonly quotedNetworkFeeInToken: bigint;
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ToBtcBaseSwap = void 0;
4
- const SwapHandlerSwap_1 = require("./SwapHandlerSwap");
5
- const Utils_1 = require("../utils/Utils");
6
- class ToBtcBaseSwap extends SwapHandlerSwap_1.SwapHandlerSwap {
4
+ const Utils_1 = require("../../utils/Utils");
5
+ const EscrowHandlerSwap_1 = require("./EscrowHandlerSwap");
6
+ class ToBtcBaseSwap extends EscrowHandlerSwap_1.EscrowHandlerSwap {
7
7
  constructor(obj, amount, swapFee, swapFeeInToken, quotedNetworkFee, quotedNetworkFeeInToken) {
8
8
  if (typeof (obj) === "string" && typeof (amount) === "bigint" && typeof (swapFee) === "bigint" && typeof (swapFeeInToken) === "bigint" &&
9
9
  typeof (quotedNetworkFee) === "bigint" && typeof (quotedNetworkFeeInToken) === "bigint") {
@@ -38,7 +38,7 @@ class ToBtcBaseSwap extends SwapHandlerSwap_1.SwapHandlerSwap {
38
38
  }
39
39
  }
40
40
  getInputAmount() {
41
- return this.data.getAmount() - this.getSwapFee().inInputToken - this.getQuotedNetworkFee().inInputToken;
41
+ return this.getTotalInputAmount() - this.getSwapFee().inInputToken - this.getQuotedNetworkFee().inInputToken;
42
42
  }
43
43
  getTotalInputAmount() {
44
44
  return this.data.getAmount();
@@ -0,0 +1,53 @@
1
+ import { MultichainData, SwapBaseConfig } from "../SwapHandler";
2
+ import { SwapData } from "@atomiqlabs/base";
3
+ import { ServerParamEncoder } from "../../utils/paramcoders/server/ServerParamEncoder";
4
+ import { IParamReader } from "../../utils/paramcoders/IParamReader";
5
+ import { Request } from "express";
6
+ import { ToBtcBaseSwap } from "./ToBtcBaseSwap";
7
+ import { EscrowHandler } from "./EscrowHandler";
8
+ import { ToBtcAmountAssertions } from "../assertions/ToBtcAmountAssertions";
9
+ import { IIntermediaryStorage } from "../../storage/IIntermediaryStorage";
10
+ import { ISwapPrice } from "../../prices/ISwapPrice";
11
+ export type ToBtcBaseConfig = SwapBaseConfig & {
12
+ gracePeriod: bigint;
13
+ refundAuthorizationTimeout: number;
14
+ };
15
+ export declare abstract class ToBtcBaseSwapHandler<V extends ToBtcBaseSwap<SwapData, S>, S> extends EscrowHandler<V, S> {
16
+ readonly AmountAssertions: ToBtcAmountAssertions;
17
+ readonly pdaExistsForToken: {
18
+ [chainIdentifier: string]: {
19
+ [token: string]: boolean;
20
+ };
21
+ };
22
+ constructor(storageDirectory: IIntermediaryStorage<V>, path: string, chainsData: MultichainData, swapPricing: ISwapPrice, config: ToBtcBaseConfig);
23
+ protected checkVaultInitialized(chainIdentifier: string, token: string): Promise<void>;
24
+ /**
25
+ * Starts pre-fetches for swap pricing & signature data
26
+ *
27
+ * @param chainIdentifier
28
+ * @param token
29
+ * @param responseStream
30
+ * @param abortController
31
+ */
32
+ protected getToBtcPrefetches(chainIdentifier: string, token: string, responseStream: ServerParamEncoder, abortController: AbortController): {
33
+ pricePrefetchPromise?: Promise<bigint>;
34
+ signDataPrefetchPromise?: Promise<any>;
35
+ };
36
+ /**
37
+ * Signs the created swap
38
+ *
39
+ * @param chainIdentifier
40
+ * @param swapObject
41
+ * @param req
42
+ * @param abortSignal
43
+ * @param signDataPrefetchPromise
44
+ */
45
+ protected getToBtcSignatureData(chainIdentifier: string, swapObject: SwapData, req: Request & {
46
+ paramReader: IParamReader;
47
+ }, abortSignal: AbortSignal, signDataPrefetchPromise?: Promise<any>): Promise<{
48
+ prefix: string;
49
+ timeout: string;
50
+ signature: string;
51
+ feeRate: string;
52
+ }>;
53
+ }