@atomiqlabs/chain-evm 1.0.0-dev.34 → 1.0.0-dev.36

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 (161) hide show
  1. package/LICENSE +201 -201
  2. package/dist/chains/citrea/CitreaBtcRelay.d.ts +21 -21
  3. package/dist/chains/citrea/CitreaBtcRelay.js +43 -43
  4. package/dist/chains/citrea/CitreaChainType.d.ts +13 -13
  5. package/dist/chains/citrea/CitreaChainType.js +2 -2
  6. package/dist/chains/citrea/CitreaFees.d.ts +29 -29
  7. package/dist/chains/citrea/CitreaFees.js +67 -67
  8. package/dist/chains/citrea/CitreaInitializer.d.ts +30 -30
  9. package/dist/chains/citrea/CitreaInitializer.js +127 -127
  10. package/dist/chains/citrea/CitreaSpvVaultContract.d.ts +15 -15
  11. package/dist/chains/citrea/CitreaSpvVaultContract.js +74 -74
  12. package/dist/chains/citrea/CitreaSwapContract.d.ts +22 -22
  13. package/dist/chains/citrea/CitreaSwapContract.js +96 -96
  14. package/dist/chains/citrea/CitreaTokens.d.ts +9 -9
  15. package/dist/chains/citrea/CitreaTokens.js +20 -20
  16. package/dist/evm/btcrelay/BtcRelayAbi.d.ts +198 -198
  17. package/dist/evm/btcrelay/BtcRelayAbi.js +261 -261
  18. package/dist/evm/btcrelay/BtcRelayTypechain.d.ts +172 -172
  19. package/dist/evm/btcrelay/BtcRelayTypechain.js +2 -2
  20. package/dist/evm/btcrelay/EVMBtcRelay.d.ts +195 -195
  21. package/dist/evm/btcrelay/EVMBtcRelay.js +423 -423
  22. package/dist/evm/btcrelay/headers/EVMBtcHeader.d.ts +33 -33
  23. package/dist/evm/btcrelay/headers/EVMBtcHeader.js +84 -84
  24. package/dist/evm/btcrelay/headers/EVMBtcStoredHeader.d.ts +56 -56
  25. package/dist/evm/btcrelay/headers/EVMBtcStoredHeader.js +123 -123
  26. package/dist/evm/chain/EVMChainInterface.d.ts +51 -51
  27. package/dist/evm/chain/EVMChainInterface.js +89 -89
  28. package/dist/evm/chain/EVMModule.d.ts +9 -9
  29. package/dist/evm/chain/EVMModule.js +13 -13
  30. package/dist/evm/chain/modules/ERC20Abi.d.ts +168 -168
  31. package/dist/evm/chain/modules/ERC20Abi.js +225 -225
  32. package/dist/evm/chain/modules/EVMAddresses.d.ts +10 -10
  33. package/dist/evm/chain/modules/EVMAddresses.js +30 -30
  34. package/dist/evm/chain/modules/EVMBlocks.d.ts +20 -20
  35. package/dist/evm/chain/modules/EVMBlocks.js +64 -64
  36. package/dist/evm/chain/modules/EVMEvents.d.ts +36 -36
  37. package/dist/evm/chain/modules/EVMEvents.js +122 -122
  38. package/dist/evm/chain/modules/EVMFees.d.ts +36 -36
  39. package/dist/evm/chain/modules/EVMFees.js +73 -73
  40. package/dist/evm/chain/modules/EVMSignatures.d.ts +29 -29
  41. package/dist/evm/chain/modules/EVMSignatures.js +68 -68
  42. package/dist/evm/chain/modules/EVMTokens.d.ts +70 -51
  43. package/dist/evm/chain/modules/EVMTokens.js +142 -113
  44. package/dist/evm/chain/modules/EVMTransactions.d.ts +89 -89
  45. package/dist/evm/chain/modules/EVMTransactions.js +216 -216
  46. package/dist/evm/contract/EVMContractBase.d.ts +22 -22
  47. package/dist/evm/contract/EVMContractBase.js +34 -34
  48. package/dist/evm/contract/EVMContractModule.d.ts +8 -8
  49. package/dist/evm/contract/EVMContractModule.js +11 -11
  50. package/dist/evm/contract/modules/EVMContractEvents.d.ts +42 -42
  51. package/dist/evm/contract/modules/EVMContractEvents.js +75 -75
  52. package/dist/evm/events/EVMChainEvents.d.ts +22 -22
  53. package/dist/evm/events/EVMChainEvents.js +67 -67
  54. package/dist/evm/events/EVMChainEventsBrowser.d.ts +86 -86
  55. package/dist/evm/events/EVMChainEventsBrowser.js +294 -294
  56. package/dist/evm/spv_swap/EVMSpvVaultContract.d.ts +78 -78
  57. package/dist/evm/spv_swap/EVMSpvVaultContract.js +478 -480
  58. package/dist/evm/spv_swap/EVMSpvVaultData.d.ts +39 -39
  59. package/dist/evm/spv_swap/EVMSpvVaultData.js +180 -180
  60. package/dist/evm/spv_swap/EVMSpvWithdrawalData.d.ts +19 -19
  61. package/dist/evm/spv_swap/EVMSpvWithdrawalData.js +55 -55
  62. package/dist/evm/spv_swap/SpvVaultContractAbi.d.ts +91 -91
  63. package/dist/evm/spv_swap/SpvVaultContractAbi.js +849 -849
  64. package/dist/evm/spv_swap/SpvVaultContractTypechain.d.ts +450 -450
  65. package/dist/evm/spv_swap/SpvVaultContractTypechain.js +2 -2
  66. package/dist/evm/swaps/EVMSwapContract.d.ts +193 -193
  67. package/dist/evm/swaps/EVMSwapContract.js +374 -374
  68. package/dist/evm/swaps/EVMSwapData.d.ts +66 -66
  69. package/dist/evm/swaps/EVMSwapData.js +260 -259
  70. package/dist/evm/swaps/EVMSwapModule.d.ts +9 -9
  71. package/dist/evm/swaps/EVMSwapModule.js +11 -11
  72. package/dist/evm/swaps/EscrowManagerAbi.d.ts +120 -120
  73. package/dist/evm/swaps/EscrowManagerAbi.js +985 -985
  74. package/dist/evm/swaps/EscrowManagerTypechain.d.ts +475 -475
  75. package/dist/evm/swaps/EscrowManagerTypechain.js +2 -2
  76. package/dist/evm/swaps/handlers/IHandler.d.ts +13 -13
  77. package/dist/evm/swaps/handlers/IHandler.js +2 -2
  78. package/dist/evm/swaps/handlers/claim/ClaimHandlers.d.ts +10 -10
  79. package/dist/evm/swaps/handlers/claim/ClaimHandlers.js +13 -13
  80. package/dist/evm/swaps/handlers/claim/HashlockClaimHandler.d.ts +20 -20
  81. package/dist/evm/swaps/handlers/claim/HashlockClaimHandler.js +39 -39
  82. package/dist/evm/swaps/handlers/claim/btc/BitcoinNoncedOutputClaimHandler.d.ts +24 -24
  83. package/dist/evm/swaps/handlers/claim/btc/BitcoinNoncedOutputClaimHandler.js +59 -59
  84. package/dist/evm/swaps/handlers/claim/btc/BitcoinOutputClaimHandler.d.ts +25 -25
  85. package/dist/evm/swaps/handlers/claim/btc/BitcoinOutputClaimHandler.js +51 -51
  86. package/dist/evm/swaps/handlers/claim/btc/BitcoinTxIdClaimHandler.d.ts +21 -21
  87. package/dist/evm/swaps/handlers/claim/btc/BitcoinTxIdClaimHandler.js +28 -28
  88. package/dist/evm/swaps/handlers/claim/btc/IBitcoinClaimHandler.d.ts +48 -48
  89. package/dist/evm/swaps/handlers/claim/btc/IBitcoinClaimHandler.js +63 -63
  90. package/dist/evm/swaps/handlers/refund/TimelockRefundHandler.d.ts +17 -17
  91. package/dist/evm/swaps/handlers/refund/TimelockRefundHandler.js +28 -28
  92. package/dist/evm/swaps/modules/EVMLpVault.d.ts +69 -69
  93. package/dist/evm/swaps/modules/EVMLpVault.js +134 -131
  94. package/dist/evm/swaps/modules/EVMSwapClaim.d.ts +54 -54
  95. package/dist/evm/swaps/modules/EVMSwapClaim.js +137 -137
  96. package/dist/evm/swaps/modules/EVMSwapInit.d.ts +88 -88
  97. package/dist/evm/swaps/modules/EVMSwapInit.js +274 -275
  98. package/dist/evm/swaps/modules/EVMSwapRefund.d.ts +62 -62
  99. package/dist/evm/swaps/modules/EVMSwapRefund.js +167 -167
  100. package/dist/evm/typechain/common.d.ts +50 -50
  101. package/dist/evm/typechain/common.js +2 -2
  102. package/dist/evm/wallet/EVMSigner.d.ts +9 -9
  103. package/dist/evm/wallet/EVMSigner.js +16 -16
  104. package/dist/index.d.ts +38 -38
  105. package/dist/index.js +54 -54
  106. package/dist/utils/Utils.d.ts +15 -15
  107. package/dist/utils/Utils.js +71 -71
  108. package/package.json +37 -37
  109. package/src/chains/citrea/CitreaBtcRelay.ts +57 -57
  110. package/src/chains/citrea/CitreaChainType.ts +28 -28
  111. package/src/chains/citrea/CitreaFees.ts +77 -77
  112. package/src/chains/citrea/CitreaInitializer.ts +178 -178
  113. package/src/chains/citrea/CitreaSpvVaultContract.ts +75 -75
  114. package/src/chains/citrea/CitreaSwapContract.ts +102 -102
  115. package/src/chains/citrea/CitreaTokens.ts +21 -21
  116. package/src/evm/btcrelay/BtcRelayAbi.ts +258 -258
  117. package/src/evm/btcrelay/BtcRelayTypechain.ts +371 -371
  118. package/src/evm/btcrelay/EVMBtcRelay.ts +522 -522
  119. package/src/evm/btcrelay/headers/EVMBtcHeader.ts +109 -109
  120. package/src/evm/btcrelay/headers/EVMBtcStoredHeader.ts +152 -152
  121. package/src/evm/chain/EVMChainInterface.ts +155 -155
  122. package/src/evm/chain/EVMModule.ts +21 -21
  123. package/src/evm/chain/modules/ERC20Abi.ts +222 -222
  124. package/src/evm/chain/modules/EVMAddresses.ts +28 -28
  125. package/src/evm/chain/modules/EVMBlocks.ts +75 -75
  126. package/src/evm/chain/modules/EVMEvents.ts +139 -139
  127. package/src/evm/chain/modules/EVMFees.ts +104 -104
  128. package/src/evm/chain/modules/EVMSignatures.ts +76 -76
  129. package/src/evm/chain/modules/EVMTokens.ts +155 -126
  130. package/src/evm/chain/modules/EVMTransactions.ts +246 -246
  131. package/src/evm/contract/EVMContractBase.ts +63 -63
  132. package/src/evm/contract/EVMContractModule.ts +16 -16
  133. package/src/evm/contract/modules/EVMContractEvents.ts +102 -102
  134. package/src/evm/events/EVMChainEvents.ts +81 -81
  135. package/src/evm/events/EVMChainEventsBrowser.ts +390 -390
  136. package/src/evm/spv_swap/EVMSpvVaultContract.ts +608 -603
  137. package/src/evm/spv_swap/EVMSpvVaultData.ts +224 -224
  138. package/src/evm/spv_swap/EVMSpvWithdrawalData.ts +70 -70
  139. package/src/evm/spv_swap/SpvVaultContractAbi.ts +846 -846
  140. package/src/evm/spv_swap/SpvVaultContractTypechain.ts +685 -685
  141. package/src/evm/swaps/EVMSwapContract.ts +592 -592
  142. package/src/evm/swaps/EVMSwapData.ts +378 -377
  143. package/src/evm/swaps/EVMSwapModule.ts +16 -16
  144. package/src/evm/swaps/EscrowManagerAbi.ts +982 -982
  145. package/src/evm/swaps/EscrowManagerTypechain.ts +723 -723
  146. package/src/evm/swaps/handlers/IHandler.ts +17 -17
  147. package/src/evm/swaps/handlers/claim/ClaimHandlers.ts +20 -20
  148. package/src/evm/swaps/handlers/claim/HashlockClaimHandler.ts +46 -46
  149. package/src/evm/swaps/handlers/claim/btc/BitcoinNoncedOutputClaimHandler.ts +82 -82
  150. package/src/evm/swaps/handlers/claim/btc/BitcoinOutputClaimHandler.ts +76 -76
  151. package/src/evm/swaps/handlers/claim/btc/BitcoinTxIdClaimHandler.ts +46 -46
  152. package/src/evm/swaps/handlers/claim/btc/IBitcoinClaimHandler.ts +115 -115
  153. package/src/evm/swaps/handlers/refund/TimelockRefundHandler.ts +37 -37
  154. package/src/evm/swaps/modules/EVMLpVault.ts +154 -152
  155. package/src/evm/swaps/modules/EVMSwapClaim.ts +172 -172
  156. package/src/evm/swaps/modules/EVMSwapInit.ts +328 -325
  157. package/src/evm/swaps/modules/EVMSwapRefund.ts +229 -229
  158. package/src/evm/typechain/common.ts +131 -131
  159. package/src/evm/wallet/EVMSigner.ts +23 -23
  160. package/src/index.ts +45 -45
  161. package/src/utils/Utils.ts +81 -81
@@ -1,480 +1,478 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EVMSpvVaultContract = exports.unpackOwnerAndVaultId = exports.packOwnerAndVaultId = void 0;
4
- const base_1 = require("@atomiqlabs/base");
5
- const buffer_1 = require("buffer");
6
- const EVMContractBase_1 = require("../contract/EVMContractBase");
7
- const SpvVaultContractAbi_1 = require("./SpvVaultContractAbi");
8
- const EVMBtcRelay_1 = require("../btcrelay/EVMBtcRelay");
9
- const Utils_1 = require("../../utils/Utils");
10
- const ethers_1 = require("ethers");
11
- const EVMAddresses_1 = require("../chain/modules/EVMAddresses");
12
- const EVMSpvVaultData_1 = require("./EVMSpvVaultData");
13
- const EVMSpvWithdrawalData_1 = require("./EVMSpvWithdrawalData");
14
- const EVMFees_1 = require("../chain/modules/EVMFees");
15
- function decodeUtxo(utxo) {
16
- const [txId, vout] = utxo.split(":");
17
- return {
18
- txHash: "0x" + buffer_1.Buffer.from(txId, "hex").reverse().toString("hex"),
19
- vout: BigInt(vout)
20
- };
21
- }
22
- function packOwnerAndVaultId(owner, vaultId) {
23
- if (owner.length !== 42)
24
- throw new Error("Invalid owner address");
25
- return owner.toLowerCase() + base_1.BigIntBufferUtils.toBuffer(vaultId, "be", 12).toString("hex");
26
- }
27
- exports.packOwnerAndVaultId = packOwnerAndVaultId;
28
- function unpackOwnerAndVaultId(data) {
29
- return [(0, ethers_1.getAddress)(data.substring(0, 42)), BigInt("0x" + data.substring(42, 66))];
30
- }
31
- exports.unpackOwnerAndVaultId = unpackOwnerAndVaultId;
32
- class EVMSpvVaultContract extends EVMContractBase_1.EVMContractBase {
33
- constructor(chainInterface, btcRelay, bitcoinRpc, contractAddress, contractDeploymentHeight) {
34
- super(chainInterface, contractAddress, SpvVaultContractAbi_1.SpvVaultContractAbi, contractDeploymentHeight);
35
- this.claimTimeout = 180;
36
- this.logger = (0, Utils_1.getLogger)("EVMSpvVaultContract: ");
37
- this.btcRelay = btcRelay;
38
- this.bitcoinRpc = bitcoinRpc;
39
- }
40
- //Transactions
41
- async Open(signer, vault, feeRate) {
42
- const { txHash, vout } = decodeUtxo(vault.getUtxo());
43
- const tokens = vault.getTokenData();
44
- if (tokens.length !== 2)
45
- throw new Error("Must specify exactly 2 tokens for vault!");
46
- const tx = await this.contract.open.populateTransaction(vault.vaultId, vault.getVaultParamsStruct(), txHash, vout);
47
- tx.from = signer;
48
- EVMFees_1.EVMFees.applyFeeRate(tx, EVMSpvVaultContract.GasCosts.OPEN, feeRate);
49
- return tx;
50
- }
51
- async Deposit(signer, vault, rawAmounts, feeRate) {
52
- let totalGas = EVMSpvVaultContract.GasCosts.DEPOSIT_BASE;
53
- let value = 0n;
54
- if (vault.token0.token.toLowerCase() === this.Chain.getNativeCurrencyAddress().toLowerCase()) {
55
- value += rawAmounts[0] * vault.token0.multiplier;
56
- }
57
- else {
58
- if (rawAmounts[0] > 0n)
59
- totalGas += EVMSpvVaultContract.GasCosts.DEPOSIT_ERC20;
60
- }
61
- if (vault.token1.token.toLowerCase() === this.Chain.getNativeCurrencyAddress().toLowerCase()) {
62
- value += (rawAmounts[1] ?? 0n) * vault.token1.multiplier;
63
- }
64
- else {
65
- if (rawAmounts[1] != null && rawAmounts[1] > 0n && vault.token0.token.toLowerCase() !== vault.token1.token.toLowerCase())
66
- totalGas += EVMSpvVaultContract.GasCosts.DEPOSIT_ERC20;
67
- }
68
- const tx = await this.contract.deposit.populateTransaction(vault.owner, vault.vaultId, vault.getVaultParamsStruct(), rawAmounts[0], rawAmounts[1] ?? 0n, { value });
69
- tx.from = signer;
70
- EVMFees_1.EVMFees.applyFeeRate(tx, totalGas, feeRate);
71
- return tx;
72
- }
73
- async Front(signer, vault, data, withdrawalSequence, feeRate) {
74
- let value = 0n;
75
- const frontingAmount = data.getFrontingAmount();
76
- if (vault.token0.token.toLowerCase() === this.Chain.getNativeCurrencyAddress().toLowerCase())
77
- value += frontingAmount[0] * vault.token0.multiplier;
78
- if (vault.token1.token.toLowerCase() === this.Chain.getNativeCurrencyAddress().toLowerCase())
79
- value += (frontingAmount[1] ?? 0n) * vault.token1.multiplier;
80
- const tx = await this.contract.front.populateTransaction(vault.owner, vault.vaultId, vault.getVaultParamsStruct(), withdrawalSequence, data.getTxHash(), data.serializeToStruct(), { value });
81
- tx.from = signer;
82
- EVMFees_1.EVMFees.applyFeeRate(tx, this.getFrontGas(signer, vault, data), feeRate);
83
- return tx;
84
- }
85
- async Claim(signer, vault, data, blockheader, merkle, position, feeRate) {
86
- const tx = await this.contract.claim.populateTransaction(vault.owner, vault.vaultId, vault.getVaultParamsStruct(), "0x" + data.btcTx.hex, blockheader.serializeToStruct(), merkle, position);
87
- tx.from = signer;
88
- EVMFees_1.EVMFees.applyFeeRate(tx, this.getClaimGas(signer, vault, data), feeRate);
89
- return tx;
90
- }
91
- async checkWithdrawalTx(tx) {
92
- const result = await this.contract.parseBitcoinTx(buffer_1.Buffer.from(tx.btcTx.hex, "hex"));
93
- if (result == null)
94
- throw new Error("Failed to parse transaction!");
95
- }
96
- createVaultData(owner, vaultId, utxo, confirmations, tokenData) {
97
- if (tokenData.length !== 2)
98
- throw new Error("Must specify 2 tokens in tokenData!");
99
- const vaultParams = {
100
- btcRelayContract: this.btcRelay.contractAddress,
101
- token0: tokenData[0].token,
102
- token1: tokenData[1].token,
103
- token0Multiplier: tokenData[0].multiplier,
104
- token1Multiplier: tokenData[1].multiplier,
105
- confirmations: BigInt(confirmations)
106
- };
107
- const spvVaultParametersCommitment = (0, ethers_1.keccak256)(ethers_1.AbiCoder.defaultAbiCoder().encode(["address", "address", "address", "uint192", "uint192", "uint256"], [vaultParams.btcRelayContract, vaultParams.token0, vaultParams.token1, vaultParams.token0Multiplier, vaultParams.token1Multiplier, vaultParams.confirmations]));
108
- return Promise.resolve(new EVMSpvVaultData_1.EVMSpvVaultData(owner, vaultId, {
109
- spvVaultParametersCommitment,
110
- utxoTxHash: ethers_1.ZeroHash,
111
- utxoVout: 0n,
112
- openBlockheight: 0n,
113
- withdrawCount: 0n,
114
- depositCount: 0n,
115
- token0Amount: 0n,
116
- token1Amount: 0n
117
- }, vaultParams, utxo));
118
- }
119
- //Getters
120
- async getFronterAddress(owner, vaultId, withdrawal) {
121
- const frontingAddress = await this.contract.getFronterById(owner, vaultId, "0x" + withdrawal.getFrontingId());
122
- if (frontingAddress === ethers_1.ZeroAddress)
123
- return null;
124
- return frontingAddress;
125
- }
126
- async getVaultData(owner, vaultId) {
127
- const vaultState = await this.contract.getVault(owner, vaultId);
128
- const blockheight = Number(vaultState.openBlockheight);
129
- const events = await this.Events.getContractBlockEvents(["Opened"], [
130
- "0x" + owner.substring(2).padStart(64, "0"),
131
- (0, ethers_1.hexlify)(base_1.BigIntBufferUtils.toBuffer(vaultId, "be", 32))
132
- ], blockheight);
133
- const foundEvent = events.find(event => (0, EVMSpvVaultData_1.getVaultParamsCommitment)(event.args.params) === vaultState.spvVaultParametersCommitment);
134
- if (foundEvent == null)
135
- throw new Error("Valid open event not found!");
136
- const vaultParams = foundEvent.args.params;
137
- if (vaultParams.btcRelayContract.toLowerCase() !== this.btcRelay.contractAddress.toLowerCase())
138
- return null;
139
- return new EVMSpvVaultData_1.EVMSpvVaultData(owner, vaultId, vaultState, vaultParams);
140
- }
141
- async getAllVaults(owner) {
142
- const openedVaults = new Map();
143
- await this.Events.findInContractEventsForward(["Opened", "Closed"], owner == null ? null : [
144
- "0x" + owner.substring(2).padStart(64, "0")
145
- ], (event) => {
146
- const vaultIdentifier = event.args.owner + ":" + event.args.vaultId.toString(10);
147
- if (event.eventName === "Opened") {
148
- const _event = event;
149
- openedVaults.set(vaultIdentifier, _event.args.params);
150
- }
151
- else {
152
- openedVaults.delete(vaultIdentifier);
153
- }
154
- return null;
155
- });
156
- const vaults = [];
157
- for (let [identifier, vaultParams] of openedVaults.entries()) {
158
- const [owner, vaultIdStr] = identifier.split(":");
159
- const vaultState = await this.contract.getVault(owner, BigInt(vaultIdStr));
160
- if (vaultState.spvVaultParametersCommitment === (0, EVMSpvVaultData_1.getVaultParamsCommitment)(vaultParams)) {
161
- vaults.push(new EVMSpvVaultData_1.EVMSpvVaultData(owner, BigInt(vaultIdStr), vaultState, vaultParams));
162
- }
163
- }
164
- return vaults;
165
- }
166
- async getWithdrawalState(btcTxId) {
167
- const txHash = buffer_1.Buffer.from(btcTxId, "hex").reverse();
168
- let result = await this.Events.findInContractEvents(["Fronted", "Claimed", "Closed"], [
169
- null,
170
- null,
171
- (0, ethers_1.hexlify)(txHash)
172
- ], async (event) => {
173
- switch (event.eventName) {
174
- case "Fronted":
175
- const frontedEvent = event;
176
- const [ownerFront, vaultIdFront] = unpackOwnerAndVaultId(frontedEvent.args.ownerAndVaultId);
177
- return {
178
- type: base_1.SpvWithdrawalStateType.FRONTED,
179
- txId: event.transactionHash,
180
- owner: ownerFront,
181
- vaultId: vaultIdFront,
182
- recipient: frontedEvent.args.recipient,
183
- fronter: frontedEvent.args.caller
184
- };
185
- case "Claimed":
186
- const claimedEvent = event;
187
- const [ownerClaim, vaultIdClaim] = unpackOwnerAndVaultId(claimedEvent.args.ownerAndVaultId);
188
- return {
189
- type: base_1.SpvWithdrawalStateType.CLAIMED,
190
- txId: event.transactionHash,
191
- owner: ownerClaim,
192
- vaultId: vaultIdClaim,
193
- recipient: claimedEvent.args.recipient,
194
- claimer: claimedEvent.args.caller,
195
- fronter: claimedEvent.args.frontingAddress
196
- };
197
- case "Closed":
198
- const closedEvent = event;
199
- return {
200
- type: base_1.SpvWithdrawalStateType.CLOSED,
201
- txId: event.transactionHash,
202
- owner: closedEvent.args.owner,
203
- vaultId: closedEvent.args.vaultId,
204
- error: closedEvent.args.error
205
- };
206
- }
207
- });
208
- result ?? (result = {
209
- type: base_1.SpvWithdrawalStateType.NOT_FOUND
210
- });
211
- return result;
212
- }
213
- getWithdrawalData(btcTx) {
214
- return Promise.resolve(new EVMSpvWithdrawalData_1.EVMSpvWithdrawalData(btcTx));
215
- }
216
- //OP_RETURN data encoding/decoding
217
- fromOpReturnData(data) {
218
- return EVMSpvVaultContract.fromOpReturnData(data);
219
- }
220
- static fromOpReturnData(data) {
221
- let rawAmount0 = 0n;
222
- let rawAmount1 = 0n;
223
- let executionHash = null;
224
- if (data.length === 28) {
225
- rawAmount0 = data.readBigInt64BE(20).valueOf();
226
- }
227
- else if (data.length === 36) {
228
- rawAmount0 = data.readBigInt64BE(20).valueOf();
229
- rawAmount1 = data.readBigInt64BE(28).valueOf();
230
- }
231
- else if (data.length === 60) {
232
- rawAmount0 = data.readBigInt64BE(20).valueOf();
233
- executionHash = data.slice(28, 60).toString("hex");
234
- }
235
- else if (data.length === 68) {
236
- rawAmount0 = data.readBigInt64BE(20).valueOf();
237
- rawAmount1 = data.readBigInt64BE(28).valueOf();
238
- executionHash = data.slice(36, 68).toString("hex");
239
- }
240
- else {
241
- throw new Error("Invalid OP_RETURN data length!");
242
- }
243
- const recipient = "0x" + data.slice(0, 20).toString("hex");
244
- if (!EVMAddresses_1.EVMAddresses.isValidAddress(recipient))
245
- throw new Error("Invalid recipient specified");
246
- return { executionHash, rawAmounts: [rawAmount0, rawAmount1], recipient: (0, ethers_1.getAddress)(recipient) };
247
- }
248
- toOpReturnData(recipient, rawAmounts, executionHash) {
249
- return EVMSpvVaultContract.toOpReturnData(recipient, rawAmounts, executionHash);
250
- }
251
- static toOpReturnData(recipient, rawAmounts, executionHash) {
252
- if (!EVMAddresses_1.EVMAddresses.isValidAddress(recipient))
253
- throw new Error("Invalid recipient specified");
254
- if (rawAmounts.length < 1)
255
- throw new Error("At least 1 amount needs to be specified");
256
- if (rawAmounts.length > 2)
257
- throw new Error("At most 2 amounts need to be specified");
258
- rawAmounts.forEach(val => {
259
- if (val < 0n)
260
- throw new Error("Negative raw amount specified");
261
- if (val >= 2n ** 64n)
262
- throw new Error("Raw amount overflow");
263
- });
264
- if (executionHash != null) {
265
- if (buffer_1.Buffer.from(executionHash, "hex").length !== 32)
266
- throw new Error("Invalid execution hash");
267
- }
268
- const recipientBuffer = buffer_1.Buffer.from(recipient.substring(2).padStart(40, "0"), "hex");
269
- const amount0Buffer = base_1.BigIntBufferUtils.toBuffer(rawAmounts[0], "be", 8);
270
- const amount1Buffer = rawAmounts[1] == null || rawAmounts[1] === 0n ? buffer_1.Buffer.alloc(0) : base_1.BigIntBufferUtils.toBuffer(rawAmounts[1], "be", 8);
271
- const executionHashBuffer = executionHash == null ? buffer_1.Buffer.alloc(0) : buffer_1.Buffer.from(executionHash, "hex");
272
- return buffer_1.Buffer.concat([
273
- recipientBuffer,
274
- amount0Buffer,
275
- amount1Buffer,
276
- executionHashBuffer
277
- ]);
278
- }
279
- //Actions
280
- async claim(signer, vault, txs, synchronizer, initAta, txOptions) {
281
- const result = await this.txsClaim(signer.getAddress(), vault, txs, synchronizer, initAta, txOptions?.feeRate);
282
- const [signature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
283
- return signature;
284
- }
285
- async deposit(signer, vault, rawAmounts, txOptions) {
286
- const result = await this.txsDeposit(signer.getAddress(), vault, rawAmounts, txOptions?.feeRate);
287
- const txHashes = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
288
- return txHashes[txHashes.length - 1];
289
- }
290
- async frontLiquidity(signer, vault, realWithdrawalTx, withdrawSequence, txOptions) {
291
- const result = await this.txsFrontLiquidity(signer.getAddress(), vault, realWithdrawalTx, withdrawSequence, txOptions?.feeRate);
292
- const txHashes = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
293
- return txHashes[txHashes.length - 1];
294
- }
295
- async open(signer, vault, txOptions) {
296
- const result = await this.txsOpen(signer.getAddress(), vault, txOptions?.feeRate);
297
- const [signature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
298
- return signature;
299
- }
300
- //Transactions
301
- async txsClaim(signer, vault, txs, synchronizer, initAta, feeRate) {
302
- if (!vault.isOpened())
303
- throw new Error("Cannot claim from a closed vault!");
304
- feeRate ?? (feeRate = await this.Chain.Fees.getFeeRate());
305
- const txsWithMerkleProofs = [];
306
- for (let tx of txs) {
307
- const merkleProof = await this.bitcoinRpc.getMerkleProof(tx.tx.btcTx.txid, tx.tx.btcTx.blockhash);
308
- this.logger.debug("txsClaim(): merkle proof computed: ", merkleProof);
309
- txsWithMerkleProofs.push({
310
- ...merkleProof,
311
- ...tx
312
- });
313
- }
314
- const evmTxs = [];
315
- const storedHeaders = await EVMBtcRelay_1.EVMBtcRelay.getCommitedHeadersAndSynchronize(signer, this.btcRelay, txsWithMerkleProofs.filter(tx => tx.storedHeader == null).map(tx => {
316
- return {
317
- blockhash: tx.tx.btcTx.blockhash,
318
- blockheight: tx.blockheight,
319
- requiredConfirmations: vault.getConfirmations()
320
- };
321
- }), evmTxs, synchronizer, feeRate);
322
- if (storedHeaders == null)
323
- throw new Error("Cannot fetch committed header!");
324
- for (let tx of txsWithMerkleProofs) {
325
- evmTxs.push(await this.Claim(signer, vault, tx.tx, tx.storedHeader ?? storedHeaders[tx.tx.btcTx.blockhash], tx.merkle, tx.pos, feeRate));
326
- }
327
- this.logger.debug("txsClaim(): " + evmTxs.length + " claim TXs created claiming " + txs.length + " txs, owner: " + vault.getOwner() +
328
- " vaultId: " + vault.getVaultId().toString(10));
329
- return evmTxs;
330
- }
331
- async txsDeposit(signer, vault, rawAmounts, feeRate) {
332
- var _a;
333
- if (!vault.isOpened())
334
- throw new Error("Cannot deposit to a closed vault!");
335
- feeRate ?? (feeRate = await this.Chain.Fees.getFeeRate());
336
- const txs = [];
337
- let realAmount0 = 0n;
338
- let realAmount1 = 0n;
339
- //Approve first
340
- const requiredApprovals = {};
341
- if (rawAmounts[0] != null && rawAmounts[0] !== 0n) {
342
- if (vault.token0.token.toLowerCase() !== this.Chain.getNativeCurrencyAddress().toLowerCase()) {
343
- realAmount0 = rawAmounts[0] * vault.token0.multiplier;
344
- requiredApprovals[vault.token0.token.toLowerCase()] = realAmount0;
345
- }
346
- }
347
- if (rawAmounts[1] != null && rawAmounts[1] !== 0n) {
348
- if (vault.token1.token.toLowerCase() !== this.Chain.getNativeCurrencyAddress().toLowerCase()) {
349
- realAmount1 = rawAmounts[1] * vault.token1.multiplier;
350
- requiredApprovals[_a = vault.token1.token.toLowerCase()] ?? (requiredApprovals[_a] = 0n);
351
- requiredApprovals[vault.token1.token.toLowerCase()] += realAmount1;
352
- }
353
- }
354
- for (let tokenAddress in requiredApprovals) {
355
- txs.push(await this.Chain.Tokens.Approve(signer, tokenAddress, requiredApprovals[tokenAddress], this.contractAddress, feeRate));
356
- }
357
- txs.push(await this.Deposit(signer, vault, rawAmounts, feeRate));
358
- this.logger.debug("txsDeposit(): deposit TX created," +
359
- " token0: " + vault.token0.token + " rawAmount0: " + rawAmounts[0].toString(10) + " amount0: " + realAmount0.toString(10) +
360
- " token1: " + vault.token1.token + " rawAmount1: " + (rawAmounts[1] ?? 0n).toString(10) + " amount1: " + realAmount1.toString(10));
361
- return txs;
362
- }
363
- async txsFrontLiquidity(signer, vault, realWithdrawalTx, withdrawSequence, feeRate) {
364
- var _a;
365
- if (!vault.isOpened())
366
- throw new Error("Cannot front on a closed vault!");
367
- feeRate ?? (feeRate = await this.Chain.Fees.getFeeRate());
368
- const txs = [];
369
- let realAmount0 = 0n;
370
- let realAmount1 = 0n;
371
- //Approve first
372
- const rawAmounts = realWithdrawalTx.getFrontingAmount();
373
- //Approve first
374
- const requiredApprovals = {};
375
- if (rawAmounts[0] != null && rawAmounts[0] !== 0n) {
376
- if (vault.token0.token.toLowerCase() !== this.Chain.getNativeCurrencyAddress().toLowerCase()) {
377
- realAmount0 = rawAmounts[0] * vault.token0.multiplier;
378
- requiredApprovals[vault.token0.token.toLowerCase()] = realAmount0;
379
- }
380
- }
381
- if (rawAmounts[1] != null && rawAmounts[1] !== 0n) {
382
- if (vault.token1.token.toLowerCase() !== this.Chain.getNativeCurrencyAddress().toLowerCase()) {
383
- realAmount1 = rawAmounts[1] * vault.token1.multiplier;
384
- requiredApprovals[_a = vault.token1.token.toLowerCase()] ?? (requiredApprovals[_a] = 0n);
385
- requiredApprovals[vault.token1.token.toLowerCase()] += realAmount1;
386
- }
387
- }
388
- for (let tokenAddress in requiredApprovals) {
389
- txs.push(await this.Chain.Tokens.Approve(signer, tokenAddress, requiredApprovals[tokenAddress], this.contractAddress, feeRate));
390
- }
391
- txs.push(await this.Front(signer, vault, realWithdrawalTx, withdrawSequence, feeRate));
392
- this.logger.debug("txsFrontLiquidity(): front TX created," +
393
- " token0: " + vault.token0.token + " rawAmount0: " + rawAmounts[0].toString(10) + " amount0: " + realAmount0.toString(10) +
394
- " token1: " + vault.token1.token + " rawAmount1: " + (rawAmounts[1] ?? 0n).toString(10) + " amount1: " + realAmount1.toString(10));
395
- return txs;
396
- }
397
- async txsOpen(signer, vault, feeRate) {
398
- if (vault.isOpened())
399
- throw new Error("Cannot open an already opened vault!");
400
- feeRate ?? (feeRate = await this.Chain.Fees.getFeeRate());
401
- const tx = await this.Open(signer, vault, feeRate);
402
- this.logger.debug("txsOpen(): open TX created, owner: " + vault.getOwner() +
403
- " vaultId: " + vault.getVaultId().toString(10));
404
- return [tx];
405
- }
406
- getClaimGas(signer, vault, data) {
407
- let totalGas = EVMSpvVaultContract.GasCosts.CLAIM_BASE;
408
- if (data == null || (data.rawAmounts[0] != null && data.rawAmounts[0] > 0n)) {
409
- const transferFee = vault.token0.token.toLowerCase() === this.Chain.getNativeCurrencyAddress() ?
410
- EVMSpvVaultContract.GasCosts.CLAIM_NATIVE_TRANSFER : EVMSpvVaultContract.GasCosts.CLAIM_ERC20_TRANSFER;
411
- totalGas += transferFee;
412
- if (data == null || data.frontingFeeRate > 0n)
413
- totalGas += transferFee; //Also needs to pay out to fronter
414
- if (data == null || (data.callerFeeRate > 0n && !data.isRecipient(signer)))
415
- totalGas += transferFee; //Also needs to pay out to caller
416
- }
417
- if (data == null || (data.rawAmounts[1] != null && data.rawAmounts[1] > 0n)) {
418
- const transferFee = vault.token1.token.toLowerCase() === this.Chain.getNativeCurrencyAddress() ?
419
- EVMSpvVaultContract.GasCosts.CLAIM_NATIVE_TRANSFER : EVMSpvVaultContract.GasCosts.CLAIM_ERC20_TRANSFER;
420
- totalGas += transferFee;
421
- if (data == null || data.frontingFeeRate > 0n)
422
- totalGas += transferFee; //Also needs to pay out to fronter
423
- if (data == null || (data.callerFeeRate > 0n && !data.isRecipient(signer)))
424
- totalGas += transferFee; //Also needs to pay out to caller
425
- }
426
- if (data == null || (data.executionHash != null && data.executionHash !== ethers_1.ZeroHash))
427
- totalGas += EVMSpvVaultContract.GasCosts.CLAIM_EXECUTION_SCHEDULE;
428
- return totalGas;
429
- }
430
- getFrontGas(signer, vault, data) {
431
- let totalGas = EVMSpvVaultContract.GasCosts.FRONT_BASE;
432
- if (data == null || (data.rawAmounts[0] != null && data.rawAmounts[0] > 0n)) {
433
- totalGas += vault.token0.token.toLowerCase() === this.Chain.getNativeCurrencyAddress() ?
434
- EVMSpvVaultContract.GasCosts.FRONT_NATIVE_TRANSFER : EVMSpvVaultContract.GasCosts.FRONT_ERC20_TRANSFER;
435
- }
436
- if (data == null || (data.rawAmounts[1] != null && data.rawAmounts[1] > 0n)) {
437
- totalGas += vault.token1.token.toLowerCase() === this.Chain.getNativeCurrencyAddress() ?
438
- EVMSpvVaultContract.GasCosts.FRONT_NATIVE_TRANSFER : EVMSpvVaultContract.GasCosts.FRONT_ERC20_TRANSFER;
439
- }
440
- if (data == null || (data.executionHash != null && data.executionHash !== ethers_1.ZeroHash))
441
- totalGas += EVMSpvVaultContract.GasCosts.FRONT_EXECUTION_SCHEDULE;
442
- return totalGas;
443
- }
444
- async getClaimFee(signer, vault, withdrawalData, feeRate) {
445
- feeRate ?? (feeRate = await this.Chain.Fees.getFeeRate());
446
- return EVMFees_1.EVMFees.getGasFee(this.getClaimGas(signer, vault, withdrawalData), feeRate);
447
- }
448
- async getFrontFee(signer, vault, withdrawalData, feeRate) {
449
- vault ?? (vault = EVMSpvVaultData_1.EVMSpvVaultData.randomVault());
450
- feeRate ?? (feeRate = await this.Chain.Fees.getFeeRate());
451
- let totalFee = EVMFees_1.EVMFees.getGasFee(this.getFrontGas(signer, vault, withdrawalData), feeRate);
452
- if (withdrawalData == null || (withdrawalData.rawAmounts[0] != null && withdrawalData.rawAmounts[0] > 0n)) {
453
- if (vault.token0.token.toLowerCase() !== this.Chain.getNativeCurrencyAddress().toLowerCase()) {
454
- totalFee += await this.Chain.Tokens.getApproveFee(feeRate);
455
- }
456
- }
457
- if (withdrawalData == null || (withdrawalData.rawAmounts[1] != null && withdrawalData.rawAmounts[1] > 0n)) {
458
- if (vault.token1.token.toLowerCase() !== this.Chain.getNativeCurrencyAddress().toLowerCase()) {
459
- if (vault.token1.token.toLowerCase() !== vault.token0.token.toLowerCase() || withdrawalData == null || withdrawalData.rawAmounts[0] == null || withdrawalData.rawAmounts[0] === 0n) {
460
- totalFee += await this.Chain.Tokens.getApproveFee(feeRate);
461
- }
462
- }
463
- }
464
- return totalFee;
465
- }
466
- }
467
- exports.EVMSpvVaultContract = EVMSpvVaultContract;
468
- EVMSpvVaultContract.GasCosts = {
469
- DEPOSIT_BASE: 15000 + 21000,
470
- DEPOSIT_ERC20: 40000,
471
- OPEN: 80000 + 21000,
472
- CLAIM_BASE: 85000 + 21000,
473
- CLAIM_NATIVE_TRANSFER: 7500,
474
- CLAIM_ERC20_TRANSFER: 40000,
475
- CLAIM_EXECUTION_SCHEDULE: 30000,
476
- FRONT_BASE: 75000 + 21000,
477
- FRONT_NATIVE_TRANSFER: 7500,
478
- FRONT_ERC20_TRANSFER: 40000,
479
- FRONT_EXECUTION_SCHEDULE: 30000
480
- };
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EVMSpvVaultContract = exports.unpackOwnerAndVaultId = exports.packOwnerAndVaultId = void 0;
4
+ const base_1 = require("@atomiqlabs/base");
5
+ const buffer_1 = require("buffer");
6
+ const EVMContractBase_1 = require("../contract/EVMContractBase");
7
+ const SpvVaultContractAbi_1 = require("./SpvVaultContractAbi");
8
+ const EVMBtcRelay_1 = require("../btcrelay/EVMBtcRelay");
9
+ const Utils_1 = require("../../utils/Utils");
10
+ const ethers_1 = require("ethers");
11
+ const EVMAddresses_1 = require("../chain/modules/EVMAddresses");
12
+ const EVMSpvVaultData_1 = require("./EVMSpvVaultData");
13
+ const EVMSpvWithdrawalData_1 = require("./EVMSpvWithdrawalData");
14
+ const EVMFees_1 = require("../chain/modules/EVMFees");
15
+ function decodeUtxo(utxo) {
16
+ const [txId, vout] = utxo.split(":");
17
+ return {
18
+ txHash: "0x" + buffer_1.Buffer.from(txId, "hex").reverse().toString("hex"),
19
+ vout: BigInt(vout)
20
+ };
21
+ }
22
+ function packOwnerAndVaultId(owner, vaultId) {
23
+ if (owner.length !== 42)
24
+ throw new Error("Invalid owner address");
25
+ return owner.toLowerCase() + base_1.BigIntBufferUtils.toBuffer(vaultId, "be", 12).toString("hex");
26
+ }
27
+ exports.packOwnerAndVaultId = packOwnerAndVaultId;
28
+ function unpackOwnerAndVaultId(data) {
29
+ return [(0, ethers_1.getAddress)(data.substring(0, 42)), BigInt("0x" + data.substring(42, 66))];
30
+ }
31
+ exports.unpackOwnerAndVaultId = unpackOwnerAndVaultId;
32
+ class EVMSpvVaultContract extends EVMContractBase_1.EVMContractBase {
33
+ constructor(chainInterface, btcRelay, bitcoinRpc, contractAddress, contractDeploymentHeight) {
34
+ super(chainInterface, contractAddress, SpvVaultContractAbi_1.SpvVaultContractAbi, contractDeploymentHeight);
35
+ this.claimTimeout = 180;
36
+ this.logger = (0, Utils_1.getLogger)("EVMSpvVaultContract: ");
37
+ this.btcRelay = btcRelay;
38
+ this.bitcoinRpc = bitcoinRpc;
39
+ }
40
+ //Transactions
41
+ async Open(signer, vault, feeRate) {
42
+ const { txHash, vout } = decodeUtxo(vault.getUtxo());
43
+ const tokens = vault.getTokenData();
44
+ if (tokens.length !== 2)
45
+ throw new Error("Must specify exactly 2 tokens for vault!");
46
+ const tx = await this.contract.open.populateTransaction(vault.vaultId, vault.getVaultParamsStruct(), txHash, vout);
47
+ tx.from = signer;
48
+ EVMFees_1.EVMFees.applyFeeRate(tx, EVMSpvVaultContract.GasCosts.OPEN, feeRate);
49
+ return tx;
50
+ }
51
+ async Deposit(signer, vault, rawAmounts, feeRate) {
52
+ let totalGas = EVMSpvVaultContract.GasCosts.DEPOSIT_BASE;
53
+ let value = 0n;
54
+ if (vault.token0.token.toLowerCase() === this.Chain.getNativeCurrencyAddress().toLowerCase()) {
55
+ value += rawAmounts[0] * vault.token0.multiplier;
56
+ }
57
+ else {
58
+ if (rawAmounts[0] > 0n)
59
+ totalGas += EVMSpvVaultContract.GasCosts.DEPOSIT_ERC20;
60
+ }
61
+ if (vault.token1.token.toLowerCase() === this.Chain.getNativeCurrencyAddress().toLowerCase()) {
62
+ value += (rawAmounts[1] ?? 0n) * vault.token1.multiplier;
63
+ }
64
+ else {
65
+ if (rawAmounts[1] != null && rawAmounts[1] > 0n && vault.token0.token.toLowerCase() !== vault.token1.token.toLowerCase())
66
+ totalGas += EVMSpvVaultContract.GasCosts.DEPOSIT_ERC20;
67
+ }
68
+ const tx = await this.contract.deposit.populateTransaction(vault.owner, vault.vaultId, vault.getVaultParamsStruct(), rawAmounts[0], rawAmounts[1] ?? 0n, { value });
69
+ tx.from = signer;
70
+ EVMFees_1.EVMFees.applyFeeRate(tx, totalGas, feeRate);
71
+ return tx;
72
+ }
73
+ async Front(signer, vault, data, withdrawalSequence, feeRate) {
74
+ let value = 0n;
75
+ const frontingAmount = data.getFrontingAmount();
76
+ if (vault.token0.token.toLowerCase() === this.Chain.getNativeCurrencyAddress().toLowerCase())
77
+ value += frontingAmount[0] * vault.token0.multiplier;
78
+ if (vault.token1.token.toLowerCase() === this.Chain.getNativeCurrencyAddress().toLowerCase())
79
+ value += (frontingAmount[1] ?? 0n) * vault.token1.multiplier;
80
+ const tx = await this.contract.front.populateTransaction(vault.owner, vault.vaultId, vault.getVaultParamsStruct(), withdrawalSequence, data.getTxHash(), data.serializeToStruct(), { value });
81
+ tx.from = signer;
82
+ EVMFees_1.EVMFees.applyFeeRate(tx, this.getFrontGas(signer, vault, data), feeRate);
83
+ return tx;
84
+ }
85
+ async Claim(signer, vault, data, blockheader, merkle, position, feeRate) {
86
+ const tx = await this.contract.claim.populateTransaction(vault.owner, vault.vaultId, vault.getVaultParamsStruct(), "0x" + data.btcTx.hex, blockheader.serializeToStruct(), merkle, position);
87
+ tx.from = signer;
88
+ EVMFees_1.EVMFees.applyFeeRate(tx, this.getClaimGas(signer, vault, data), feeRate);
89
+ return tx;
90
+ }
91
+ async checkWithdrawalTx(tx) {
92
+ const result = await this.contract.parseBitcoinTx(buffer_1.Buffer.from(tx.btcTx.hex, "hex"));
93
+ if (result == null)
94
+ throw new Error("Failed to parse transaction!");
95
+ }
96
+ createVaultData(owner, vaultId, utxo, confirmations, tokenData) {
97
+ if (tokenData.length !== 2)
98
+ throw new Error("Must specify 2 tokens in tokenData!");
99
+ const vaultParams = {
100
+ btcRelayContract: this.btcRelay.contractAddress,
101
+ token0: tokenData[0].token,
102
+ token1: tokenData[1].token,
103
+ token0Multiplier: tokenData[0].multiplier,
104
+ token1Multiplier: tokenData[1].multiplier,
105
+ confirmations: BigInt(confirmations)
106
+ };
107
+ const spvVaultParametersCommitment = (0, ethers_1.keccak256)(ethers_1.AbiCoder.defaultAbiCoder().encode(["address", "address", "address", "uint192", "uint192", "uint256"], [vaultParams.btcRelayContract, vaultParams.token0, vaultParams.token1, vaultParams.token0Multiplier, vaultParams.token1Multiplier, vaultParams.confirmations]));
108
+ return Promise.resolve(new EVMSpvVaultData_1.EVMSpvVaultData(owner, vaultId, {
109
+ spvVaultParametersCommitment,
110
+ utxoTxHash: ethers_1.ZeroHash,
111
+ utxoVout: 0n,
112
+ openBlockheight: 0n,
113
+ withdrawCount: 0n,
114
+ depositCount: 0n,
115
+ token0Amount: 0n,
116
+ token1Amount: 0n
117
+ }, vaultParams, utxo));
118
+ }
119
+ //Getters
120
+ async getFronterAddress(owner, vaultId, withdrawal) {
121
+ const frontingAddress = await this.contract.getFronterById(owner, vaultId, "0x" + withdrawal.getFrontingId());
122
+ if (frontingAddress === ethers_1.ZeroAddress)
123
+ return null;
124
+ return frontingAddress;
125
+ }
126
+ async getVaultData(owner, vaultId) {
127
+ const vaultState = await this.contract.getVault(owner, vaultId);
128
+ const blockheight = Number(vaultState.openBlockheight);
129
+ const events = await this.Events.getContractBlockEvents(["Opened"], [
130
+ "0x" + owner.substring(2).padStart(64, "0"),
131
+ (0, ethers_1.hexlify)(base_1.BigIntBufferUtils.toBuffer(vaultId, "be", 32))
132
+ ], blockheight);
133
+ const foundEvent = events.find(event => (0, EVMSpvVaultData_1.getVaultParamsCommitment)(event.args.params) === vaultState.spvVaultParametersCommitment);
134
+ if (foundEvent == null)
135
+ throw new Error("Valid open event not found!");
136
+ const vaultParams = foundEvent.args.params;
137
+ if (vaultParams.btcRelayContract.toLowerCase() !== this.btcRelay.contractAddress.toLowerCase())
138
+ return null;
139
+ return new EVMSpvVaultData_1.EVMSpvVaultData(owner, vaultId, vaultState, vaultParams);
140
+ }
141
+ async getAllVaults(owner) {
142
+ const openedVaults = new Map();
143
+ await this.Events.findInContractEventsForward(["Opened", "Closed"], owner == null ? null : [
144
+ "0x" + owner.substring(2).padStart(64, "0")
145
+ ], (event) => {
146
+ const vaultIdentifier = event.args.owner + ":" + event.args.vaultId.toString(10);
147
+ if (event.eventName === "Opened") {
148
+ const _event = event;
149
+ openedVaults.set(vaultIdentifier, _event.args.params);
150
+ }
151
+ else {
152
+ openedVaults.delete(vaultIdentifier);
153
+ }
154
+ return null;
155
+ });
156
+ const vaults = [];
157
+ for (let [identifier, vaultParams] of openedVaults.entries()) {
158
+ const [owner, vaultIdStr] = identifier.split(":");
159
+ const vaultState = await this.contract.getVault(owner, BigInt(vaultIdStr));
160
+ if (vaultState.spvVaultParametersCommitment === (0, EVMSpvVaultData_1.getVaultParamsCommitment)(vaultParams)) {
161
+ vaults.push(new EVMSpvVaultData_1.EVMSpvVaultData(owner, BigInt(vaultIdStr), vaultState, vaultParams));
162
+ }
163
+ }
164
+ return vaults;
165
+ }
166
+ async getWithdrawalState(btcTxId) {
167
+ const txHash = buffer_1.Buffer.from(btcTxId, "hex").reverse();
168
+ let result = await this.Events.findInContractEvents(["Fronted", "Claimed", "Closed"], [
169
+ null,
170
+ null,
171
+ (0, ethers_1.hexlify)(txHash)
172
+ ], async (event) => {
173
+ switch (event.eventName) {
174
+ case "Fronted":
175
+ const frontedEvent = event;
176
+ const [ownerFront, vaultIdFront] = unpackOwnerAndVaultId(frontedEvent.args.ownerAndVaultId);
177
+ return {
178
+ type: base_1.SpvWithdrawalStateType.FRONTED,
179
+ txId: event.transactionHash,
180
+ owner: ownerFront,
181
+ vaultId: vaultIdFront,
182
+ recipient: frontedEvent.args.recipient,
183
+ fronter: frontedEvent.args.caller
184
+ };
185
+ case "Claimed":
186
+ const claimedEvent = event;
187
+ const [ownerClaim, vaultIdClaim] = unpackOwnerAndVaultId(claimedEvent.args.ownerAndVaultId);
188
+ return {
189
+ type: base_1.SpvWithdrawalStateType.CLAIMED,
190
+ txId: event.transactionHash,
191
+ owner: ownerClaim,
192
+ vaultId: vaultIdClaim,
193
+ recipient: claimedEvent.args.recipient,
194
+ claimer: claimedEvent.args.caller,
195
+ fronter: claimedEvent.args.frontingAddress
196
+ };
197
+ case "Closed":
198
+ const closedEvent = event;
199
+ return {
200
+ type: base_1.SpvWithdrawalStateType.CLOSED,
201
+ txId: event.transactionHash,
202
+ owner: closedEvent.args.owner,
203
+ vaultId: closedEvent.args.vaultId,
204
+ error: closedEvent.args.error
205
+ };
206
+ }
207
+ });
208
+ result ?? (result = {
209
+ type: base_1.SpvWithdrawalStateType.NOT_FOUND
210
+ });
211
+ return result;
212
+ }
213
+ getWithdrawalData(btcTx) {
214
+ return Promise.resolve(new EVMSpvWithdrawalData_1.EVMSpvWithdrawalData(btcTx));
215
+ }
216
+ //OP_RETURN data encoding/decoding
217
+ fromOpReturnData(data) {
218
+ return EVMSpvVaultContract.fromOpReturnData(data);
219
+ }
220
+ static fromOpReturnData(data) {
221
+ let rawAmount0 = 0n;
222
+ let rawAmount1 = 0n;
223
+ let executionHash = null;
224
+ if (data.length === 28) {
225
+ rawAmount0 = data.readBigInt64BE(20).valueOf();
226
+ }
227
+ else if (data.length === 36) {
228
+ rawAmount0 = data.readBigInt64BE(20).valueOf();
229
+ rawAmount1 = data.readBigInt64BE(28).valueOf();
230
+ }
231
+ else if (data.length === 60) {
232
+ rawAmount0 = data.readBigInt64BE(20).valueOf();
233
+ executionHash = data.slice(28, 60).toString("hex");
234
+ }
235
+ else if (data.length === 68) {
236
+ rawAmount0 = data.readBigInt64BE(20).valueOf();
237
+ rawAmount1 = data.readBigInt64BE(28).valueOf();
238
+ executionHash = data.slice(36, 68).toString("hex");
239
+ }
240
+ else {
241
+ throw new Error("Invalid OP_RETURN data length!");
242
+ }
243
+ const recipient = "0x" + data.slice(0, 20).toString("hex");
244
+ if (!EVMAddresses_1.EVMAddresses.isValidAddress(recipient))
245
+ throw new Error("Invalid recipient specified");
246
+ return { executionHash, rawAmounts: [rawAmount0, rawAmount1], recipient: (0, ethers_1.getAddress)(recipient) };
247
+ }
248
+ toOpReturnData(recipient, rawAmounts, executionHash) {
249
+ return EVMSpvVaultContract.toOpReturnData(recipient, rawAmounts, executionHash);
250
+ }
251
+ static toOpReturnData(recipient, rawAmounts, executionHash) {
252
+ if (!EVMAddresses_1.EVMAddresses.isValidAddress(recipient))
253
+ throw new Error("Invalid recipient specified");
254
+ if (rawAmounts.length < 1)
255
+ throw new Error("At least 1 amount needs to be specified");
256
+ if (rawAmounts.length > 2)
257
+ throw new Error("At most 2 amounts need to be specified");
258
+ rawAmounts.forEach(val => {
259
+ if (val < 0n)
260
+ throw new Error("Negative raw amount specified");
261
+ if (val >= 2n ** 64n)
262
+ throw new Error("Raw amount overflow");
263
+ });
264
+ if (executionHash != null) {
265
+ if (buffer_1.Buffer.from(executionHash, "hex").length !== 32)
266
+ throw new Error("Invalid execution hash");
267
+ }
268
+ const recipientBuffer = buffer_1.Buffer.from(recipient.substring(2).padStart(40, "0"), "hex");
269
+ const amount0Buffer = base_1.BigIntBufferUtils.toBuffer(rawAmounts[0], "be", 8);
270
+ const amount1Buffer = rawAmounts[1] == null || rawAmounts[1] === 0n ? buffer_1.Buffer.alloc(0) : base_1.BigIntBufferUtils.toBuffer(rawAmounts[1], "be", 8);
271
+ const executionHashBuffer = executionHash == null ? buffer_1.Buffer.alloc(0) : buffer_1.Buffer.from(executionHash, "hex");
272
+ return buffer_1.Buffer.concat([
273
+ recipientBuffer,
274
+ amount0Buffer,
275
+ amount1Buffer,
276
+ executionHashBuffer
277
+ ]);
278
+ }
279
+ //Actions
280
+ async claim(signer, vault, txs, synchronizer, initAta, txOptions) {
281
+ const result = await this.txsClaim(signer.getAddress(), vault, txs, synchronizer, initAta, txOptions?.feeRate);
282
+ const [signature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
283
+ return signature;
284
+ }
285
+ async deposit(signer, vault, rawAmounts, txOptions) {
286
+ const result = await this.txsDeposit(signer.getAddress(), vault, rawAmounts, txOptions?.feeRate);
287
+ const txHashes = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
288
+ return txHashes[txHashes.length - 1];
289
+ }
290
+ async frontLiquidity(signer, vault, realWithdrawalTx, withdrawSequence, txOptions) {
291
+ const result = await this.txsFrontLiquidity(signer.getAddress(), vault, realWithdrawalTx, withdrawSequence, txOptions?.feeRate);
292
+ const txHashes = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
293
+ return txHashes[txHashes.length - 1];
294
+ }
295
+ async open(signer, vault, txOptions) {
296
+ const result = await this.txsOpen(signer.getAddress(), vault, txOptions?.feeRate);
297
+ const [signature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
298
+ return signature;
299
+ }
300
+ //Transactions
301
+ async txsClaim(signer, vault, txs, synchronizer, initAta, feeRate) {
302
+ if (!vault.isOpened())
303
+ throw new Error("Cannot claim from a closed vault!");
304
+ feeRate ?? (feeRate = await this.Chain.Fees.getFeeRate());
305
+ const txsWithMerkleProofs = [];
306
+ for (let tx of txs) {
307
+ const merkleProof = await this.bitcoinRpc.getMerkleProof(tx.tx.btcTx.txid, tx.tx.btcTx.blockhash);
308
+ this.logger.debug("txsClaim(): merkle proof computed: ", merkleProof);
309
+ txsWithMerkleProofs.push({
310
+ ...merkleProof,
311
+ ...tx
312
+ });
313
+ }
314
+ const evmTxs = [];
315
+ const storedHeaders = await EVMBtcRelay_1.EVMBtcRelay.getCommitedHeadersAndSynchronize(signer, this.btcRelay, txsWithMerkleProofs.filter(tx => tx.storedHeader == null).map(tx => {
316
+ return {
317
+ blockhash: tx.tx.btcTx.blockhash,
318
+ blockheight: tx.blockheight,
319
+ requiredConfirmations: vault.getConfirmations()
320
+ };
321
+ }), evmTxs, synchronizer, feeRate);
322
+ if (storedHeaders == null)
323
+ throw new Error("Cannot fetch committed header!");
324
+ for (let tx of txsWithMerkleProofs) {
325
+ evmTxs.push(await this.Claim(signer, vault, tx.tx, tx.storedHeader ?? storedHeaders[tx.tx.btcTx.blockhash], tx.merkle, tx.pos, feeRate));
326
+ }
327
+ this.logger.debug("txsClaim(): " + evmTxs.length + " claim TXs created claiming " + txs.length + " txs, owner: " + vault.getOwner() +
328
+ " vaultId: " + vault.getVaultId().toString(10));
329
+ return evmTxs;
330
+ }
331
+ async txsDeposit(signer, vault, rawAmounts, feeRate) {
332
+ var _a;
333
+ if (!vault.isOpened())
334
+ throw new Error("Cannot deposit to a closed vault!");
335
+ feeRate ?? (feeRate = await this.Chain.Fees.getFeeRate());
336
+ const txs = [];
337
+ let realAmount0 = 0n;
338
+ let realAmount1 = 0n;
339
+ //Approve first
340
+ const requiredApprovals = {};
341
+ if (rawAmounts[0] != null && rawAmounts[0] !== 0n) {
342
+ if (vault.token0.token.toLowerCase() !== this.Chain.getNativeCurrencyAddress().toLowerCase()) {
343
+ realAmount0 = rawAmounts[0] * vault.token0.multiplier;
344
+ requiredApprovals[vault.token0.token.toLowerCase()] = realAmount0;
345
+ }
346
+ }
347
+ if (rawAmounts[1] != null && rawAmounts[1] !== 0n) {
348
+ if (vault.token1.token.toLowerCase() !== this.Chain.getNativeCurrencyAddress().toLowerCase()) {
349
+ realAmount1 = rawAmounts[1] * vault.token1.multiplier;
350
+ requiredApprovals[_a = vault.token1.token.toLowerCase()] ?? (requiredApprovals[_a] = 0n);
351
+ requiredApprovals[vault.token1.token.toLowerCase()] += realAmount1;
352
+ }
353
+ }
354
+ const requiredApprovalTxns = await Promise.all(Object.keys(requiredApprovals).map(token => this.Chain.Tokens.checkAndGetApproveTx(signer, token, requiredApprovals[token], this.contractAddress, feeRate)));
355
+ requiredApprovalTxns.forEach(tx => tx != null && txs.push(tx));
356
+ txs.push(await this.Deposit(signer, vault, rawAmounts, feeRate));
357
+ this.logger.debug("txsDeposit(): deposit TX created," +
358
+ " token0: " + vault.token0.token + " rawAmount0: " + rawAmounts[0].toString(10) + " amount0: " + realAmount0.toString(10) +
359
+ " token1: " + vault.token1.token + " rawAmount1: " + (rawAmounts[1] ?? 0n).toString(10) + " amount1: " + realAmount1.toString(10));
360
+ return txs;
361
+ }
362
+ async txsFrontLiquidity(signer, vault, realWithdrawalTx, withdrawSequence, feeRate) {
363
+ var _a;
364
+ if (!vault.isOpened())
365
+ throw new Error("Cannot front on a closed vault!");
366
+ feeRate ?? (feeRate = await this.Chain.Fees.getFeeRate());
367
+ const txs = [];
368
+ let realAmount0 = 0n;
369
+ let realAmount1 = 0n;
370
+ //Approve first
371
+ const rawAmounts = realWithdrawalTx.getFrontingAmount();
372
+ //Approve first
373
+ const requiredApprovals = {};
374
+ if (rawAmounts[0] != null && rawAmounts[0] !== 0n) {
375
+ if (vault.token0.token.toLowerCase() !== this.Chain.getNativeCurrencyAddress().toLowerCase()) {
376
+ realAmount0 = rawAmounts[0] * vault.token0.multiplier;
377
+ requiredApprovals[vault.token0.token.toLowerCase()] = realAmount0;
378
+ }
379
+ }
380
+ if (rawAmounts[1] != null && rawAmounts[1] !== 0n) {
381
+ if (vault.token1.token.toLowerCase() !== this.Chain.getNativeCurrencyAddress().toLowerCase()) {
382
+ realAmount1 = rawAmounts[1] * vault.token1.multiplier;
383
+ requiredApprovals[_a = vault.token1.token.toLowerCase()] ?? (requiredApprovals[_a] = 0n);
384
+ requiredApprovals[vault.token1.token.toLowerCase()] += realAmount1;
385
+ }
386
+ }
387
+ const requiredApprovalTxns = await Promise.all(Object.keys(requiredApprovals).map(token => this.Chain.Tokens.checkAndGetApproveTx(signer, token, requiredApprovals[token], this.contractAddress, feeRate)));
388
+ requiredApprovalTxns.forEach(tx => tx != null && txs.push(tx));
389
+ txs.push(await this.Front(signer, vault, realWithdrawalTx, withdrawSequence, feeRate));
390
+ this.logger.debug("txsFrontLiquidity(): front TX created," +
391
+ " token0: " + vault.token0.token + " rawAmount0: " + rawAmounts[0].toString(10) + " amount0: " + realAmount0.toString(10) +
392
+ " token1: " + vault.token1.token + " rawAmount1: " + (rawAmounts[1] ?? 0n).toString(10) + " amount1: " + realAmount1.toString(10));
393
+ return txs;
394
+ }
395
+ async txsOpen(signer, vault, feeRate) {
396
+ if (vault.isOpened())
397
+ throw new Error("Cannot open an already opened vault!");
398
+ feeRate ?? (feeRate = await this.Chain.Fees.getFeeRate());
399
+ const tx = await this.Open(signer, vault, feeRate);
400
+ this.logger.debug("txsOpen(): open TX created, owner: " + vault.getOwner() +
401
+ " vaultId: " + vault.getVaultId().toString(10));
402
+ return [tx];
403
+ }
404
+ getClaimGas(signer, vault, data) {
405
+ let totalGas = EVMSpvVaultContract.GasCosts.CLAIM_BASE;
406
+ if (data == null || (data.rawAmounts[0] != null && data.rawAmounts[0] > 0n)) {
407
+ const transferFee = vault.token0.token.toLowerCase() === this.Chain.getNativeCurrencyAddress() ?
408
+ EVMSpvVaultContract.GasCosts.CLAIM_NATIVE_TRANSFER : EVMSpvVaultContract.GasCosts.CLAIM_ERC20_TRANSFER;
409
+ totalGas += transferFee;
410
+ if (data == null || data.frontingFeeRate > 0n)
411
+ totalGas += transferFee; //Also needs to pay out to fronter
412
+ if (data == null || (data.callerFeeRate > 0n && !data.isRecipient(signer)))
413
+ totalGas += transferFee; //Also needs to pay out to caller
414
+ }
415
+ if (data == null || (data.rawAmounts[1] != null && data.rawAmounts[1] > 0n)) {
416
+ const transferFee = vault.token1.token.toLowerCase() === this.Chain.getNativeCurrencyAddress() ?
417
+ EVMSpvVaultContract.GasCosts.CLAIM_NATIVE_TRANSFER : EVMSpvVaultContract.GasCosts.CLAIM_ERC20_TRANSFER;
418
+ totalGas += transferFee;
419
+ if (data == null || data.frontingFeeRate > 0n)
420
+ totalGas += transferFee; //Also needs to pay out to fronter
421
+ if (data == null || (data.callerFeeRate > 0n && !data.isRecipient(signer)))
422
+ totalGas += transferFee; //Also needs to pay out to caller
423
+ }
424
+ if (data == null || (data.executionHash != null && data.executionHash !== ethers_1.ZeroHash))
425
+ totalGas += EVMSpvVaultContract.GasCosts.CLAIM_EXECUTION_SCHEDULE;
426
+ return totalGas;
427
+ }
428
+ getFrontGas(signer, vault, data) {
429
+ let totalGas = EVMSpvVaultContract.GasCosts.FRONT_BASE;
430
+ if (data == null || (data.rawAmounts[0] != null && data.rawAmounts[0] > 0n)) {
431
+ totalGas += vault.token0.token.toLowerCase() === this.Chain.getNativeCurrencyAddress() ?
432
+ EVMSpvVaultContract.GasCosts.FRONT_NATIVE_TRANSFER : EVMSpvVaultContract.GasCosts.FRONT_ERC20_TRANSFER;
433
+ }
434
+ if (data == null || (data.rawAmounts[1] != null && data.rawAmounts[1] > 0n)) {
435
+ totalGas += vault.token1.token.toLowerCase() === this.Chain.getNativeCurrencyAddress() ?
436
+ EVMSpvVaultContract.GasCosts.FRONT_NATIVE_TRANSFER : EVMSpvVaultContract.GasCosts.FRONT_ERC20_TRANSFER;
437
+ }
438
+ if (data == null || (data.executionHash != null && data.executionHash !== ethers_1.ZeroHash))
439
+ totalGas += EVMSpvVaultContract.GasCosts.FRONT_EXECUTION_SCHEDULE;
440
+ return totalGas;
441
+ }
442
+ async getClaimFee(signer, vault, withdrawalData, feeRate) {
443
+ feeRate ?? (feeRate = await this.Chain.Fees.getFeeRate());
444
+ return EVMFees_1.EVMFees.getGasFee(this.getClaimGas(signer, vault, withdrawalData), feeRate);
445
+ }
446
+ async getFrontFee(signer, vault, withdrawalData, feeRate) {
447
+ vault ?? (vault = EVMSpvVaultData_1.EVMSpvVaultData.randomVault());
448
+ feeRate ?? (feeRate = await this.Chain.Fees.getFeeRate());
449
+ let totalFee = EVMFees_1.EVMFees.getGasFee(this.getFrontGas(signer, vault, withdrawalData), feeRate);
450
+ if (withdrawalData == null || (withdrawalData.rawAmounts[0] != null && withdrawalData.rawAmounts[0] > 0n)) {
451
+ if (vault.token0.token.toLowerCase() !== this.Chain.getNativeCurrencyAddress().toLowerCase()) {
452
+ totalFee += await this.Chain.Tokens.getApproveFee(feeRate);
453
+ }
454
+ }
455
+ if (withdrawalData == null || (withdrawalData.rawAmounts[1] != null && withdrawalData.rawAmounts[1] > 0n)) {
456
+ if (vault.token1.token.toLowerCase() !== this.Chain.getNativeCurrencyAddress().toLowerCase()) {
457
+ if (vault.token1.token.toLowerCase() !== vault.token0.token.toLowerCase() || withdrawalData == null || withdrawalData.rawAmounts[0] == null || withdrawalData.rawAmounts[0] === 0n) {
458
+ totalFee += await this.Chain.Tokens.getApproveFee(feeRate);
459
+ }
460
+ }
461
+ }
462
+ return totalFee;
463
+ }
464
+ }
465
+ exports.EVMSpvVaultContract = EVMSpvVaultContract;
466
+ EVMSpvVaultContract.GasCosts = {
467
+ DEPOSIT_BASE: 15000 + 21000,
468
+ DEPOSIT_ERC20: 40000,
469
+ OPEN: 80000 + 21000,
470
+ CLAIM_BASE: 85000 + 21000,
471
+ CLAIM_NATIVE_TRANSFER: 7500,
472
+ CLAIM_ERC20_TRANSFER: 40000,
473
+ CLAIM_EXECUTION_SCHEDULE: 30000,
474
+ FRONT_BASE: 75000 + 21000,
475
+ FRONT_NATIVE_TRANSFER: 7500,
476
+ FRONT_ERC20_TRANSFER: 40000,
477
+ FRONT_EXECUTION_SCHEDULE: 30000
478
+ };