@atomiqlabs/chain-evm 1.0.0-dev.75 → 1.0.0-dev.77

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