@atomiqlabs/chain-evm 1.0.0-dev.62 → 1.0.0-dev.64

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 (187) 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 +195 -195
  25. package/dist/evm/btcrelay/EVMBtcRelay.js +423 -423
  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 +73 -73
  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 +89 -89
  49. package/dist/evm/chain/modules/EVMTransactions.js +235 -235
  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 +402 -400
  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 -20
  63. package/dist/evm/providers/ReconnectingWebSocketProvider.js +87 -77
  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 +78 -78
  69. package/dist/evm/spv_swap/EVMSpvVaultContract.js +478 -478
  70. package/dist/evm/spv_swap/EVMSpvVaultData.d.ts +39 -39
  71. package/dist/evm/spv_swap/EVMSpvVaultData.js +180 -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/EVMSigner.d.ts +10 -10
  115. package/dist/evm/wallet/EVMSigner.js +17 -17
  116. package/dist/index.d.ts +43 -43
  117. package/dist/index.js +59 -59
  118. package/dist/utils/Utils.d.ts +15 -15
  119. package/dist/utils/Utils.js +71 -71
  120. package/package.json +37 -37
  121. package/src/chains/botanix/BotanixChainType.ts +28 -28
  122. package/src/chains/botanix/BotanixInitializer.ts +171 -171
  123. package/src/chains/citrea/CitreaBtcRelay.ts +57 -57
  124. package/src/chains/citrea/CitreaChainType.ts +28 -28
  125. package/src/chains/citrea/CitreaFees.ts +77 -77
  126. package/src/chains/citrea/CitreaInitializer.ts +178 -178
  127. package/src/chains/citrea/CitreaSpvVaultContract.ts +75 -75
  128. package/src/chains/citrea/CitreaSwapContract.ts +102 -102
  129. package/src/chains/citrea/CitreaTokens.ts +21 -21
  130. package/src/evm/btcrelay/BtcRelayAbi.ts +258 -258
  131. package/src/evm/btcrelay/BtcRelayTypechain.ts +371 -371
  132. package/src/evm/btcrelay/EVMBtcRelay.ts +522 -522
  133. package/src/evm/btcrelay/headers/EVMBtcHeader.ts +109 -109
  134. package/src/evm/btcrelay/headers/EVMBtcStoredHeader.ts +152 -152
  135. package/src/evm/chain/EVMChainInterface.ts +155 -155
  136. package/src/evm/chain/EVMModule.ts +21 -21
  137. package/src/evm/chain/modules/ERC20Abi.ts +222 -222
  138. package/src/evm/chain/modules/EVMAddresses.ts +28 -28
  139. package/src/evm/chain/modules/EVMBlocks.ts +75 -75
  140. package/src/evm/chain/modules/EVMEvents.ts +139 -139
  141. package/src/evm/chain/modules/EVMFees.ts +104 -104
  142. package/src/evm/chain/modules/EVMSignatures.ts +76 -76
  143. package/src/evm/chain/modules/EVMTokens.ts +155 -155
  144. package/src/evm/chain/modules/EVMTransactions.ts +263 -263
  145. package/src/evm/contract/EVMContractBase.ts +63 -63
  146. package/src/evm/contract/EVMContractModule.ts +16 -16
  147. package/src/evm/contract/modules/EVMContractEvents.ts +102 -102
  148. package/src/evm/events/EVMChainEvents.ts +82 -82
  149. package/src/evm/events/EVMChainEventsBrowser.ts +524 -523
  150. package/src/evm/providers/JsonRpcProviderWithRetries.ts +26 -26
  151. package/src/evm/providers/ReconnectingWebSocketProvider.ts +101 -93
  152. package/src/evm/providers/SocketProvider.ts +368 -368
  153. package/src/evm/providers/WebSocketProviderWithRetries.ts +28 -28
  154. package/src/evm/spv_swap/EVMSpvVaultContract.ts +608 -608
  155. package/src/evm/spv_swap/EVMSpvVaultData.ts +224 -224
  156. package/src/evm/spv_swap/EVMSpvWithdrawalData.ts +70 -70
  157. package/src/evm/spv_swap/SpvVaultContractAbi.ts +846 -846
  158. package/src/evm/spv_swap/SpvVaultContractTypechain.ts +685 -685
  159. package/src/evm/swaps/EVMSwapContract.ts +600 -600
  160. package/src/evm/swaps/EVMSwapData.ts +378 -378
  161. package/src/evm/swaps/EVMSwapModule.ts +16 -16
  162. package/src/evm/swaps/EscrowManagerAbi.ts +982 -982
  163. package/src/evm/swaps/EscrowManagerTypechain.ts +723 -723
  164. package/src/evm/swaps/handlers/IHandler.ts +17 -17
  165. package/src/evm/swaps/handlers/claim/ClaimHandlers.ts +20 -20
  166. package/src/evm/swaps/handlers/claim/HashlockClaimHandler.ts +46 -46
  167. package/src/evm/swaps/handlers/claim/btc/BitcoinNoncedOutputClaimHandler.ts +82 -82
  168. package/src/evm/swaps/handlers/claim/btc/BitcoinOutputClaimHandler.ts +76 -76
  169. package/src/evm/swaps/handlers/claim/btc/BitcoinTxIdClaimHandler.ts +46 -46
  170. package/src/evm/swaps/handlers/claim/btc/IBitcoinClaimHandler.ts +115 -115
  171. package/src/evm/swaps/handlers/refund/TimelockRefundHandler.ts +37 -37
  172. package/src/evm/swaps/modules/EVMLpVault.ts +154 -154
  173. package/src/evm/swaps/modules/EVMSwapClaim.ts +172 -172
  174. package/src/evm/swaps/modules/EVMSwapInit.ts +328 -328
  175. package/src/evm/swaps/modules/EVMSwapRefund.ts +229 -229
  176. package/src/evm/typechain/common.ts +131 -131
  177. package/src/evm/wallet/EVMSigner.ts +25 -25
  178. package/src/index.ts +52 -52
  179. package/src/utils/Utils.ts +81 -81
  180. package/dist/evm/JsonRpcProviderWithRetries.d.ts +0 -15
  181. package/dist/evm/JsonRpcProviderWithRetries.js +0 -19
  182. package/dist/evm/ReconnectingWebSocketProvider.d.ts +0 -20
  183. package/dist/evm/ReconnectingWebSocketProvider.js +0 -77
  184. package/dist/evm/SocketProvider.d.ts +0 -111
  185. package/dist/evm/SocketProvider.js +0 -334
  186. package/dist/evm/WebSocketProviderWithRetries.d.ts +0 -17
  187. package/dist/evm/WebSocketProviderWithRetries.js +0 -19
@@ -1,600 +1,600 @@
1
- import {
2
- BigIntBufferUtils,
3
- ChainSwapType,
4
- IntermediaryReputationType,
5
- RelaySynchronizer,
6
- SignatureData, SwapCommitState, SwapCommitStateType,
7
- SwapContract,
8
- TransactionConfirmationOptions
9
- } from "@atomiqlabs/base";
10
- import {Buffer} from "buffer";
11
- import {TimelockRefundHandler} from "./handlers/refund/TimelockRefundHandler";
12
- import {claimHandlersList, IClaimHandler} from "./handlers/claim/ClaimHandlers"
13
- import {IHandler} from "./handlers/IHandler";
14
- import {sha256} from "@noble/hashes/sha2";
15
- import { EVMContractBase } from "../contract/EVMContractBase";
16
- import {EscrowManager} from "./EscrowManagerTypechain";
17
- import { EVMSwapData } from "./EVMSwapData";
18
- import {EVMTx} from "../chain/modules/EVMTransactions";
19
- import { EVMSigner } from "../wallet/EVMSigner";
20
- import {EVMChainInterface} from "../chain/EVMChainInterface";
21
- import { EVMBtcRelay } from "../btcrelay/EVMBtcRelay";
22
- import {EscrowManagerAbi} from "./EscrowManagerAbi";
23
- import {hexlify} from "ethers";
24
- import {EVMBtcStoredHeader} from "../btcrelay/headers/EVMBtcStoredHeader";
25
- import {EVMLpVault} from "./modules/EVMLpVault";
26
- import {EVMPreFetchVerification, EVMSwapInit} from "./modules/EVMSwapInit";
27
- import { EVMSwapRefund } from "./modules/EVMSwapRefund";
28
- import {EVMSwapClaim} from "./modules/EVMSwapClaim";
29
-
30
- const ESCROW_STATE_COMMITTED = 1;
31
- const ESCROW_STATE_CLAIMED = 2;
32
- const ESCROW_STATE_REFUNDED = 3;
33
-
34
- export class EVMSwapContract<ChainId extends string = string>
35
- extends EVMContractBase<EscrowManager>
36
- implements SwapContract<
37
- EVMSwapData,
38
- EVMTx,
39
- never,
40
- EVMPreFetchVerification,
41
- EVMSigner,
42
- ChainId
43
- > {
44
-
45
- readonly supportsInitWithoutClaimer = true;
46
-
47
- ////////////////////////
48
- //// Constants
49
- readonly chainId: ChainId;
50
-
51
- ////////////////////////
52
- //// Timeouts
53
- readonly claimWithSecretTimeout: number = 180;
54
- readonly claimWithTxDataTimeout: number = 180;
55
- readonly refundTimeout: number = 180;
56
- readonly claimGracePeriod: number = 10*60;
57
- readonly refundGracePeriod: number = 10*60;
58
- readonly authGracePeriod: number = 30;
59
-
60
- ////////////////////////
61
- //// Services
62
- readonly Init: EVMSwapInit;
63
- readonly Refund: EVMSwapRefund;
64
- readonly Claim: EVMSwapClaim;
65
- readonly LpVault: EVMLpVault;
66
-
67
- ////////////////////////
68
- //// Handlers
69
- readonly claimHandlersByAddress: {[address: string]: IClaimHandler<any, any>} = {};
70
- readonly claimHandlersBySwapType: {[type in ChainSwapType]?: IClaimHandler<any, any>} = {};
71
-
72
- readonly refundHandlersByAddress: {[address: string]: IHandler<any, any>} = {};
73
- readonly timelockRefundHandler: IHandler<any, any>;
74
-
75
- readonly btcRelay: EVMBtcRelay<any>;
76
-
77
- constructor(
78
- chainInterface: EVMChainInterface<ChainId>,
79
- btcRelay: EVMBtcRelay<any>,
80
- contractAddress: string,
81
- handlerAddresses: {
82
- refund: {
83
- timelock: string
84
- },
85
- claim: {
86
- [type in ChainSwapType]: string
87
- }
88
- }
89
- ) {
90
- super(chainInterface, contractAddress, EscrowManagerAbi);
91
- this.chainId = chainInterface.chainId;
92
- this.Init = new EVMSwapInit(chainInterface, this);
93
- this.Refund = new EVMSwapRefund(chainInterface, this);
94
- this.Claim = new EVMSwapClaim(chainInterface, this);
95
- this.LpVault = new EVMLpVault(chainInterface, this);
96
-
97
- this.btcRelay = btcRelay;
98
-
99
- claimHandlersList.forEach(handlerCtor => {
100
- const handler = new handlerCtor(handlerAddresses.claim[handlerCtor.type]);
101
- this.claimHandlersByAddress[handler.address.toLowerCase()] = handler;
102
- this.claimHandlersBySwapType[handlerCtor.type] = handler;
103
- });
104
-
105
- this.timelockRefundHandler = new TimelockRefundHandler(handlerAddresses.refund.timelock);
106
- this.refundHandlersByAddress[this.timelockRefundHandler.address.toLowerCase()] = this.timelockRefundHandler;
107
- }
108
-
109
- async start(): Promise<void> {
110
- }
111
-
112
- ////////////////////////////////////////////
113
- //// Signatures
114
- preFetchForInitSignatureVerification(): Promise<EVMPreFetchVerification> {
115
- return this.Init.preFetchForInitSignatureVerification();
116
- }
117
-
118
- getInitSignature(signer: EVMSigner, swapData: EVMSwapData, authorizationTimeout: number, preFetchedBlockData?: never, feeRate?: string): Promise<SignatureData> {
119
- return this.Init.signSwapInitialization(signer, swapData, authorizationTimeout);
120
- }
121
-
122
- isValidInitAuthorization(sender: string, swapData: EVMSwapData, {timeout, prefix, signature}, feeRate?: string, preFetchedData?: EVMPreFetchVerification): Promise<Buffer> {
123
- return this.Init.isSignatureValid(sender, swapData, timeout, prefix, signature, preFetchedData);
124
- }
125
-
126
- getInitAuthorizationExpiry(swapData: EVMSwapData, {timeout, prefix, signature}, preFetchedData?: EVMPreFetchVerification): Promise<number> {
127
- return this.Init.getSignatureExpiry(timeout);
128
- }
129
-
130
- isInitAuthorizationExpired(swapData: EVMSwapData, {timeout, prefix, signature}): Promise<boolean> {
131
- return this.Init.isSignatureExpired(timeout);
132
- }
133
-
134
- getRefundSignature(signer: EVMSigner, swapData: EVMSwapData, authorizationTimeout: number): Promise<SignatureData> {
135
- return this.Refund.signSwapRefund(signer, swapData, authorizationTimeout);
136
- }
137
-
138
- isValidRefundAuthorization(swapData: EVMSwapData, {timeout, prefix, signature}): Promise<Buffer> {
139
- return this.Refund.isSignatureValid(swapData, timeout, prefix, signature);
140
- }
141
-
142
- getDataSignature(signer: EVMSigner, data: Buffer): Promise<string> {
143
- return this.Chain.Signatures.getDataSignature(signer, data);
144
- }
145
-
146
- isValidDataSignature(data: Buffer, signature: string, publicKey: string): Promise<boolean> {
147
- return this.Chain.Signatures.isValidDataSignature(data, signature, publicKey);
148
- }
149
-
150
- ////////////////////////////////////////////
151
- //// Swap data utils
152
- /**
153
- * Checks whether the claim is claimable by us, that means not expired, we are claimer & the swap is commited
154
- *
155
- * @param signer
156
- * @param data
157
- */
158
- async isClaimable(signer: string, data: EVMSwapData): Promise<boolean> {
159
- if(!data.isClaimer(signer)) return false;
160
- if(await this.isExpired(signer, data)) return false;
161
- return await this.isCommited(data);
162
- }
163
-
164
- /**
165
- * Checks whether a swap is commited, i.e. the swap still exists on-chain and was not claimed nor refunded
166
- *
167
- * @param swapData
168
- */
169
- async isCommited(swapData: EVMSwapData): Promise<boolean> {
170
- const data = await this.contract.getHashState("0x"+swapData.getEscrowHash());
171
- return Number(data.state)===ESCROW_STATE_COMMITTED;
172
- }
173
-
174
- /**
175
- * Checks whether the swap is expired, takes into consideration possible on-chain time skew, therefore for claimer
176
- * the swap expires a bit sooner than it should've & for the offerer it expires a bit later
177
- *
178
- * @param signer
179
- * @param data
180
- */
181
- isExpired(signer: string, data: EVMSwapData): Promise<boolean> {
182
- let currentTimestamp: bigint = BigInt(Math.floor(Date.now()/1000));
183
- if(data.isClaimer(signer)) currentTimestamp = currentTimestamp + BigInt(this.claimGracePeriod);
184
- if(data.isOfferer(signer)) currentTimestamp = currentTimestamp - BigInt(this.refundGracePeriod);
185
- return Promise.resolve(data.getExpiry() < currentTimestamp);
186
- }
187
-
188
- /**
189
- * Checks if the swap is refundable by us, checks if we are offerer, if the swap is already expired & if the swap
190
- * is still commited
191
- *
192
- * @param signer
193
- * @param data
194
- */
195
- async isRequestRefundable(signer: string, data: EVMSwapData): Promise<boolean> {
196
- //Swap can only be refunded by the offerer
197
- if(!data.isOfferer(signer)) return false;
198
- if(!(await this.isExpired(signer, data))) return false;
199
- return await this.isCommited(data);
200
- }
201
-
202
- getHashForTxId(txId: string, confirmations: number) {
203
- return Buffer.from(this.claimHandlersBySwapType[ChainSwapType.CHAIN_TXID].getCommitment({
204
- txId,
205
- confirmations,
206
- btcRelay: this.btcRelay
207
- }).slice(2), "hex");
208
- }
209
-
210
- /**
211
- * Get the swap payment hash to be used for an on-chain swap, uses poseidon hash of the value
212
- *
213
- * @param outputScript output script required to claim the swap
214
- * @param amount sats sent required to claim the swap
215
- * @param confirmations
216
- * @param nonce swap nonce uniquely identifying the transaction to prevent replay attacks
217
- */
218
- getHashForOnchain(outputScript: Buffer, amount: bigint, confirmations: number, nonce?: bigint): Buffer {
219
- let result: string;
220
- if(nonce==null || nonce === 0n) {
221
- result = this.claimHandlersBySwapType[ChainSwapType.CHAIN].getCommitment({
222
- output: outputScript,
223
- amount,
224
- confirmations,
225
- btcRelay: this.btcRelay
226
- });
227
- } else {
228
- result = this.claimHandlersBySwapType[ChainSwapType.CHAIN_NONCED].getCommitment({
229
- output: outputScript,
230
- amount,
231
- nonce,
232
- confirmations,
233
- btcRelay: this.btcRelay
234
- });
235
- }
236
- return Buffer.from(result.slice(2), "hex");
237
- }
238
-
239
- /**
240
- * Get the swap payment hash to be used for a lightning htlc swap, uses poseidon hash of the sha256 hash of the preimage
241
- *
242
- * @param paymentHash payment hash of the HTLC
243
- */
244
- getHashForHtlc(paymentHash: Buffer): Buffer {
245
- return Buffer.from(this.claimHandlersBySwapType[ChainSwapType.HTLC].getCommitment(paymentHash).slice(2), "hex");
246
- }
247
-
248
- getExtraData(outputScript: Buffer, amount: bigint, confirmations: number, nonce?: bigint): Buffer {
249
- if(nonce==null) nonce = 0n;
250
- const txoHash = Buffer.from(sha256(Buffer.concat([
251
- BigIntBufferUtils.toBuffer(amount, "le", 8),
252
- outputScript
253
- ])));
254
- return Buffer.concat([
255
- txoHash,
256
- BigIntBufferUtils.toBuffer(nonce, "be", 8),
257
- BigIntBufferUtils.toBuffer(BigInt(confirmations), "be", 2)
258
- ]);
259
- }
260
-
261
-
262
- ////////////////////////////////////////////
263
- //// Swap data getters
264
- /**
265
- * Gets the status of the specific swap, this also checks if we are offerer/claimer & checks for expiry (to see
266
- * if swap is refundable)
267
- *
268
- * @param signer
269
- * @param data
270
- */
271
- async getCommitStatus(signer: string, data: EVMSwapData): Promise<SwapCommitState> {
272
- const escrowHash = data.getEscrowHash();
273
- const stateData = await this.contract.getHashState("0x"+escrowHash);
274
- const state = Number(stateData.state);
275
- const blockHeight = Number(stateData.finishBlockheight);
276
- switch(state) {
277
- case ESCROW_STATE_COMMITTED:
278
- if(data.isOfferer(signer) && await this.isExpired(signer,data)) return {type: SwapCommitStateType.REFUNDABLE};
279
- return {type: SwapCommitStateType.COMMITED};
280
- case ESCROW_STATE_CLAIMED:
281
- return {
282
- type: SwapCommitStateType.PAID,
283
- getTxBlock: async () => {
284
- return {
285
- blockTime: await this.Chain.Blocks.getBlockTime(blockHeight),
286
- blockHeight: blockHeight
287
- };
288
- },
289
- getClaimResult: async () => {
290
- const events = await this.Events.getContractBlockEvents(
291
- ["Claim"],
292
- [null, null, "0x"+escrowHash],
293
- blockHeight, blockHeight
294
- );
295
- return events.length===0 ? null : events[0].args.witnessResult;
296
- },
297
- getClaimTxId: async () => {
298
- const events = await this.Events.getContractBlockEvents(
299
- ["Claim"],
300
- [null, null, "0x"+escrowHash],
301
- blockHeight, blockHeight
302
- );
303
- return events.length===0 ? null : events[0].transactionHash;
304
- }
305
- };
306
- default:
307
- return {
308
- type: await this.isExpired(signer, data) ? SwapCommitStateType.EXPIRED : SwapCommitStateType.NOT_COMMITED,
309
- getTxBlock: async () => {
310
- return {
311
- blockTime: await this.Chain.Blocks.getBlockTime(blockHeight),
312
- blockHeight: blockHeight
313
- };
314
- },
315
- getRefundTxId: async () => {
316
- const events = await this.Events.getContractBlockEvents(
317
- ["Refund"],
318
- [null, null, "0x"+escrowHash],
319
- blockHeight, blockHeight
320
- );
321
- return events.length===0 ? null : events[0].transactionHash;
322
- }
323
- };
324
- }
325
- }
326
-
327
- /**
328
- * Returns the data committed for a specific payment hash, or null if no data is currently commited for
329
- * the specific swap
330
- *
331
- * @param paymentHashHex
332
- */
333
- async getCommitedData(paymentHashHex: string): Promise<EVMSwapData> {
334
- //TODO: Noop
335
- return null;
336
- }
337
-
338
- ////////////////////////////////////////////
339
- //// Swap data initializer
340
- createSwapData(
341
- type: ChainSwapType,
342
- offerer: string,
343
- claimer: string,
344
- token: string,
345
- amount: bigint,
346
- paymentHash: string,
347
- sequence: bigint,
348
- expiry: bigint,
349
- payIn: boolean,
350
- payOut: boolean,
351
- securityDeposit: bigint,
352
- claimerBounty: bigint,
353
- depositToken: string = this.Chain.Tokens.getNativeCurrencyAddress()
354
- ): Promise<EVMSwapData> {
355
- return Promise.resolve(new EVMSwapData(
356
- offerer,
357
- claimer,
358
- token,
359
- this.timelockRefundHandler.address,
360
- this.claimHandlersBySwapType?.[type]?.address,
361
- payOut,
362
- payIn,
363
- payIn, //For now track reputation for all payIn swaps
364
- sequence,
365
- "0x"+paymentHash,
366
- hexlify(BigIntBufferUtils.toBuffer(expiry, "be", 32)),
367
- amount,
368
- depositToken,
369
- securityDeposit,
370
- claimerBounty,
371
- type,
372
- null
373
- ));
374
- }
375
-
376
- ////////////////////////////////////////////
377
- //// Utils
378
- async getBalance(signer: string, tokenAddress: string, inContract?: boolean): Promise<bigint> {
379
- if(inContract) return await this.getIntermediaryBalance(signer, tokenAddress);
380
-
381
- return await this.Chain.getBalance(signer, tokenAddress);
382
- }
383
-
384
- getIntermediaryData(address: string, token: string): Promise<{
385
- balance: bigint,
386
- reputation: IntermediaryReputationType
387
- }> {
388
- return this.LpVault.getIntermediaryData(address, token);
389
- }
390
-
391
- getIntermediaryReputation(address: string, token: string): Promise<IntermediaryReputationType> {
392
- return this.LpVault.getIntermediaryReputation(address, token);
393
- }
394
-
395
- getIntermediaryBalance(address: string, token: string): Promise<bigint> {
396
- return this.LpVault.getIntermediaryBalance(address, token);
397
- }
398
-
399
- ////////////////////////////////////////////
400
- //// Transaction initializers
401
- async txsClaimWithSecret(
402
- signer: string | EVMSigner,
403
- swapData: EVMSwapData,
404
- secret: string,
405
- checkExpiry?: boolean,
406
- initAta?: boolean,
407
- feeRate?: string,
408
- skipAtaCheck?: boolean
409
- ): Promise<EVMTx[]> {
410
- return this.Claim.txsClaimWithSecret(typeof(signer)==="string" ? signer : signer.getAddress(), swapData, secret, checkExpiry, feeRate)
411
- }
412
-
413
- async txsClaimWithTxData(
414
- signer: string | EVMSigner,
415
- swapData: EVMSwapData,
416
- tx: { blockhash: string, confirmations: number, txid: string, hex: string, height: number },
417
- requiredConfirmations: number,
418
- vout: number,
419
- commitedHeader?: EVMBtcStoredHeader,
420
- synchronizer?: RelaySynchronizer<EVMBtcStoredHeader, EVMTx, any>,
421
- initAta?: boolean,
422
- feeRate?: string
423
- ): Promise<EVMTx[] | null> {
424
- return this.Claim.txsClaimWithTxData(
425
- typeof(signer)==="string" ? signer : signer.getAddress(),
426
- swapData,
427
- tx,
428
- requiredConfirmations,
429
- vout,
430
- commitedHeader,
431
- synchronizer,
432
- feeRate
433
- );
434
- }
435
-
436
- txsRefund(signer: string, swapData: EVMSwapData, check?: boolean, initAta?: boolean, feeRate?: string): Promise<EVMTx[]> {
437
- return this.Refund.txsRefund(signer, swapData, check, feeRate);
438
- }
439
-
440
- txsRefundWithAuthorization(signer: string, swapData: EVMSwapData, {timeout, prefix, signature}, check?: boolean, initAta?: boolean, feeRate?: string): Promise<EVMTx[]> {
441
- return this.Refund.txsRefundWithAuthorization(signer, swapData, timeout, prefix,signature, check, feeRate);
442
- }
443
-
444
- txsInit(signer: string, swapData: EVMSwapData, {timeout, prefix, signature}, skipChecks?: boolean, feeRate?: string): Promise<EVMTx[]> {
445
- return this.Init.txsInit(signer, swapData, timeout, prefix, signature, skipChecks, feeRate);
446
- }
447
-
448
- txsWithdraw(signer: string, token: string, amount: bigint, feeRate?: string): Promise<EVMTx[]> {
449
- return this.LpVault.txsWithdraw(signer, token, amount, feeRate);
450
- }
451
-
452
- txsDeposit(signer: string, token: string, amount: bigint, feeRate?: string): Promise<EVMTx[]> {
453
- return this.LpVault.txsDeposit(signer, token, amount, feeRate);
454
- }
455
-
456
- ////////////////////////////////////////////
457
- //// Executors
458
- async claimWithSecret(
459
- signer: EVMSigner,
460
- swapData: EVMSwapData,
461
- secret: string,
462
- checkExpiry?: boolean,
463
- initAta?: boolean,
464
- txOptions?: TransactionConfirmationOptions
465
- ): Promise<string> {
466
- const result = await this.Claim.txsClaimWithSecret(signer.getAddress(), swapData, secret, checkExpiry, txOptions?.feeRate);
467
- const [signature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
468
- return signature;
469
- }
470
-
471
- async claimWithTxData(
472
- signer: EVMSigner,
473
- swapData: EVMSwapData,
474
- tx: { blockhash: string, confirmations: number, txid: string, hex: string, height: number },
475
- requiredConfirmations: number,
476
- vout: number,
477
- commitedHeader?: EVMBtcStoredHeader,
478
- synchronizer?: RelaySynchronizer<EVMBtcStoredHeader, EVMTx, any>,
479
- initAta?: boolean,
480
- txOptions?: TransactionConfirmationOptions
481
- ): Promise<string> {
482
- const txs = await this.Claim.txsClaimWithTxData(
483
- signer.getAddress(), swapData, tx, requiredConfirmations, vout,
484
- commitedHeader, synchronizer, txOptions?.feeRate
485
- );
486
- if(txs===null) throw new Error("Btc relay not synchronized to required blockheight!");
487
-
488
- const txHashes = await this.Chain.sendAndConfirm(signer, txs, txOptions?.waitForConfirmation, txOptions?.abortSignal);
489
-
490
- return txHashes[txHashes.length - 1];
491
- }
492
-
493
- async refund(
494
- signer: EVMSigner,
495
- swapData: EVMSwapData,
496
- check?: boolean,
497
- initAta?: boolean,
498
- txOptions?: TransactionConfirmationOptions
499
- ): Promise<string> {
500
- let result = await this.txsRefund(signer.getAddress(), swapData, check, initAta, txOptions?.feeRate);
501
-
502
- const [signature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
503
-
504
- return signature;
505
- }
506
-
507
- async refundWithAuthorization(
508
- signer: EVMSigner,
509
- swapData: EVMSwapData,
510
- signature: SignatureData,
511
- check?: boolean,
512
- initAta?: boolean,
513
- txOptions?: TransactionConfirmationOptions
514
- ): Promise<string> {
515
- let result = await this.txsRefundWithAuthorization(signer.getAddress(), swapData, signature, check, initAta, txOptions?.feeRate);
516
-
517
- const [txSignature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
518
-
519
- return txSignature;
520
- }
521
-
522
- async init(
523
- signer: EVMSigner,
524
- swapData: EVMSwapData,
525
- signature: SignatureData,
526
- skipChecks?: boolean,
527
- txOptions?: TransactionConfirmationOptions
528
- ): Promise<string> {
529
- if(swapData.isPayIn()) {
530
- if(!swapData.isOfferer(signer.getAddress()) && !swapData.isOfferer(signer.getAddress())) throw new Error("Invalid signer provided!");
531
- } else {
532
- if(!swapData.isClaimer(signer.getAddress()) && !swapData.isOfferer(signer.getAddress())) throw new Error("Invalid signer provided!");
533
- }
534
-
535
- let result = await this.txsInit(signer.getAddress(), swapData, signature, skipChecks, txOptions?.feeRate);
536
-
537
- const txHashes = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
538
-
539
- return txHashes[txHashes.length - 1];
540
- }
541
-
542
- async withdraw(
543
- signer: EVMSigner,
544
- token: string,
545
- amount: bigint,
546
- txOptions?: TransactionConfirmationOptions
547
- ): Promise<string> {
548
- const txs = await this.LpVault.txsWithdraw(signer.getAddress(), token, amount, txOptions?.feeRate);
549
- const [txId] = await this.Chain.sendAndConfirm(signer, txs, txOptions?.waitForConfirmation, txOptions?.abortSignal, false);
550
- return txId;
551
- }
552
-
553
- async deposit(
554
- signer: EVMSigner,
555
- token: string,
556
- amount: bigint,
557
- txOptions?: TransactionConfirmationOptions
558
- ): Promise<string> {
559
- const txs = await this.LpVault.txsDeposit(signer.getAddress(), token, amount, txOptions?.feeRate);
560
- const [txId] = await this.Chain.sendAndConfirm(signer, txs, txOptions?.waitForConfirmation, txOptions?.abortSignal, false);
561
- return txId;
562
- }
563
-
564
- ////////////////////////////////////////////
565
- //// Fees
566
- getInitPayInFeeRate(offerer?: string, claimer?: string, token?: string, paymentHash?: string): Promise<string> {
567
- return this.Chain.Fees.getFeeRate();
568
- }
569
-
570
- getInitFeeRate(offerer?: string, claimer?: string, token?: string, paymentHash?: string): Promise<string> {
571
- return this.Chain.Fees.getFeeRate();
572
- }
573
-
574
- getRefundFeeRate(swapData: EVMSwapData): Promise<string> {
575
- return this.Chain.Fees.getFeeRate();
576
- }
577
-
578
- getClaimFeeRate(signer: string, swapData: EVMSwapData): Promise<string> {
579
- return this.Chain.Fees.getFeeRate();
580
- }
581
-
582
- getClaimFee(signer: string, swapData: EVMSwapData, feeRate?: string): Promise<bigint> {
583
- return this.Claim.getClaimFee(swapData, feeRate);
584
- }
585
-
586
- /**
587
- * Get the estimated fee of the commit transaction
588
- */
589
- getCommitFee(signer: string, swapData: EVMSwapData, feeRate?: string): Promise<bigint> {
590
- return this.Init.getInitFee(swapData, feeRate);
591
- }
592
-
593
- /**
594
- * Get the estimated transaction fee of the refund transaction
595
- */
596
- getRefundFee(signer: string, swapData: EVMSwapData, feeRate?: string): Promise<bigint> {
597
- return this.Refund.getRefundFee(swapData, feeRate);
598
- }
599
-
600
- }
1
+ import {
2
+ BigIntBufferUtils,
3
+ ChainSwapType,
4
+ IntermediaryReputationType,
5
+ RelaySynchronizer,
6
+ SignatureData, SwapCommitState, SwapCommitStateType,
7
+ SwapContract,
8
+ TransactionConfirmationOptions
9
+ } from "@atomiqlabs/base";
10
+ import {Buffer} from "buffer";
11
+ import {TimelockRefundHandler} from "./handlers/refund/TimelockRefundHandler";
12
+ import {claimHandlersList, IClaimHandler} from "./handlers/claim/ClaimHandlers"
13
+ import {IHandler} from "./handlers/IHandler";
14
+ import {sha256} from "@noble/hashes/sha2";
15
+ import { EVMContractBase } from "../contract/EVMContractBase";
16
+ import {EscrowManager} from "./EscrowManagerTypechain";
17
+ import { EVMSwapData } from "./EVMSwapData";
18
+ import {EVMTx} from "../chain/modules/EVMTransactions";
19
+ import { EVMSigner } from "../wallet/EVMSigner";
20
+ import {EVMChainInterface} from "../chain/EVMChainInterface";
21
+ import { EVMBtcRelay } from "../btcrelay/EVMBtcRelay";
22
+ import {EscrowManagerAbi} from "./EscrowManagerAbi";
23
+ import {hexlify} from "ethers";
24
+ import {EVMBtcStoredHeader} from "../btcrelay/headers/EVMBtcStoredHeader";
25
+ import {EVMLpVault} from "./modules/EVMLpVault";
26
+ import {EVMPreFetchVerification, EVMSwapInit} from "./modules/EVMSwapInit";
27
+ import { EVMSwapRefund } from "./modules/EVMSwapRefund";
28
+ import {EVMSwapClaim} from "./modules/EVMSwapClaim";
29
+
30
+ const ESCROW_STATE_COMMITTED = 1;
31
+ const ESCROW_STATE_CLAIMED = 2;
32
+ const ESCROW_STATE_REFUNDED = 3;
33
+
34
+ export class EVMSwapContract<ChainId extends string = string>
35
+ extends EVMContractBase<EscrowManager>
36
+ implements SwapContract<
37
+ EVMSwapData,
38
+ EVMTx,
39
+ never,
40
+ EVMPreFetchVerification,
41
+ EVMSigner,
42
+ ChainId
43
+ > {
44
+
45
+ readonly supportsInitWithoutClaimer = true;
46
+
47
+ ////////////////////////
48
+ //// Constants
49
+ readonly chainId: ChainId;
50
+
51
+ ////////////////////////
52
+ //// Timeouts
53
+ readonly claimWithSecretTimeout: number = 180;
54
+ readonly claimWithTxDataTimeout: number = 180;
55
+ readonly refundTimeout: number = 180;
56
+ readonly claimGracePeriod: number = 10*60;
57
+ readonly refundGracePeriod: number = 10*60;
58
+ readonly authGracePeriod: number = 30;
59
+
60
+ ////////////////////////
61
+ //// Services
62
+ readonly Init: EVMSwapInit;
63
+ readonly Refund: EVMSwapRefund;
64
+ readonly Claim: EVMSwapClaim;
65
+ readonly LpVault: EVMLpVault;
66
+
67
+ ////////////////////////
68
+ //// Handlers
69
+ readonly claimHandlersByAddress: {[address: string]: IClaimHandler<any, any>} = {};
70
+ readonly claimHandlersBySwapType: {[type in ChainSwapType]?: IClaimHandler<any, any>} = {};
71
+
72
+ readonly refundHandlersByAddress: {[address: string]: IHandler<any, any>} = {};
73
+ readonly timelockRefundHandler: IHandler<any, any>;
74
+
75
+ readonly btcRelay: EVMBtcRelay<any>;
76
+
77
+ constructor(
78
+ chainInterface: EVMChainInterface<ChainId>,
79
+ btcRelay: EVMBtcRelay<any>,
80
+ contractAddress: string,
81
+ handlerAddresses: {
82
+ refund: {
83
+ timelock: string
84
+ },
85
+ claim: {
86
+ [type in ChainSwapType]: string
87
+ }
88
+ }
89
+ ) {
90
+ super(chainInterface, contractAddress, EscrowManagerAbi);
91
+ this.chainId = chainInterface.chainId;
92
+ this.Init = new EVMSwapInit(chainInterface, this);
93
+ this.Refund = new EVMSwapRefund(chainInterface, this);
94
+ this.Claim = new EVMSwapClaim(chainInterface, this);
95
+ this.LpVault = new EVMLpVault(chainInterface, this);
96
+
97
+ this.btcRelay = btcRelay;
98
+
99
+ claimHandlersList.forEach(handlerCtor => {
100
+ const handler = new handlerCtor(handlerAddresses.claim[handlerCtor.type]);
101
+ this.claimHandlersByAddress[handler.address.toLowerCase()] = handler;
102
+ this.claimHandlersBySwapType[handlerCtor.type] = handler;
103
+ });
104
+
105
+ this.timelockRefundHandler = new TimelockRefundHandler(handlerAddresses.refund.timelock);
106
+ this.refundHandlersByAddress[this.timelockRefundHandler.address.toLowerCase()] = this.timelockRefundHandler;
107
+ }
108
+
109
+ async start(): Promise<void> {
110
+ }
111
+
112
+ ////////////////////////////////////////////
113
+ //// Signatures
114
+ preFetchForInitSignatureVerification(): Promise<EVMPreFetchVerification> {
115
+ return this.Init.preFetchForInitSignatureVerification();
116
+ }
117
+
118
+ getInitSignature(signer: EVMSigner, swapData: EVMSwapData, authorizationTimeout: number, preFetchedBlockData?: never, feeRate?: string): Promise<SignatureData> {
119
+ return this.Init.signSwapInitialization(signer, swapData, authorizationTimeout);
120
+ }
121
+
122
+ isValidInitAuthorization(sender: string, swapData: EVMSwapData, {timeout, prefix, signature}, feeRate?: string, preFetchedData?: EVMPreFetchVerification): Promise<Buffer> {
123
+ return this.Init.isSignatureValid(sender, swapData, timeout, prefix, signature, preFetchedData);
124
+ }
125
+
126
+ getInitAuthorizationExpiry(swapData: EVMSwapData, {timeout, prefix, signature}, preFetchedData?: EVMPreFetchVerification): Promise<number> {
127
+ return this.Init.getSignatureExpiry(timeout);
128
+ }
129
+
130
+ isInitAuthorizationExpired(swapData: EVMSwapData, {timeout, prefix, signature}): Promise<boolean> {
131
+ return this.Init.isSignatureExpired(timeout);
132
+ }
133
+
134
+ getRefundSignature(signer: EVMSigner, swapData: EVMSwapData, authorizationTimeout: number): Promise<SignatureData> {
135
+ return this.Refund.signSwapRefund(signer, swapData, authorizationTimeout);
136
+ }
137
+
138
+ isValidRefundAuthorization(swapData: EVMSwapData, {timeout, prefix, signature}): Promise<Buffer> {
139
+ return this.Refund.isSignatureValid(swapData, timeout, prefix, signature);
140
+ }
141
+
142
+ getDataSignature(signer: EVMSigner, data: Buffer): Promise<string> {
143
+ return this.Chain.Signatures.getDataSignature(signer, data);
144
+ }
145
+
146
+ isValidDataSignature(data: Buffer, signature: string, publicKey: string): Promise<boolean> {
147
+ return this.Chain.Signatures.isValidDataSignature(data, signature, publicKey);
148
+ }
149
+
150
+ ////////////////////////////////////////////
151
+ //// Swap data utils
152
+ /**
153
+ * Checks whether the claim is claimable by us, that means not expired, we are claimer & the swap is commited
154
+ *
155
+ * @param signer
156
+ * @param data
157
+ */
158
+ async isClaimable(signer: string, data: EVMSwapData): Promise<boolean> {
159
+ if(!data.isClaimer(signer)) return false;
160
+ if(await this.isExpired(signer, data)) return false;
161
+ return await this.isCommited(data);
162
+ }
163
+
164
+ /**
165
+ * Checks whether a swap is commited, i.e. the swap still exists on-chain and was not claimed nor refunded
166
+ *
167
+ * @param swapData
168
+ */
169
+ async isCommited(swapData: EVMSwapData): Promise<boolean> {
170
+ const data = await this.contract.getHashState("0x"+swapData.getEscrowHash());
171
+ return Number(data.state)===ESCROW_STATE_COMMITTED;
172
+ }
173
+
174
+ /**
175
+ * Checks whether the swap is expired, takes into consideration possible on-chain time skew, therefore for claimer
176
+ * the swap expires a bit sooner than it should've & for the offerer it expires a bit later
177
+ *
178
+ * @param signer
179
+ * @param data
180
+ */
181
+ isExpired(signer: string, data: EVMSwapData): Promise<boolean> {
182
+ let currentTimestamp: bigint = BigInt(Math.floor(Date.now()/1000));
183
+ if(data.isClaimer(signer)) currentTimestamp = currentTimestamp + BigInt(this.claimGracePeriod);
184
+ if(data.isOfferer(signer)) currentTimestamp = currentTimestamp - BigInt(this.refundGracePeriod);
185
+ return Promise.resolve(data.getExpiry() < currentTimestamp);
186
+ }
187
+
188
+ /**
189
+ * Checks if the swap is refundable by us, checks if we are offerer, if the swap is already expired & if the swap
190
+ * is still commited
191
+ *
192
+ * @param signer
193
+ * @param data
194
+ */
195
+ async isRequestRefundable(signer: string, data: EVMSwapData): Promise<boolean> {
196
+ //Swap can only be refunded by the offerer
197
+ if(!data.isOfferer(signer)) return false;
198
+ if(!(await this.isExpired(signer, data))) return false;
199
+ return await this.isCommited(data);
200
+ }
201
+
202
+ getHashForTxId(txId: string, confirmations: number) {
203
+ return Buffer.from(this.claimHandlersBySwapType[ChainSwapType.CHAIN_TXID].getCommitment({
204
+ txId,
205
+ confirmations,
206
+ btcRelay: this.btcRelay
207
+ }).slice(2), "hex");
208
+ }
209
+
210
+ /**
211
+ * Get the swap payment hash to be used for an on-chain swap, uses poseidon hash of the value
212
+ *
213
+ * @param outputScript output script required to claim the swap
214
+ * @param amount sats sent required to claim the swap
215
+ * @param confirmations
216
+ * @param nonce swap nonce uniquely identifying the transaction to prevent replay attacks
217
+ */
218
+ getHashForOnchain(outputScript: Buffer, amount: bigint, confirmations: number, nonce?: bigint): Buffer {
219
+ let result: string;
220
+ if(nonce==null || nonce === 0n) {
221
+ result = this.claimHandlersBySwapType[ChainSwapType.CHAIN].getCommitment({
222
+ output: outputScript,
223
+ amount,
224
+ confirmations,
225
+ btcRelay: this.btcRelay
226
+ });
227
+ } else {
228
+ result = this.claimHandlersBySwapType[ChainSwapType.CHAIN_NONCED].getCommitment({
229
+ output: outputScript,
230
+ amount,
231
+ nonce,
232
+ confirmations,
233
+ btcRelay: this.btcRelay
234
+ });
235
+ }
236
+ return Buffer.from(result.slice(2), "hex");
237
+ }
238
+
239
+ /**
240
+ * Get the swap payment hash to be used for a lightning htlc swap, uses poseidon hash of the sha256 hash of the preimage
241
+ *
242
+ * @param paymentHash payment hash of the HTLC
243
+ */
244
+ getHashForHtlc(paymentHash: Buffer): Buffer {
245
+ return Buffer.from(this.claimHandlersBySwapType[ChainSwapType.HTLC].getCommitment(paymentHash).slice(2), "hex");
246
+ }
247
+
248
+ getExtraData(outputScript: Buffer, amount: bigint, confirmations: number, nonce?: bigint): Buffer {
249
+ if(nonce==null) nonce = 0n;
250
+ const txoHash = Buffer.from(sha256(Buffer.concat([
251
+ BigIntBufferUtils.toBuffer(amount, "le", 8),
252
+ outputScript
253
+ ])));
254
+ return Buffer.concat([
255
+ txoHash,
256
+ BigIntBufferUtils.toBuffer(nonce, "be", 8),
257
+ BigIntBufferUtils.toBuffer(BigInt(confirmations), "be", 2)
258
+ ]);
259
+ }
260
+
261
+
262
+ ////////////////////////////////////////////
263
+ //// Swap data getters
264
+ /**
265
+ * Gets the status of the specific swap, this also checks if we are offerer/claimer & checks for expiry (to see
266
+ * if swap is refundable)
267
+ *
268
+ * @param signer
269
+ * @param data
270
+ */
271
+ async getCommitStatus(signer: string, data: EVMSwapData): Promise<SwapCommitState> {
272
+ const escrowHash = data.getEscrowHash();
273
+ const stateData = await this.contract.getHashState("0x"+escrowHash);
274
+ const state = Number(stateData.state);
275
+ const blockHeight = Number(stateData.finishBlockheight);
276
+ switch(state) {
277
+ case ESCROW_STATE_COMMITTED:
278
+ if(data.isOfferer(signer) && await this.isExpired(signer,data)) return {type: SwapCommitStateType.REFUNDABLE};
279
+ return {type: SwapCommitStateType.COMMITED};
280
+ case ESCROW_STATE_CLAIMED:
281
+ return {
282
+ type: SwapCommitStateType.PAID,
283
+ getTxBlock: async () => {
284
+ return {
285
+ blockTime: await this.Chain.Blocks.getBlockTime(blockHeight),
286
+ blockHeight: blockHeight
287
+ };
288
+ },
289
+ getClaimResult: async () => {
290
+ const events = await this.Events.getContractBlockEvents(
291
+ ["Claim"],
292
+ [null, null, "0x"+escrowHash],
293
+ blockHeight, blockHeight
294
+ );
295
+ return events.length===0 ? null : events[0].args.witnessResult;
296
+ },
297
+ getClaimTxId: async () => {
298
+ const events = await this.Events.getContractBlockEvents(
299
+ ["Claim"],
300
+ [null, null, "0x"+escrowHash],
301
+ blockHeight, blockHeight
302
+ );
303
+ return events.length===0 ? null : events[0].transactionHash;
304
+ }
305
+ };
306
+ default:
307
+ return {
308
+ type: await this.isExpired(signer, data) ? SwapCommitStateType.EXPIRED : SwapCommitStateType.NOT_COMMITED,
309
+ getTxBlock: async () => {
310
+ return {
311
+ blockTime: await this.Chain.Blocks.getBlockTime(blockHeight),
312
+ blockHeight: blockHeight
313
+ };
314
+ },
315
+ getRefundTxId: async () => {
316
+ const events = await this.Events.getContractBlockEvents(
317
+ ["Refund"],
318
+ [null, null, "0x"+escrowHash],
319
+ blockHeight, blockHeight
320
+ );
321
+ return events.length===0 ? null : events[0].transactionHash;
322
+ }
323
+ };
324
+ }
325
+ }
326
+
327
+ /**
328
+ * Returns the data committed for a specific payment hash, or null if no data is currently commited for
329
+ * the specific swap
330
+ *
331
+ * @param paymentHashHex
332
+ */
333
+ async getCommitedData(paymentHashHex: string): Promise<EVMSwapData> {
334
+ //TODO: Noop
335
+ return null;
336
+ }
337
+
338
+ ////////////////////////////////////////////
339
+ //// Swap data initializer
340
+ createSwapData(
341
+ type: ChainSwapType,
342
+ offerer: string,
343
+ claimer: string,
344
+ token: string,
345
+ amount: bigint,
346
+ paymentHash: string,
347
+ sequence: bigint,
348
+ expiry: bigint,
349
+ payIn: boolean,
350
+ payOut: boolean,
351
+ securityDeposit: bigint,
352
+ claimerBounty: bigint,
353
+ depositToken: string = this.Chain.Tokens.getNativeCurrencyAddress()
354
+ ): Promise<EVMSwapData> {
355
+ return Promise.resolve(new EVMSwapData(
356
+ offerer,
357
+ claimer,
358
+ token,
359
+ this.timelockRefundHandler.address,
360
+ this.claimHandlersBySwapType?.[type]?.address,
361
+ payOut,
362
+ payIn,
363
+ payIn, //For now track reputation for all payIn swaps
364
+ sequence,
365
+ "0x"+paymentHash,
366
+ hexlify(BigIntBufferUtils.toBuffer(expiry, "be", 32)),
367
+ amount,
368
+ depositToken,
369
+ securityDeposit,
370
+ claimerBounty,
371
+ type,
372
+ null
373
+ ));
374
+ }
375
+
376
+ ////////////////////////////////////////////
377
+ //// Utils
378
+ async getBalance(signer: string, tokenAddress: string, inContract?: boolean): Promise<bigint> {
379
+ if(inContract) return await this.getIntermediaryBalance(signer, tokenAddress);
380
+
381
+ return await this.Chain.getBalance(signer, tokenAddress);
382
+ }
383
+
384
+ getIntermediaryData(address: string, token: string): Promise<{
385
+ balance: bigint,
386
+ reputation: IntermediaryReputationType
387
+ }> {
388
+ return this.LpVault.getIntermediaryData(address, token);
389
+ }
390
+
391
+ getIntermediaryReputation(address: string, token: string): Promise<IntermediaryReputationType> {
392
+ return this.LpVault.getIntermediaryReputation(address, token);
393
+ }
394
+
395
+ getIntermediaryBalance(address: string, token: string): Promise<bigint> {
396
+ return this.LpVault.getIntermediaryBalance(address, token);
397
+ }
398
+
399
+ ////////////////////////////////////////////
400
+ //// Transaction initializers
401
+ async txsClaimWithSecret(
402
+ signer: string | EVMSigner,
403
+ swapData: EVMSwapData,
404
+ secret: string,
405
+ checkExpiry?: boolean,
406
+ initAta?: boolean,
407
+ feeRate?: string,
408
+ skipAtaCheck?: boolean
409
+ ): Promise<EVMTx[]> {
410
+ return this.Claim.txsClaimWithSecret(typeof(signer)==="string" ? signer : signer.getAddress(), swapData, secret, checkExpiry, feeRate)
411
+ }
412
+
413
+ async txsClaimWithTxData(
414
+ signer: string | EVMSigner,
415
+ swapData: EVMSwapData,
416
+ tx: { blockhash: string, confirmations: number, txid: string, hex: string, height: number },
417
+ requiredConfirmations: number,
418
+ vout: number,
419
+ commitedHeader?: EVMBtcStoredHeader,
420
+ synchronizer?: RelaySynchronizer<EVMBtcStoredHeader, EVMTx, any>,
421
+ initAta?: boolean,
422
+ feeRate?: string
423
+ ): Promise<EVMTx[] | null> {
424
+ return this.Claim.txsClaimWithTxData(
425
+ typeof(signer)==="string" ? signer : signer.getAddress(),
426
+ swapData,
427
+ tx,
428
+ requiredConfirmations,
429
+ vout,
430
+ commitedHeader,
431
+ synchronizer,
432
+ feeRate
433
+ );
434
+ }
435
+
436
+ txsRefund(signer: string, swapData: EVMSwapData, check?: boolean, initAta?: boolean, feeRate?: string): Promise<EVMTx[]> {
437
+ return this.Refund.txsRefund(signer, swapData, check, feeRate);
438
+ }
439
+
440
+ txsRefundWithAuthorization(signer: string, swapData: EVMSwapData, {timeout, prefix, signature}, check?: boolean, initAta?: boolean, feeRate?: string): Promise<EVMTx[]> {
441
+ return this.Refund.txsRefundWithAuthorization(signer, swapData, timeout, prefix,signature, check, feeRate);
442
+ }
443
+
444
+ txsInit(signer: string, swapData: EVMSwapData, {timeout, prefix, signature}, skipChecks?: boolean, feeRate?: string): Promise<EVMTx[]> {
445
+ return this.Init.txsInit(signer, swapData, timeout, prefix, signature, skipChecks, feeRate);
446
+ }
447
+
448
+ txsWithdraw(signer: string, token: string, amount: bigint, feeRate?: string): Promise<EVMTx[]> {
449
+ return this.LpVault.txsWithdraw(signer, token, amount, feeRate);
450
+ }
451
+
452
+ txsDeposit(signer: string, token: string, amount: bigint, feeRate?: string): Promise<EVMTx[]> {
453
+ return this.LpVault.txsDeposit(signer, token, amount, feeRate);
454
+ }
455
+
456
+ ////////////////////////////////////////////
457
+ //// Executors
458
+ async claimWithSecret(
459
+ signer: EVMSigner,
460
+ swapData: EVMSwapData,
461
+ secret: string,
462
+ checkExpiry?: boolean,
463
+ initAta?: boolean,
464
+ txOptions?: TransactionConfirmationOptions
465
+ ): Promise<string> {
466
+ const result = await this.Claim.txsClaimWithSecret(signer.getAddress(), swapData, secret, checkExpiry, txOptions?.feeRate);
467
+ const [signature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
468
+ return signature;
469
+ }
470
+
471
+ async claimWithTxData(
472
+ signer: EVMSigner,
473
+ swapData: EVMSwapData,
474
+ tx: { blockhash: string, confirmations: number, txid: string, hex: string, height: number },
475
+ requiredConfirmations: number,
476
+ vout: number,
477
+ commitedHeader?: EVMBtcStoredHeader,
478
+ synchronizer?: RelaySynchronizer<EVMBtcStoredHeader, EVMTx, any>,
479
+ initAta?: boolean,
480
+ txOptions?: TransactionConfirmationOptions
481
+ ): Promise<string> {
482
+ const txs = await this.Claim.txsClaimWithTxData(
483
+ signer.getAddress(), swapData, tx, requiredConfirmations, vout,
484
+ commitedHeader, synchronizer, txOptions?.feeRate
485
+ );
486
+ if(txs===null) throw new Error("Btc relay not synchronized to required blockheight!");
487
+
488
+ const txHashes = await this.Chain.sendAndConfirm(signer, txs, txOptions?.waitForConfirmation, txOptions?.abortSignal);
489
+
490
+ return txHashes[txHashes.length - 1];
491
+ }
492
+
493
+ async refund(
494
+ signer: EVMSigner,
495
+ swapData: EVMSwapData,
496
+ check?: boolean,
497
+ initAta?: boolean,
498
+ txOptions?: TransactionConfirmationOptions
499
+ ): Promise<string> {
500
+ let result = await this.txsRefund(signer.getAddress(), swapData, check, initAta, txOptions?.feeRate);
501
+
502
+ const [signature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
503
+
504
+ return signature;
505
+ }
506
+
507
+ async refundWithAuthorization(
508
+ signer: EVMSigner,
509
+ swapData: EVMSwapData,
510
+ signature: SignatureData,
511
+ check?: boolean,
512
+ initAta?: boolean,
513
+ txOptions?: TransactionConfirmationOptions
514
+ ): Promise<string> {
515
+ let result = await this.txsRefundWithAuthorization(signer.getAddress(), swapData, signature, check, initAta, txOptions?.feeRate);
516
+
517
+ const [txSignature] = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
518
+
519
+ return txSignature;
520
+ }
521
+
522
+ async init(
523
+ signer: EVMSigner,
524
+ swapData: EVMSwapData,
525
+ signature: SignatureData,
526
+ skipChecks?: boolean,
527
+ txOptions?: TransactionConfirmationOptions
528
+ ): Promise<string> {
529
+ if(swapData.isPayIn()) {
530
+ if(!swapData.isOfferer(signer.getAddress()) && !swapData.isOfferer(signer.getAddress())) throw new Error("Invalid signer provided!");
531
+ } else {
532
+ if(!swapData.isClaimer(signer.getAddress()) && !swapData.isOfferer(signer.getAddress())) throw new Error("Invalid signer provided!");
533
+ }
534
+
535
+ let result = await this.txsInit(signer.getAddress(), swapData, signature, skipChecks, txOptions?.feeRate);
536
+
537
+ const txHashes = await this.Chain.sendAndConfirm(signer, result, txOptions?.waitForConfirmation, txOptions?.abortSignal);
538
+
539
+ return txHashes[txHashes.length - 1];
540
+ }
541
+
542
+ async withdraw(
543
+ signer: EVMSigner,
544
+ token: string,
545
+ amount: bigint,
546
+ txOptions?: TransactionConfirmationOptions
547
+ ): Promise<string> {
548
+ const txs = await this.LpVault.txsWithdraw(signer.getAddress(), token, amount, txOptions?.feeRate);
549
+ const [txId] = await this.Chain.sendAndConfirm(signer, txs, txOptions?.waitForConfirmation, txOptions?.abortSignal, false);
550
+ return txId;
551
+ }
552
+
553
+ async deposit(
554
+ signer: EVMSigner,
555
+ token: string,
556
+ amount: bigint,
557
+ txOptions?: TransactionConfirmationOptions
558
+ ): Promise<string> {
559
+ const txs = await this.LpVault.txsDeposit(signer.getAddress(), token, amount, txOptions?.feeRate);
560
+ const [txId] = await this.Chain.sendAndConfirm(signer, txs, txOptions?.waitForConfirmation, txOptions?.abortSignal, false);
561
+ return txId;
562
+ }
563
+
564
+ ////////////////////////////////////////////
565
+ //// Fees
566
+ getInitPayInFeeRate(offerer?: string, claimer?: string, token?: string, paymentHash?: string): Promise<string> {
567
+ return this.Chain.Fees.getFeeRate();
568
+ }
569
+
570
+ getInitFeeRate(offerer?: string, claimer?: string, token?: string, paymentHash?: string): Promise<string> {
571
+ return this.Chain.Fees.getFeeRate();
572
+ }
573
+
574
+ getRefundFeeRate(swapData: EVMSwapData): Promise<string> {
575
+ return this.Chain.Fees.getFeeRate();
576
+ }
577
+
578
+ getClaimFeeRate(signer: string, swapData: EVMSwapData): Promise<string> {
579
+ return this.Chain.Fees.getFeeRate();
580
+ }
581
+
582
+ getClaimFee(signer: string, swapData: EVMSwapData, feeRate?: string): Promise<bigint> {
583
+ return this.Claim.getClaimFee(swapData, feeRate);
584
+ }
585
+
586
+ /**
587
+ * Get the estimated fee of the commit transaction
588
+ */
589
+ getCommitFee(signer: string, swapData: EVMSwapData, feeRate?: string): Promise<bigint> {
590
+ return this.Init.getInitFee(swapData, feeRate);
591
+ }
592
+
593
+ /**
594
+ * Get the estimated transaction fee of the refund transaction
595
+ */
596
+ getRefundFee(signer: string, swapData: EVMSwapData, feeRate?: string): Promise<bigint> {
597
+ return this.Refund.getRefundFee(swapData, feeRate);
598
+ }
599
+
600
+ }