@atomiqlabs/lp-lib 14.0.0-dev.21 → 14.0.0-dev.24
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.
- package/LICENSE +201 -201
- package/dist/fees/IBtcFeeEstimator.d.ts +3 -3
- package/dist/fees/IBtcFeeEstimator.js +2 -2
- package/dist/index.d.ts +42 -42
- package/dist/index.js +58 -58
- package/dist/info/InfoHandler.d.ts +17 -17
- package/dist/info/InfoHandler.js +61 -61
- package/dist/plugins/IPlugin.d.ts +143 -143
- package/dist/plugins/IPlugin.js +34 -34
- package/dist/plugins/PluginManager.d.ts +112 -112
- package/dist/plugins/PluginManager.js +259 -259
- package/dist/prices/BinanceSwapPrice.d.ts +26 -26
- package/dist/prices/BinanceSwapPrice.js +92 -92
- package/dist/prices/CoinGeckoSwapPrice.d.ts +30 -30
- package/dist/prices/CoinGeckoSwapPrice.js +64 -64
- package/dist/prices/ISwapPrice.d.ts +43 -43
- package/dist/prices/ISwapPrice.js +55 -55
- package/dist/prices/OKXSwapPrice.d.ts +26 -26
- package/dist/prices/OKXSwapPrice.js +92 -92
- package/dist/storage/IIntermediaryStorage.d.ts +18 -18
- package/dist/storage/IIntermediaryStorage.js +2 -2
- package/dist/storagemanager/IntermediaryStorageManager.d.ts +19 -19
- package/dist/storagemanager/IntermediaryStorageManager.js +111 -111
- package/dist/storagemanager/StorageManager.d.ts +13 -13
- package/dist/storagemanager/StorageManager.js +64 -64
- package/dist/swaps/SwapHandler.d.ts +153 -153
- package/dist/swaps/SwapHandler.js +160 -160
- package/dist/swaps/SwapHandlerSwap.d.ts +79 -79
- package/dist/swaps/SwapHandlerSwap.js +78 -78
- package/dist/swaps/assertions/AmountAssertions.d.ts +28 -28
- package/dist/swaps/assertions/AmountAssertions.js +72 -72
- package/dist/swaps/assertions/FromBtcAmountAssertions.d.ts +76 -76
- package/dist/swaps/assertions/FromBtcAmountAssertions.js +180 -180
- package/dist/swaps/assertions/LightningAssertions.d.ts +44 -44
- package/dist/swaps/assertions/LightningAssertions.js +86 -86
- package/dist/swaps/assertions/ToBtcAmountAssertions.d.ts +53 -53
- package/dist/swaps/assertions/ToBtcAmountAssertions.js +150 -150
- package/dist/swaps/escrow/EscrowHandler.d.ts +51 -51
- package/dist/swaps/escrow/EscrowHandler.js +158 -158
- package/dist/swaps/escrow/EscrowHandlerSwap.d.ts +35 -35
- package/dist/swaps/escrow/EscrowHandlerSwap.js +69 -69
- package/dist/swaps/escrow/FromBtcBaseSwap.d.ts +14 -14
- package/dist/swaps/escrow/FromBtcBaseSwap.js +32 -32
- package/dist/swaps/escrow/FromBtcBaseSwapHandler.d.ts +102 -102
- package/dist/swaps/escrow/FromBtcBaseSwapHandler.js +210 -210
- package/dist/swaps/escrow/ToBtcBaseSwap.d.ts +36 -36
- package/dist/swaps/escrow/ToBtcBaseSwap.js +67 -67
- package/dist/swaps/escrow/ToBtcBaseSwapHandler.d.ts +53 -53
- package/dist/swaps/escrow/ToBtcBaseSwapHandler.js +81 -81
- package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.d.ts +83 -83
- package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.js +318 -318
- package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.d.ts +21 -21
- package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.js +50 -50
- package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.d.ts +107 -107
- package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.js +675 -675
- package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +33 -33
- package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.js +91 -91
- package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.d.ts +111 -111
- package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.js +684 -684
- package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.d.ts +55 -55
- package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.js +120 -120
- package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.d.ts +171 -171
- package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.js +706 -706
- package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.d.ts +26 -26
- package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.js +62 -62
- package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.d.ts +177 -177
- package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.js +863 -863
- package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +24 -24
- package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.js +58 -58
- package/dist/swaps/spv_vault_swap/SpvVault.d.ts +40 -41
- package/dist/swaps/spv_vault_swap/SpvVault.js +111 -111
- package/dist/swaps/spv_vault_swap/SpvVaultSwap.d.ts +67 -67
- package/dist/swaps/spv_vault_swap/SpvVaultSwap.js +158 -158
- package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.d.ts +68 -68
- package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.js +492 -492
- package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +52 -52
- package/dist/swaps/spv_vault_swap/SpvVaults.js +394 -364
- package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.d.ts +51 -51
- package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.js +650 -650
- package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.d.ts +52 -52
- package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.js +118 -118
- package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.d.ts +76 -76
- package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.js +494 -494
- package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.d.ts +34 -34
- package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.js +81 -81
- package/dist/utils/BitcoinUtils.d.ts +2 -2
- package/dist/utils/BitcoinUtils.js +45 -45
- package/dist/utils/Utils.d.ts +29 -29
- package/dist/utils/Utils.js +89 -89
- package/dist/utils/paramcoders/IParamReader.d.ts +5 -5
- package/dist/utils/paramcoders/IParamReader.js +2 -2
- package/dist/utils/paramcoders/IParamWriter.d.ts +4 -4
- package/dist/utils/paramcoders/IParamWriter.js +2 -2
- package/dist/utils/paramcoders/LegacyParamEncoder.d.ts +10 -10
- package/dist/utils/paramcoders/LegacyParamEncoder.js +22 -22
- package/dist/utils/paramcoders/ParamDecoder.d.ts +25 -25
- package/dist/utils/paramcoders/ParamDecoder.js +222 -222
- package/dist/utils/paramcoders/ParamEncoder.d.ts +9 -9
- package/dist/utils/paramcoders/ParamEncoder.js +22 -22
- package/dist/utils/paramcoders/SchemaVerifier.d.ts +21 -21
- package/dist/utils/paramcoders/SchemaVerifier.js +84 -84
- package/dist/utils/paramcoders/server/ServerParamDecoder.d.ts +8 -8
- package/dist/utils/paramcoders/server/ServerParamDecoder.js +107 -107
- package/dist/utils/paramcoders/server/ServerParamEncoder.d.ts +11 -11
- package/dist/utils/paramcoders/server/ServerParamEncoder.js +65 -65
- package/dist/wallets/IBitcoinWallet.d.ts +67 -67
- package/dist/wallets/IBitcoinWallet.js +2 -2
- package/dist/wallets/ILightningWallet.d.ts +117 -117
- package/dist/wallets/ILightningWallet.js +37 -37
- package/dist/wallets/ISpvVaultSigner.d.ts +7 -7
- package/dist/wallets/ISpvVaultSigner.js +2 -2
- package/package.json +36 -36
- package/src/fees/IBtcFeeEstimator.ts +6 -6
- package/src/index.ts +53 -53
- package/src/info/InfoHandler.ts +106 -106
- package/src/plugins/IPlugin.ts +168 -168
- package/src/plugins/PluginManager.ts +336 -336
- package/src/prices/BinanceSwapPrice.ts +113 -113
- package/src/prices/CoinGeckoSwapPrice.ts +87 -87
- package/src/prices/ISwapPrice.ts +88 -88
- package/src/prices/OKXSwapPrice.ts +113 -113
- package/src/storage/IIntermediaryStorage.ts +19 -19
- package/src/storagemanager/IntermediaryStorageManager.ts +118 -118
- package/src/storagemanager/StorageManager.ts +78 -78
- package/src/swaps/SwapHandler.ts +277 -277
- package/src/swaps/SwapHandlerSwap.ts +141 -141
- package/src/swaps/assertions/AmountAssertions.ts +76 -76
- package/src/swaps/assertions/FromBtcAmountAssertions.ts +246 -246
- package/src/swaps/assertions/LightningAssertions.ts +103 -103
- package/src/swaps/assertions/ToBtcAmountAssertions.ts +203 -203
- package/src/swaps/escrow/EscrowHandler.ts +179 -179
- package/src/swaps/escrow/EscrowHandlerSwap.ts +86 -86
- package/src/swaps/escrow/FromBtcBaseSwap.ts +38 -38
- package/src/swaps/escrow/FromBtcBaseSwapHandler.ts +286 -286
- package/src/swaps/escrow/ToBtcBaseSwap.ts +85 -85
- package/src/swaps/escrow/ToBtcBaseSwapHandler.ts +129 -129
- package/src/swaps/escrow/frombtc_abstract/FromBtcAbs.ts +452 -452
- package/src/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.ts +61 -61
- package/src/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.ts +856 -856
- package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +141 -141
- package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.ts +850 -850
- package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.ts +196 -196
- package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +879 -879
- package/src/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.ts +102 -102
- package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +1112 -1112
- package/src/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.ts +80 -80
- package/src/swaps/spv_vault_swap/SpvVault.ts +143 -143
- package/src/swaps/spv_vault_swap/SpvVaultSwap.ts +225 -225
- package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +628 -628
- package/src/swaps/spv_vault_swap/SpvVaults.ts +469 -435
- package/src/swaps/trusted/frombtc_trusted/FromBtcTrusted.ts +747 -747
- package/src/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.ts +185 -185
- package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +590 -590
- package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.ts +121 -121
- package/src/utils/BitcoinUtils.ts +42 -42
- package/src/utils/Utils.ts +104 -104
- package/src/utils/paramcoders/IParamReader.ts +7 -7
- package/src/utils/paramcoders/IParamWriter.ts +8 -8
- package/src/utils/paramcoders/LegacyParamEncoder.ts +27 -27
- package/src/utils/paramcoders/ParamDecoder.ts +218 -218
- package/src/utils/paramcoders/ParamEncoder.ts +29 -29
- package/src/utils/paramcoders/SchemaVerifier.ts +96 -96
- package/src/utils/paramcoders/server/ServerParamDecoder.ts +118 -118
- package/src/utils/paramcoders/server/ServerParamEncoder.ts +75 -75
- package/src/wallets/IBitcoinWallet.ts +68 -68
- package/src/wallets/ILightningWallet.ts +178 -178
- package/src/wallets/ISpvVaultSigner.ts +10 -10
|
@@ -1,318 +1,318 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.FromBtcAbs = void 0;
|
|
4
|
-
const FromBtcSwapAbs_1 = require("./FromBtcSwapAbs");
|
|
5
|
-
const SwapHandler_1 = require("../../SwapHandler");
|
|
6
|
-
const base_1 = require("@atomiqlabs/base");
|
|
7
|
-
const crypto_1 = require("crypto");
|
|
8
|
-
const Utils_1 = require("../../../utils/Utils");
|
|
9
|
-
const PluginManager_1 = require("../../../plugins/PluginManager");
|
|
10
|
-
const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
|
|
11
|
-
const ServerParamDecoder_1 = require("../../../utils/paramcoders/server/ServerParamDecoder");
|
|
12
|
-
const FromBtcBaseSwapHandler_1 = require("../FromBtcBaseSwapHandler");
|
|
13
|
-
/**
|
|
14
|
-
* Swap handler handling from BTC swaps using PTLCs (proof-time locked contracts) and btc relay (on-chain bitcoin SPV)
|
|
15
|
-
*/
|
|
16
|
-
class FromBtcAbs extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapHandler {
|
|
17
|
-
constructor(storageDirectory, path, chains, bitcoin, swapPricing, config) {
|
|
18
|
-
super(storageDirectory, path, chains, swapPricing, config);
|
|
19
|
-
this.type = SwapHandler_1.SwapHandlerType.FROM_BTC;
|
|
20
|
-
this.swapType = base_1.ChainSwapType.CHAIN;
|
|
21
|
-
this.bitcoin = bitcoin;
|
|
22
|
-
this.config = {
|
|
23
|
-
...config,
|
|
24
|
-
swapTsCsvDelta: BigInt(config.swapCsvDelta) * (config.bitcoinBlocktime / config.safetyFactor)
|
|
25
|
-
};
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Returns the payment hash of the swap, takes swap nonce into account. Payment hash is chain-specific.
|
|
29
|
-
*
|
|
30
|
-
* @param chainIdentifier
|
|
31
|
-
* @param address
|
|
32
|
-
* @param amount
|
|
33
|
-
*/
|
|
34
|
-
getHash(chainIdentifier, address, amount) {
|
|
35
|
-
const parsedOutputScript = this.bitcoin.toOutputScript(address);
|
|
36
|
-
const { swapContract } = this.getChain(chainIdentifier);
|
|
37
|
-
return swapContract.getHashForOnchain(parsedOutputScript, amount, this.config.confirmations, 0n);
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Processes past swap
|
|
41
|
-
*
|
|
42
|
-
* @param swap
|
|
43
|
-
* @protected
|
|
44
|
-
* @returns true if the swap should be refunded, false if nothing should be done
|
|
45
|
-
*/
|
|
46
|
-
async processPastSwap(swap) {
|
|
47
|
-
const { swapContract, signer } = this.getChain(swap.chainIdentifier);
|
|
48
|
-
//Once authorization expires in CREATED state, the user can no more commit it on-chain
|
|
49
|
-
if (swap.state === FromBtcSwapAbs_1.FromBtcSwapState.CREATED) {
|
|
50
|
-
if (!await swapContract.isInitAuthorizationExpired(swap.data, swap))
|
|
51
|
-
return false;
|
|
52
|
-
const isCommited = await swapContract.isCommited(swap.data);
|
|
53
|
-
if (isCommited) {
|
|
54
|
-
this.swapLogger.info(swap, "processPastSwap(state=CREATED): swap was commited, but processed from watchdog, address: " + swap.address);
|
|
55
|
-
await swap.setState(FromBtcSwapAbs_1.FromBtcSwapState.COMMITED);
|
|
56
|
-
await this.saveSwapData(swap);
|
|
57
|
-
return false;
|
|
58
|
-
}
|
|
59
|
-
this.swapLogger.info(swap, "processPastSwap(state=CREATED): removing past swap due to authorization expiry, address: " + swap.address);
|
|
60
|
-
await this.removeSwapData(swap, FromBtcSwapAbs_1.FromBtcSwapState.CANCELED);
|
|
61
|
-
await this.bitcoin.addUnusedAddress(swap.address);
|
|
62
|
-
return false;
|
|
63
|
-
}
|
|
64
|
-
//Check if commited swap expired by now
|
|
65
|
-
if (swap.state === FromBtcSwapAbs_1.FromBtcSwapState.COMMITED) {
|
|
66
|
-
if (!await swapContract.isExpired(signer.getAddress(), swap.data))
|
|
67
|
-
return false;
|
|
68
|
-
const isCommited = await swapContract.isCommited(swap.data);
|
|
69
|
-
if (isCommited) {
|
|
70
|
-
this.swapLogger.info(swap, "processPastSwap(state=COMMITED): swap expired, will refund, address: " + swap.address);
|
|
71
|
-
return true;
|
|
72
|
-
}
|
|
73
|
-
this.swapLogger.warn(swap, "processPastSwap(state=COMMITED): commited swap expired and not committed anymore (already refunded?), address: " + swap.address);
|
|
74
|
-
await this.removeSwapData(swap, FromBtcSwapAbs_1.FromBtcSwapState.CANCELED);
|
|
75
|
-
return false;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
/**
|
|
79
|
-
* Checks past swaps, refunds and deletes ones that are already expired.
|
|
80
|
-
*/
|
|
81
|
-
async processPastSwaps() {
|
|
82
|
-
const queriedData = await this.storageManager.query([
|
|
83
|
-
{
|
|
84
|
-
key: "state",
|
|
85
|
-
value: [
|
|
86
|
-
FromBtcSwapAbs_1.FromBtcSwapState.CREATED,
|
|
87
|
-
FromBtcSwapAbs_1.FromBtcSwapState.COMMITED
|
|
88
|
-
]
|
|
89
|
-
}
|
|
90
|
-
]);
|
|
91
|
-
const refundSwaps = [];
|
|
92
|
-
for (let { obj: swap } of queriedData) {
|
|
93
|
-
if (await this.processPastSwap(swap))
|
|
94
|
-
refundSwaps.push(swap);
|
|
95
|
-
}
|
|
96
|
-
await this.refundSwaps(refundSwaps);
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Refunds all swaps (calls SC on-chain refund function)
|
|
100
|
-
*
|
|
101
|
-
* @param refundSwaps
|
|
102
|
-
* @protected
|
|
103
|
-
*/
|
|
104
|
-
async refundSwaps(refundSwaps) {
|
|
105
|
-
for (let refundSwap of refundSwaps) {
|
|
106
|
-
const { swapContract, signer } = this.getChain(refundSwap.chainIdentifier);
|
|
107
|
-
const unlock = refundSwap.lock(swapContract.refundTimeout);
|
|
108
|
-
if (unlock == null)
|
|
109
|
-
continue;
|
|
110
|
-
this.swapLogger.debug(refundSwap, "refundSwaps(): initiate refund of swap");
|
|
111
|
-
await swapContract.refund(signer, refundSwap.data, true, false, { waitForConfirmation: true });
|
|
112
|
-
this.swapLogger.info(refundSwap, "refundSwaps(): swap refunded, address: " + refundSwap.address);
|
|
113
|
-
//The swap should be removed by the event handler
|
|
114
|
-
await refundSwap.setState(FromBtcSwapAbs_1.FromBtcSwapState.REFUNDED);
|
|
115
|
-
unlock();
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
async processInitializeEvent(chainIdentifier, savedSwap, event) {
|
|
119
|
-
this.swapLogger.info(savedSwap, "SC: InitializeEvent: swap initialized by the client, address: " + savedSwap.address);
|
|
120
|
-
if (savedSwap.state === FromBtcSwapAbs_1.FromBtcSwapState.CREATED) {
|
|
121
|
-
await savedSwap.setState(FromBtcSwapAbs_1.FromBtcSwapState.COMMITED);
|
|
122
|
-
await this.saveSwapData(savedSwap);
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
async processClaimEvent(chainIdentifier, savedSwap, event) {
|
|
126
|
-
savedSwap.txId = Buffer.from(event.result, "hex").reverse().toString("hex");
|
|
127
|
-
this.swapLogger.info(savedSwap, "SC: ClaimEvent: swap successfully claimed by the client, address: " + savedSwap.address);
|
|
128
|
-
await this.removeSwapData(savedSwap, FromBtcSwapAbs_1.FromBtcSwapState.CLAIMED);
|
|
129
|
-
}
|
|
130
|
-
async processRefundEvent(chainIdentifier, savedSwap, event) {
|
|
131
|
-
savedSwap.txIds.refund = event.meta?.txId;
|
|
132
|
-
this.swapLogger.info(event, "SC: RefundEvent: swap refunded, address: " + savedSwap.address);
|
|
133
|
-
await this.removeSwapData(savedSwap, FromBtcSwapAbs_1.FromBtcSwapState.REFUNDED);
|
|
134
|
-
await this.bitcoin.addUnusedAddress(savedSwap.address);
|
|
135
|
-
}
|
|
136
|
-
/**
|
|
137
|
-
* Calculates the requested claimer bounty, based on client's request
|
|
138
|
-
*
|
|
139
|
-
* @param req
|
|
140
|
-
* @param expiry
|
|
141
|
-
* @param signal
|
|
142
|
-
* @throws {DefinedRuntimeError} will throw an error if the plugin cancelled the request
|
|
143
|
-
* @returns {Promise<BN>} resulting claimer bounty to be used with the swap
|
|
144
|
-
*/
|
|
145
|
-
async getClaimerBounty(req, expiry, signal) {
|
|
146
|
-
const parsedClaimerBounty = await req.paramReader.getParams({
|
|
147
|
-
claimerBounty: {
|
|
148
|
-
feePerBlock: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
149
|
-
safetyFactor: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
150
|
-
startTimestamp: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
151
|
-
addBlock: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
152
|
-
addFee: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
153
|
-
},
|
|
154
|
-
}).catch(e => null);
|
|
155
|
-
signal.throwIfAborted();
|
|
156
|
-
if (parsedClaimerBounty == null || parsedClaimerBounty.claimerBounty == null) {
|
|
157
|
-
throw {
|
|
158
|
-
code: 20043,
|
|
159
|
-
msg: "Invalid claimerBounty"
|
|
160
|
-
};
|
|
161
|
-
}
|
|
162
|
-
const tsDelta = expiry - parsedClaimerBounty.claimerBounty.startTimestamp;
|
|
163
|
-
const blocksDelta = tsDelta / this.config.bitcoinBlocktime * parsedClaimerBounty.claimerBounty.safetyFactor;
|
|
164
|
-
const totalBlock = blocksDelta + parsedClaimerBounty.claimerBounty.addBlock;
|
|
165
|
-
return parsedClaimerBounty.claimerBounty.addFee + (totalBlock * parsedClaimerBounty.claimerBounty.feePerBlock);
|
|
166
|
-
}
|
|
167
|
-
getDummySwapData(chainIdentifier, useToken, address) {
|
|
168
|
-
const { swapContract, signer } = this.getChain(chainIdentifier);
|
|
169
|
-
const dummyAmount = BigInt(Math.floor(Math.random() * 0x1000000));
|
|
170
|
-
return swapContract.createSwapData(base_1.ChainSwapType.CHAIN, signer.getAddress(), address, useToken, dummyAmount, swapContract.getHashForOnchain((0, crypto_1.randomBytes)(32), dummyAmount, 3, null).toString("hex"), base_1.BigIntBufferUtils.fromBuffer((0, crypto_1.randomBytes)(8)), BigInt(Math.floor(Date.now() / 1000)) + this.config.swapTsCsvDelta, false, true, BigInt(Math.floor(Math.random() * 0x10000)), BigInt(Math.floor(Math.random() * 0x10000)));
|
|
171
|
-
}
|
|
172
|
-
/**
|
|
173
|
-
* Sets up required listeners for the REST server
|
|
174
|
-
*
|
|
175
|
-
* @param restServer
|
|
176
|
-
*/
|
|
177
|
-
startRestServer(restServer) {
|
|
178
|
-
restServer.use(this.path + "/getAddress", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
|
|
179
|
-
restServer.post(this.path + "/getAddress", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
|
|
180
|
-
const metadata = { request: {}, times: {} };
|
|
181
|
-
const chainIdentifier = req.query.chain ?? this.chains.default;
|
|
182
|
-
const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
|
|
183
|
-
const depositToken = req.query.depositToken ?? chainInterface.getNativeCurrencyAddress();
|
|
184
|
-
this.checkAllowedDepositToken(chainIdentifier, depositToken);
|
|
185
|
-
metadata.times.requestReceived = Date.now();
|
|
186
|
-
/**
|
|
187
|
-
* address: string solana address of the recipient
|
|
188
|
-
* amount: string amount (in sats) of the invoice
|
|
189
|
-
* token: string Desired token to use
|
|
190
|
-
* exactOut: boolean Whether the swap should be an exact out instead of exact in swap
|
|
191
|
-
* sequence: BN Unique sequence number for the swap
|
|
192
|
-
*
|
|
193
|
-
*Sent later
|
|
194
|
-
* claimerBounty: object Data for calculating claimer bounty
|
|
195
|
-
* - feePerBlock: string Fee per block to be synchronized with btc relay
|
|
196
|
-
* - safetyFactor: number Safety factor to multiply required blocks (when using 10 min block time)
|
|
197
|
-
* - startTimestamp: string UNIX seconds used for timestamp delta calc
|
|
198
|
-
* - addBlock: number Additional blocks to add to the calculation
|
|
199
|
-
* - addFee: string Additional fee to add to the final claimer bounty
|
|
200
|
-
* feeRate: string Fee rate to be used for init signature
|
|
201
|
-
*/
|
|
202
|
-
const parsedBody = await req.paramReader.getParams({
|
|
203
|
-
address: (val) => val != null &&
|
|
204
|
-
typeof (val) === "string" &&
|
|
205
|
-
chainInterface.isValidAddress(val) ? val : null,
|
|
206
|
-
amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
207
|
-
token: (val) => val != null &&
|
|
208
|
-
typeof (val) === "string" &&
|
|
209
|
-
this.isTokenSupported(chainIdentifier, val) ? val : null,
|
|
210
|
-
sequence: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
211
|
-
exactOut: SchemaVerifier_1.FieldTypeEnum.BooleanOptional
|
|
212
|
-
});
|
|
213
|
-
if (parsedBody == null)
|
|
214
|
-
throw {
|
|
215
|
-
code: 20100,
|
|
216
|
-
msg: "Invalid request body"
|
|
217
|
-
};
|
|
218
|
-
metadata.request = parsedBody;
|
|
219
|
-
const requestedAmount = { input: !parsedBody.exactOut, amount: parsedBody.amount, token: parsedBody.token };
|
|
220
|
-
const request = {
|
|
221
|
-
chainIdentifier,
|
|
222
|
-
raw: req,
|
|
223
|
-
parsed: parsedBody,
|
|
224
|
-
metadata
|
|
225
|
-
};
|
|
226
|
-
const useToken = parsedBody.token;
|
|
227
|
-
//Check request params
|
|
228
|
-
this.checkSequence(parsedBody.sequence);
|
|
229
|
-
const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount);
|
|
230
|
-
metadata.times.requestChecked = Date.now();
|
|
231
|
-
//Create abortController for parallel prefetches
|
|
232
|
-
const responseStream = res.responseStream;
|
|
233
|
-
const abortController = (0, Utils_1.getAbortController)(responseStream);
|
|
234
|
-
//Pre-fetch data
|
|
235
|
-
const { pricePrefetchPromise, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise } = this.getFromBtcPricePrefetches(chainIdentifier, useToken, depositToken, abortController);
|
|
236
|
-
const balancePrefetch = this.getBalancePrefetch(chainIdentifier, useToken, abortController);
|
|
237
|
-
const signDataPrefetchPromise = this.getSignDataPrefetch(chainIdentifier, abortController, responseStream);
|
|
238
|
-
const dummySwapData = await this.getDummySwapData(chainIdentifier, useToken, parsedBody.address);
|
|
239
|
-
abortController.signal.throwIfAborted();
|
|
240
|
-
const baseSDPromise = this.getBaseSecurityDepositPrefetch(chainIdentifier, dummySwapData, depositToken, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise, abortController);
|
|
241
|
-
//Check valid amount specified (min/max)
|
|
242
|
-
const { amountBD, swapFee, swapFeeInToken, totalInToken, securityDepositApyPPM, securityDepositBaseMultiplierPPM } = await this.AmountAssertions.checkFromBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, abortController.signal);
|
|
243
|
-
metadata.times.priceCalculated = Date.now();
|
|
244
|
-
if (securityDepositApyPPM != null)
|
|
245
|
-
fees.securityDepositApyPPM = securityDepositApyPPM;
|
|
246
|
-
if (securityDepositBaseMultiplierPPM != null)
|
|
247
|
-
fees.securityDepositBaseMultiplierPPM = securityDepositBaseMultiplierPPM;
|
|
248
|
-
//Check if we have enough funds to honor the request
|
|
249
|
-
await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
|
|
250
|
-
metadata.times.balanceChecked = Date.now();
|
|
251
|
-
//Create swap receive bitcoin address
|
|
252
|
-
const receiveAddress = await this.bitcoin.getAddress();
|
|
253
|
-
abortController.signal.throwIfAborted();
|
|
254
|
-
metadata.times.addressCreated = Date.now();
|
|
255
|
-
const paymentHash = this.getHash(chainIdentifier, receiveAddress, amountBD);
|
|
256
|
-
const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
|
|
257
|
-
const expiryTimeout = this.config.swapTsCsvDelta;
|
|
258
|
-
const expiry = currentTimestamp + expiryTimeout;
|
|
259
|
-
//Calculate security deposit
|
|
260
|
-
const totalSecurityDeposit = await this.getSecurityDeposit(chainIdentifier, amountBD, swapFee, expiryTimeout, baseSDPromise, depositToken, depositTokenPricePrefetchPromise, fees, abortController.signal, metadata);
|
|
261
|
-
metadata.times.securityDepositCalculated = Date.now();
|
|
262
|
-
//Calculate claimer bounty
|
|
263
|
-
const totalClaimerBounty = await this.getClaimerBounty(req, expiry, abortController.signal);
|
|
264
|
-
metadata.times.claimerBountyCalculated = Date.now();
|
|
265
|
-
//Create swap data
|
|
266
|
-
const data = await swapContract.createSwapData(base_1.ChainSwapType.CHAIN, signer.getAddress(), parsedBody.address, useToken, totalInToken, paymentHash.toString("hex"), parsedBody.sequence, expiry, false, true, totalSecurityDeposit, totalClaimerBounty, depositToken);
|
|
267
|
-
data.setExtraData(swapContract.getExtraData(this.bitcoin.toOutputScript(receiveAddress), amountBD, this.config.confirmations).toString("hex"));
|
|
268
|
-
abortController.signal.throwIfAborted();
|
|
269
|
-
metadata.times.swapCreated = Date.now();
|
|
270
|
-
//Sign the swap
|
|
271
|
-
const sigData = await this.getFromBtcSignatureData(chainIdentifier, data, req, abortController.signal, signDataPrefetchPromise);
|
|
272
|
-
metadata.times.swapSigned = Date.now();
|
|
273
|
-
const createdSwap = new FromBtcSwapAbs_1.FromBtcSwapAbs(chainIdentifier, receiveAddress, this.config.confirmations, amountBD, swapFee, swapFeeInToken);
|
|
274
|
-
createdSwap.data = data;
|
|
275
|
-
createdSwap.metadata = metadata;
|
|
276
|
-
createdSwap.prefix = sigData.prefix;
|
|
277
|
-
createdSwap.timeout = sigData.timeout;
|
|
278
|
-
createdSwap.signature = sigData.signature;
|
|
279
|
-
createdSwap.feeRate = sigData.feeRate;
|
|
280
|
-
await PluginManager_1.PluginManager.swapCreate(createdSwap);
|
|
281
|
-
await this.saveSwapData(createdSwap);
|
|
282
|
-
this.swapLogger.info(createdSwap, "REST: /getAddress: Created swap address: " + receiveAddress + " amount: " + amountBD.toString(10));
|
|
283
|
-
await responseStream.writeParamsAndEnd({
|
|
284
|
-
code: 20000,
|
|
285
|
-
msg: "Success",
|
|
286
|
-
data: {
|
|
287
|
-
amount: amountBD.toString(10),
|
|
288
|
-
btcAddress: receiveAddress,
|
|
289
|
-
address: signer.getAddress(),
|
|
290
|
-
swapFee: swapFeeInToken.toString(10),
|
|
291
|
-
total: totalInToken.toString(10),
|
|
292
|
-
confirmations: this.config.confirmations,
|
|
293
|
-
data: data.serialize(),
|
|
294
|
-
prefix: sigData.prefix,
|
|
295
|
-
timeout: sigData.timeout,
|
|
296
|
-
signature: sigData.signature
|
|
297
|
-
}
|
|
298
|
-
});
|
|
299
|
-
}));
|
|
300
|
-
this.logger.info("REST: Started at path: ", this.path);
|
|
301
|
-
}
|
|
302
|
-
/**
|
|
303
|
-
* Initializes swap handler, loads data and subscribes to chain events
|
|
304
|
-
*/
|
|
305
|
-
async init() {
|
|
306
|
-
await this.loadData(FromBtcSwapAbs_1.FromBtcSwapAbs);
|
|
307
|
-
this.subscribeToEvents();
|
|
308
|
-
await PluginManager_1.PluginManager.serviceInitialize(this);
|
|
309
|
-
}
|
|
310
|
-
getInfoData() {
|
|
311
|
-
return {
|
|
312
|
-
confirmations: this.config.confirmations,
|
|
313
|
-
cltv: this.config.swapCsvDelta,
|
|
314
|
-
timestampCltv: Number(this.config.swapTsCsvDelta)
|
|
315
|
-
};
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
exports.FromBtcAbs = FromBtcAbs;
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FromBtcAbs = void 0;
|
|
4
|
+
const FromBtcSwapAbs_1 = require("./FromBtcSwapAbs");
|
|
5
|
+
const SwapHandler_1 = require("../../SwapHandler");
|
|
6
|
+
const base_1 = require("@atomiqlabs/base");
|
|
7
|
+
const crypto_1 = require("crypto");
|
|
8
|
+
const Utils_1 = require("../../../utils/Utils");
|
|
9
|
+
const PluginManager_1 = require("../../../plugins/PluginManager");
|
|
10
|
+
const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
|
|
11
|
+
const ServerParamDecoder_1 = require("../../../utils/paramcoders/server/ServerParamDecoder");
|
|
12
|
+
const FromBtcBaseSwapHandler_1 = require("../FromBtcBaseSwapHandler");
|
|
13
|
+
/**
|
|
14
|
+
* Swap handler handling from BTC swaps using PTLCs (proof-time locked contracts) and btc relay (on-chain bitcoin SPV)
|
|
15
|
+
*/
|
|
16
|
+
class FromBtcAbs extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapHandler {
|
|
17
|
+
constructor(storageDirectory, path, chains, bitcoin, swapPricing, config) {
|
|
18
|
+
super(storageDirectory, path, chains, swapPricing, config);
|
|
19
|
+
this.type = SwapHandler_1.SwapHandlerType.FROM_BTC;
|
|
20
|
+
this.swapType = base_1.ChainSwapType.CHAIN;
|
|
21
|
+
this.bitcoin = bitcoin;
|
|
22
|
+
this.config = {
|
|
23
|
+
...config,
|
|
24
|
+
swapTsCsvDelta: BigInt(config.swapCsvDelta) * (config.bitcoinBlocktime / config.safetyFactor)
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Returns the payment hash of the swap, takes swap nonce into account. Payment hash is chain-specific.
|
|
29
|
+
*
|
|
30
|
+
* @param chainIdentifier
|
|
31
|
+
* @param address
|
|
32
|
+
* @param amount
|
|
33
|
+
*/
|
|
34
|
+
getHash(chainIdentifier, address, amount) {
|
|
35
|
+
const parsedOutputScript = this.bitcoin.toOutputScript(address);
|
|
36
|
+
const { swapContract } = this.getChain(chainIdentifier);
|
|
37
|
+
return swapContract.getHashForOnchain(parsedOutputScript, amount, this.config.confirmations, 0n);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Processes past swap
|
|
41
|
+
*
|
|
42
|
+
* @param swap
|
|
43
|
+
* @protected
|
|
44
|
+
* @returns true if the swap should be refunded, false if nothing should be done
|
|
45
|
+
*/
|
|
46
|
+
async processPastSwap(swap) {
|
|
47
|
+
const { swapContract, signer } = this.getChain(swap.chainIdentifier);
|
|
48
|
+
//Once authorization expires in CREATED state, the user can no more commit it on-chain
|
|
49
|
+
if (swap.state === FromBtcSwapAbs_1.FromBtcSwapState.CREATED) {
|
|
50
|
+
if (!await swapContract.isInitAuthorizationExpired(swap.data, swap))
|
|
51
|
+
return false;
|
|
52
|
+
const isCommited = await swapContract.isCommited(swap.data);
|
|
53
|
+
if (isCommited) {
|
|
54
|
+
this.swapLogger.info(swap, "processPastSwap(state=CREATED): swap was commited, but processed from watchdog, address: " + swap.address);
|
|
55
|
+
await swap.setState(FromBtcSwapAbs_1.FromBtcSwapState.COMMITED);
|
|
56
|
+
await this.saveSwapData(swap);
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
this.swapLogger.info(swap, "processPastSwap(state=CREATED): removing past swap due to authorization expiry, address: " + swap.address);
|
|
60
|
+
await this.removeSwapData(swap, FromBtcSwapAbs_1.FromBtcSwapState.CANCELED);
|
|
61
|
+
await this.bitcoin.addUnusedAddress(swap.address);
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
//Check if commited swap expired by now
|
|
65
|
+
if (swap.state === FromBtcSwapAbs_1.FromBtcSwapState.COMMITED) {
|
|
66
|
+
if (!await swapContract.isExpired(signer.getAddress(), swap.data))
|
|
67
|
+
return false;
|
|
68
|
+
const isCommited = await swapContract.isCommited(swap.data);
|
|
69
|
+
if (isCommited) {
|
|
70
|
+
this.swapLogger.info(swap, "processPastSwap(state=COMMITED): swap expired, will refund, address: " + swap.address);
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
this.swapLogger.warn(swap, "processPastSwap(state=COMMITED): commited swap expired and not committed anymore (already refunded?), address: " + swap.address);
|
|
74
|
+
await this.removeSwapData(swap, FromBtcSwapAbs_1.FromBtcSwapState.CANCELED);
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Checks past swaps, refunds and deletes ones that are already expired.
|
|
80
|
+
*/
|
|
81
|
+
async processPastSwaps() {
|
|
82
|
+
const queriedData = await this.storageManager.query([
|
|
83
|
+
{
|
|
84
|
+
key: "state",
|
|
85
|
+
value: [
|
|
86
|
+
FromBtcSwapAbs_1.FromBtcSwapState.CREATED,
|
|
87
|
+
FromBtcSwapAbs_1.FromBtcSwapState.COMMITED
|
|
88
|
+
]
|
|
89
|
+
}
|
|
90
|
+
]);
|
|
91
|
+
const refundSwaps = [];
|
|
92
|
+
for (let { obj: swap } of queriedData) {
|
|
93
|
+
if (await this.processPastSwap(swap))
|
|
94
|
+
refundSwaps.push(swap);
|
|
95
|
+
}
|
|
96
|
+
await this.refundSwaps(refundSwaps);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Refunds all swaps (calls SC on-chain refund function)
|
|
100
|
+
*
|
|
101
|
+
* @param refundSwaps
|
|
102
|
+
* @protected
|
|
103
|
+
*/
|
|
104
|
+
async refundSwaps(refundSwaps) {
|
|
105
|
+
for (let refundSwap of refundSwaps) {
|
|
106
|
+
const { swapContract, signer } = this.getChain(refundSwap.chainIdentifier);
|
|
107
|
+
const unlock = refundSwap.lock(swapContract.refundTimeout);
|
|
108
|
+
if (unlock == null)
|
|
109
|
+
continue;
|
|
110
|
+
this.swapLogger.debug(refundSwap, "refundSwaps(): initiate refund of swap");
|
|
111
|
+
await swapContract.refund(signer, refundSwap.data, true, false, { waitForConfirmation: true });
|
|
112
|
+
this.swapLogger.info(refundSwap, "refundSwaps(): swap refunded, address: " + refundSwap.address);
|
|
113
|
+
//The swap should be removed by the event handler
|
|
114
|
+
await refundSwap.setState(FromBtcSwapAbs_1.FromBtcSwapState.REFUNDED);
|
|
115
|
+
unlock();
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
async processInitializeEvent(chainIdentifier, savedSwap, event) {
|
|
119
|
+
this.swapLogger.info(savedSwap, "SC: InitializeEvent: swap initialized by the client, address: " + savedSwap.address);
|
|
120
|
+
if (savedSwap.state === FromBtcSwapAbs_1.FromBtcSwapState.CREATED) {
|
|
121
|
+
await savedSwap.setState(FromBtcSwapAbs_1.FromBtcSwapState.COMMITED);
|
|
122
|
+
await this.saveSwapData(savedSwap);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
async processClaimEvent(chainIdentifier, savedSwap, event) {
|
|
126
|
+
savedSwap.txId = Buffer.from(event.result, "hex").reverse().toString("hex");
|
|
127
|
+
this.swapLogger.info(savedSwap, "SC: ClaimEvent: swap successfully claimed by the client, address: " + savedSwap.address);
|
|
128
|
+
await this.removeSwapData(savedSwap, FromBtcSwapAbs_1.FromBtcSwapState.CLAIMED);
|
|
129
|
+
}
|
|
130
|
+
async processRefundEvent(chainIdentifier, savedSwap, event) {
|
|
131
|
+
savedSwap.txIds.refund = event.meta?.txId;
|
|
132
|
+
this.swapLogger.info(event, "SC: RefundEvent: swap refunded, address: " + savedSwap.address);
|
|
133
|
+
await this.removeSwapData(savedSwap, FromBtcSwapAbs_1.FromBtcSwapState.REFUNDED);
|
|
134
|
+
await this.bitcoin.addUnusedAddress(savedSwap.address);
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Calculates the requested claimer bounty, based on client's request
|
|
138
|
+
*
|
|
139
|
+
* @param req
|
|
140
|
+
* @param expiry
|
|
141
|
+
* @param signal
|
|
142
|
+
* @throws {DefinedRuntimeError} will throw an error if the plugin cancelled the request
|
|
143
|
+
* @returns {Promise<BN>} resulting claimer bounty to be used with the swap
|
|
144
|
+
*/
|
|
145
|
+
async getClaimerBounty(req, expiry, signal) {
|
|
146
|
+
const parsedClaimerBounty = await req.paramReader.getParams({
|
|
147
|
+
claimerBounty: {
|
|
148
|
+
feePerBlock: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
149
|
+
safetyFactor: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
150
|
+
startTimestamp: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
151
|
+
addBlock: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
152
|
+
addFee: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
153
|
+
},
|
|
154
|
+
}).catch(e => null);
|
|
155
|
+
signal.throwIfAborted();
|
|
156
|
+
if (parsedClaimerBounty == null || parsedClaimerBounty.claimerBounty == null) {
|
|
157
|
+
throw {
|
|
158
|
+
code: 20043,
|
|
159
|
+
msg: "Invalid claimerBounty"
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
const tsDelta = expiry - parsedClaimerBounty.claimerBounty.startTimestamp;
|
|
163
|
+
const blocksDelta = tsDelta / this.config.bitcoinBlocktime * parsedClaimerBounty.claimerBounty.safetyFactor;
|
|
164
|
+
const totalBlock = blocksDelta + parsedClaimerBounty.claimerBounty.addBlock;
|
|
165
|
+
return parsedClaimerBounty.claimerBounty.addFee + (totalBlock * parsedClaimerBounty.claimerBounty.feePerBlock);
|
|
166
|
+
}
|
|
167
|
+
getDummySwapData(chainIdentifier, useToken, address) {
|
|
168
|
+
const { swapContract, signer } = this.getChain(chainIdentifier);
|
|
169
|
+
const dummyAmount = BigInt(Math.floor(Math.random() * 0x1000000));
|
|
170
|
+
return swapContract.createSwapData(base_1.ChainSwapType.CHAIN, signer.getAddress(), address, useToken, dummyAmount, swapContract.getHashForOnchain((0, crypto_1.randomBytes)(32), dummyAmount, 3, null).toString("hex"), base_1.BigIntBufferUtils.fromBuffer((0, crypto_1.randomBytes)(8)), BigInt(Math.floor(Date.now() / 1000)) + this.config.swapTsCsvDelta, false, true, BigInt(Math.floor(Math.random() * 0x10000)), BigInt(Math.floor(Math.random() * 0x10000)));
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Sets up required listeners for the REST server
|
|
174
|
+
*
|
|
175
|
+
* @param restServer
|
|
176
|
+
*/
|
|
177
|
+
startRestServer(restServer) {
|
|
178
|
+
restServer.use(this.path + "/getAddress", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
|
|
179
|
+
restServer.post(this.path + "/getAddress", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
|
|
180
|
+
const metadata = { request: {}, times: {} };
|
|
181
|
+
const chainIdentifier = req.query.chain ?? this.chains.default;
|
|
182
|
+
const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
|
|
183
|
+
const depositToken = req.query.depositToken ?? chainInterface.getNativeCurrencyAddress();
|
|
184
|
+
this.checkAllowedDepositToken(chainIdentifier, depositToken);
|
|
185
|
+
metadata.times.requestReceived = Date.now();
|
|
186
|
+
/**
|
|
187
|
+
* address: string solana address of the recipient
|
|
188
|
+
* amount: string amount (in sats) of the invoice
|
|
189
|
+
* token: string Desired token to use
|
|
190
|
+
* exactOut: boolean Whether the swap should be an exact out instead of exact in swap
|
|
191
|
+
* sequence: BN Unique sequence number for the swap
|
|
192
|
+
*
|
|
193
|
+
*Sent later
|
|
194
|
+
* claimerBounty: object Data for calculating claimer bounty
|
|
195
|
+
* - feePerBlock: string Fee per block to be synchronized with btc relay
|
|
196
|
+
* - safetyFactor: number Safety factor to multiply required blocks (when using 10 min block time)
|
|
197
|
+
* - startTimestamp: string UNIX seconds used for timestamp delta calc
|
|
198
|
+
* - addBlock: number Additional blocks to add to the calculation
|
|
199
|
+
* - addFee: string Additional fee to add to the final claimer bounty
|
|
200
|
+
* feeRate: string Fee rate to be used for init signature
|
|
201
|
+
*/
|
|
202
|
+
const parsedBody = await req.paramReader.getParams({
|
|
203
|
+
address: (val) => val != null &&
|
|
204
|
+
typeof (val) === "string" &&
|
|
205
|
+
chainInterface.isValidAddress(val) ? val : null,
|
|
206
|
+
amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
207
|
+
token: (val) => val != null &&
|
|
208
|
+
typeof (val) === "string" &&
|
|
209
|
+
this.isTokenSupported(chainIdentifier, val) ? val : null,
|
|
210
|
+
sequence: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
211
|
+
exactOut: SchemaVerifier_1.FieldTypeEnum.BooleanOptional
|
|
212
|
+
});
|
|
213
|
+
if (parsedBody == null)
|
|
214
|
+
throw {
|
|
215
|
+
code: 20100,
|
|
216
|
+
msg: "Invalid request body"
|
|
217
|
+
};
|
|
218
|
+
metadata.request = parsedBody;
|
|
219
|
+
const requestedAmount = { input: !parsedBody.exactOut, amount: parsedBody.amount, token: parsedBody.token };
|
|
220
|
+
const request = {
|
|
221
|
+
chainIdentifier,
|
|
222
|
+
raw: req,
|
|
223
|
+
parsed: parsedBody,
|
|
224
|
+
metadata
|
|
225
|
+
};
|
|
226
|
+
const useToken = parsedBody.token;
|
|
227
|
+
//Check request params
|
|
228
|
+
this.checkSequence(parsedBody.sequence);
|
|
229
|
+
const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount);
|
|
230
|
+
metadata.times.requestChecked = Date.now();
|
|
231
|
+
//Create abortController for parallel prefetches
|
|
232
|
+
const responseStream = res.responseStream;
|
|
233
|
+
const abortController = (0, Utils_1.getAbortController)(responseStream);
|
|
234
|
+
//Pre-fetch data
|
|
235
|
+
const { pricePrefetchPromise, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise } = this.getFromBtcPricePrefetches(chainIdentifier, useToken, depositToken, abortController);
|
|
236
|
+
const balancePrefetch = this.getBalancePrefetch(chainIdentifier, useToken, abortController);
|
|
237
|
+
const signDataPrefetchPromise = this.getSignDataPrefetch(chainIdentifier, abortController, responseStream);
|
|
238
|
+
const dummySwapData = await this.getDummySwapData(chainIdentifier, useToken, parsedBody.address);
|
|
239
|
+
abortController.signal.throwIfAborted();
|
|
240
|
+
const baseSDPromise = this.getBaseSecurityDepositPrefetch(chainIdentifier, dummySwapData, depositToken, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise, abortController);
|
|
241
|
+
//Check valid amount specified (min/max)
|
|
242
|
+
const { amountBD, swapFee, swapFeeInToken, totalInToken, securityDepositApyPPM, securityDepositBaseMultiplierPPM } = await this.AmountAssertions.checkFromBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, abortController.signal);
|
|
243
|
+
metadata.times.priceCalculated = Date.now();
|
|
244
|
+
if (securityDepositApyPPM != null)
|
|
245
|
+
fees.securityDepositApyPPM = securityDepositApyPPM;
|
|
246
|
+
if (securityDepositBaseMultiplierPPM != null)
|
|
247
|
+
fees.securityDepositBaseMultiplierPPM = securityDepositBaseMultiplierPPM;
|
|
248
|
+
//Check if we have enough funds to honor the request
|
|
249
|
+
await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
|
|
250
|
+
metadata.times.balanceChecked = Date.now();
|
|
251
|
+
//Create swap receive bitcoin address
|
|
252
|
+
const receiveAddress = await this.bitcoin.getAddress();
|
|
253
|
+
abortController.signal.throwIfAborted();
|
|
254
|
+
metadata.times.addressCreated = Date.now();
|
|
255
|
+
const paymentHash = this.getHash(chainIdentifier, receiveAddress, amountBD);
|
|
256
|
+
const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
|
|
257
|
+
const expiryTimeout = this.config.swapTsCsvDelta;
|
|
258
|
+
const expiry = currentTimestamp + expiryTimeout;
|
|
259
|
+
//Calculate security deposit
|
|
260
|
+
const totalSecurityDeposit = await this.getSecurityDeposit(chainIdentifier, amountBD, swapFee, expiryTimeout, baseSDPromise, depositToken, depositTokenPricePrefetchPromise, fees, abortController.signal, metadata);
|
|
261
|
+
metadata.times.securityDepositCalculated = Date.now();
|
|
262
|
+
//Calculate claimer bounty
|
|
263
|
+
const totalClaimerBounty = await this.getClaimerBounty(req, expiry, abortController.signal);
|
|
264
|
+
metadata.times.claimerBountyCalculated = Date.now();
|
|
265
|
+
//Create swap data
|
|
266
|
+
const data = await swapContract.createSwapData(base_1.ChainSwapType.CHAIN, signer.getAddress(), parsedBody.address, useToken, totalInToken, paymentHash.toString("hex"), parsedBody.sequence, expiry, false, true, totalSecurityDeposit, totalClaimerBounty, depositToken);
|
|
267
|
+
data.setExtraData(swapContract.getExtraData(this.bitcoin.toOutputScript(receiveAddress), amountBD, this.config.confirmations).toString("hex"));
|
|
268
|
+
abortController.signal.throwIfAborted();
|
|
269
|
+
metadata.times.swapCreated = Date.now();
|
|
270
|
+
//Sign the swap
|
|
271
|
+
const sigData = await this.getFromBtcSignatureData(chainIdentifier, data, req, abortController.signal, signDataPrefetchPromise);
|
|
272
|
+
metadata.times.swapSigned = Date.now();
|
|
273
|
+
const createdSwap = new FromBtcSwapAbs_1.FromBtcSwapAbs(chainIdentifier, receiveAddress, this.config.confirmations, amountBD, swapFee, swapFeeInToken);
|
|
274
|
+
createdSwap.data = data;
|
|
275
|
+
createdSwap.metadata = metadata;
|
|
276
|
+
createdSwap.prefix = sigData.prefix;
|
|
277
|
+
createdSwap.timeout = sigData.timeout;
|
|
278
|
+
createdSwap.signature = sigData.signature;
|
|
279
|
+
createdSwap.feeRate = sigData.feeRate;
|
|
280
|
+
await PluginManager_1.PluginManager.swapCreate(createdSwap);
|
|
281
|
+
await this.saveSwapData(createdSwap);
|
|
282
|
+
this.swapLogger.info(createdSwap, "REST: /getAddress: Created swap address: " + receiveAddress + " amount: " + amountBD.toString(10));
|
|
283
|
+
await responseStream.writeParamsAndEnd({
|
|
284
|
+
code: 20000,
|
|
285
|
+
msg: "Success",
|
|
286
|
+
data: {
|
|
287
|
+
amount: amountBD.toString(10),
|
|
288
|
+
btcAddress: receiveAddress,
|
|
289
|
+
address: signer.getAddress(),
|
|
290
|
+
swapFee: swapFeeInToken.toString(10),
|
|
291
|
+
total: totalInToken.toString(10),
|
|
292
|
+
confirmations: this.config.confirmations,
|
|
293
|
+
data: data.serialize(),
|
|
294
|
+
prefix: sigData.prefix,
|
|
295
|
+
timeout: sigData.timeout,
|
|
296
|
+
signature: sigData.signature
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
}));
|
|
300
|
+
this.logger.info("REST: Started at path: ", this.path);
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Initializes swap handler, loads data and subscribes to chain events
|
|
304
|
+
*/
|
|
305
|
+
async init() {
|
|
306
|
+
await this.loadData(FromBtcSwapAbs_1.FromBtcSwapAbs);
|
|
307
|
+
this.subscribeToEvents();
|
|
308
|
+
await PluginManager_1.PluginManager.serviceInitialize(this);
|
|
309
|
+
}
|
|
310
|
+
getInfoData() {
|
|
311
|
+
return {
|
|
312
|
+
confirmations: this.config.confirmations,
|
|
313
|
+
cltv: this.config.swapCsvDelta,
|
|
314
|
+
timestampCltv: Number(this.config.swapTsCsvDelta)
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
exports.FromBtcAbs = FromBtcAbs;
|