@atomiqlabs/chain-starknet 4.0.0-dev.22 → 4.0.0-dev.23

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 (154) hide show
  1. package/LICENSE +201 -201
  2. package/dist/index.d.ts +39 -38
  3. package/dist/index.js +55 -54
  4. package/dist/starknet/StarknetChainType.d.ts +13 -13
  5. package/dist/starknet/StarknetChainType.js +2 -2
  6. package/dist/starknet/StarknetInitializer.d.ts +28 -28
  7. package/dist/starknet/StarknetInitializer.js +69 -69
  8. package/dist/starknet/btcrelay/BtcRelayAbi.d.ts +250 -250
  9. package/dist/starknet/btcrelay/BtcRelayAbi.js +341 -341
  10. package/dist/starknet/btcrelay/StarknetBtcRelay.d.ts +186 -186
  11. package/dist/starknet/btcrelay/StarknetBtcRelay.js +379 -379
  12. package/dist/starknet/btcrelay/headers/StarknetBtcHeader.d.ts +31 -31
  13. package/dist/starknet/btcrelay/headers/StarknetBtcHeader.js +74 -74
  14. package/dist/starknet/btcrelay/headers/StarknetBtcStoredHeader.d.ts +51 -51
  15. package/dist/starknet/btcrelay/headers/StarknetBtcStoredHeader.js +113 -113
  16. package/dist/starknet/chain/StarknetAction.d.ts +19 -19
  17. package/dist/starknet/chain/StarknetAction.js +73 -73
  18. package/dist/starknet/chain/StarknetChainInterface.d.ts +54 -59
  19. package/dist/starknet/chain/StarknetChainInterface.js +97 -97
  20. package/dist/starknet/chain/StarknetModule.d.ts +9 -14
  21. package/dist/starknet/chain/StarknetModule.js +13 -13
  22. package/dist/starknet/chain/modules/ERC20Abi.d.ts +755 -755
  23. package/dist/starknet/chain/modules/ERC20Abi.js +1032 -1032
  24. package/dist/starknet/chain/modules/StarknetAccounts.d.ts +6 -6
  25. package/dist/starknet/chain/modules/StarknetAccounts.js +24 -24
  26. package/dist/starknet/chain/modules/StarknetAddresses.d.ts +9 -9
  27. package/dist/starknet/chain/modules/StarknetAddresses.js +26 -26
  28. package/dist/starknet/chain/modules/StarknetBlocks.d.ts +20 -20
  29. package/dist/starknet/chain/modules/StarknetBlocks.js +64 -64
  30. package/dist/starknet/chain/modules/StarknetEvents.d.ts +44 -44
  31. package/dist/starknet/chain/modules/StarknetEvents.js +88 -88
  32. package/dist/starknet/chain/modules/StarknetFees.d.ts +82 -77
  33. package/dist/starknet/chain/modules/StarknetFees.js +121 -114
  34. package/dist/starknet/chain/modules/StarknetSignatures.d.ts +29 -29
  35. package/dist/starknet/chain/modules/StarknetSignatures.js +72 -72
  36. package/dist/starknet/chain/modules/StarknetTokens.d.ts +69 -69
  37. package/dist/starknet/chain/modules/StarknetTokens.js +102 -102
  38. package/dist/starknet/chain/modules/StarknetTransactions.d.ts +110 -93
  39. package/dist/starknet/chain/modules/StarknetTransactions.js +351 -261
  40. package/dist/starknet/contract/StarknetContractBase.d.ts +13 -13
  41. package/dist/starknet/contract/StarknetContractBase.js +20 -20
  42. package/dist/starknet/contract/StarknetContractModule.d.ts +8 -8
  43. package/dist/starknet/contract/StarknetContractModule.js +11 -11
  44. package/dist/starknet/contract/modules/StarknetContractEvents.d.ts +51 -51
  45. package/dist/starknet/contract/modules/StarknetContractEvents.js +97 -97
  46. package/dist/starknet/events/StarknetChainEvents.d.ts +21 -21
  47. package/dist/starknet/events/StarknetChainEvents.js +52 -52
  48. package/dist/starknet/events/StarknetChainEventsBrowser.d.ts +84 -89
  49. package/dist/starknet/events/StarknetChainEventsBrowser.js +307 -307
  50. package/dist/starknet/provider/RpcProviderWithRetries.d.ts +41 -41
  51. package/dist/starknet/provider/RpcProviderWithRetries.js +70 -70
  52. package/dist/starknet/spv_swap/SpvVaultContractAbi.d.ts +488 -488
  53. package/dist/starknet/spv_swap/SpvVaultContractAbi.js +656 -656
  54. package/dist/starknet/spv_swap/StarknetSpvVaultContract.d.ts +89 -94
  55. package/dist/starknet/spv_swap/StarknetSpvVaultContract.js +477 -477
  56. package/dist/starknet/spv_swap/StarknetSpvVaultData.d.ts +49 -49
  57. package/dist/starknet/spv_swap/StarknetSpvVaultData.js +145 -145
  58. package/dist/starknet/spv_swap/StarknetSpvWithdrawalData.d.ts +25 -25
  59. package/dist/starknet/spv_swap/StarknetSpvWithdrawalData.js +72 -72
  60. package/dist/starknet/swaps/EscrowManagerAbi.d.ts +431 -431
  61. package/dist/starknet/swaps/EscrowManagerAbi.js +583 -583
  62. package/dist/starknet/swaps/StarknetSwapContract.d.ts +197 -197
  63. package/dist/starknet/swaps/StarknetSwapContract.js +440 -440
  64. package/dist/starknet/swaps/StarknetSwapData.d.ts +74 -74
  65. package/dist/starknet/swaps/StarknetSwapData.js +325 -325
  66. package/dist/starknet/swaps/StarknetSwapModule.d.ts +10 -10
  67. package/dist/starknet/swaps/StarknetSwapModule.js +11 -11
  68. package/dist/starknet/swaps/handlers/IHandler.d.ts +13 -13
  69. package/dist/starknet/swaps/handlers/IHandler.js +2 -2
  70. package/dist/starknet/swaps/handlers/claim/ClaimHandlers.d.ts +13 -13
  71. package/dist/starknet/swaps/handlers/claim/ClaimHandlers.js +13 -13
  72. package/dist/starknet/swaps/handlers/claim/HashlockClaimHandler.d.ts +21 -21
  73. package/dist/starknet/swaps/handlers/claim/HashlockClaimHandler.js +44 -44
  74. package/dist/starknet/swaps/handlers/claim/btc/BitcoinNoncedOutputClaimHandler.d.ts +24 -24
  75. package/dist/starknet/swaps/handlers/claim/btc/BitcoinNoncedOutputClaimHandler.js +48 -48
  76. package/dist/starknet/swaps/handlers/claim/btc/BitcoinOutputClaimHandler.d.ts +25 -25
  77. package/dist/starknet/swaps/handlers/claim/btc/BitcoinOutputClaimHandler.js +40 -40
  78. package/dist/starknet/swaps/handlers/claim/btc/BitcoinTxIdClaimHandler.d.ts +20 -20
  79. package/dist/starknet/swaps/handlers/claim/btc/BitcoinTxIdClaimHandler.js +30 -30
  80. package/dist/starknet/swaps/handlers/claim/btc/IBitcoinClaimHandler.d.ts +45 -45
  81. package/dist/starknet/swaps/handlers/claim/btc/IBitcoinClaimHandler.js +52 -52
  82. package/dist/starknet/swaps/handlers/refund/TimelockRefundHandler.d.ts +17 -17
  83. package/dist/starknet/swaps/handlers/refund/TimelockRefundHandler.js +27 -27
  84. package/dist/starknet/swaps/modules/StarknetLpVault.d.ts +69 -69
  85. package/dist/starknet/swaps/modules/StarknetLpVault.js +122 -122
  86. package/dist/starknet/swaps/modules/StarknetSwapClaim.d.ts +53 -53
  87. package/dist/starknet/swaps/modules/StarknetSwapClaim.js +100 -100
  88. package/dist/starknet/swaps/modules/StarknetSwapInit.d.ts +94 -94
  89. package/dist/starknet/swaps/modules/StarknetSwapInit.js +235 -235
  90. package/dist/starknet/swaps/modules/StarknetSwapRefund.d.ts +62 -62
  91. package/dist/starknet/swaps/modules/StarknetSwapRefund.js +128 -128
  92. package/dist/starknet/wallet/StarknetBrowserSigner.d.ts +5 -0
  93. package/dist/starknet/wallet/StarknetBrowserSigner.js +11 -0
  94. package/dist/starknet/wallet/StarknetKeypairWallet.d.ts +7 -7
  95. package/dist/starknet/wallet/StarknetKeypairWallet.js +35 -35
  96. package/dist/starknet/wallet/StarknetPersistentSigner.d.ts +33 -0
  97. package/dist/starknet/wallet/StarknetPersistentSigner.js +243 -0
  98. package/dist/starknet/wallet/StarknetSigner.d.ts +18 -12
  99. package/dist/starknet/wallet/StarknetSigner.js +69 -47
  100. package/dist/starknet/wallet/accounts/StarknetKeypairWallet.d.ts +7 -0
  101. package/dist/starknet/wallet/accounts/StarknetKeypairWallet.js +35 -0
  102. package/dist/utils/Utils.d.ts +39 -37
  103. package/dist/utils/Utils.js +264 -260
  104. package/package.json +45 -43
  105. package/src/index.ts +48 -47
  106. package/src/starknet/StarknetChainType.ts +28 -28
  107. package/src/starknet/StarknetInitializer.ts +110 -110
  108. package/src/starknet/btcrelay/BtcRelayAbi.ts +338 -338
  109. package/src/starknet/btcrelay/StarknetBtcRelay.ts +494 -494
  110. package/src/starknet/btcrelay/headers/StarknetBtcHeader.ts +100 -100
  111. package/src/starknet/btcrelay/headers/StarknetBtcStoredHeader.ts +141 -141
  112. package/src/starknet/chain/StarknetAction.ts +85 -85
  113. package/src/starknet/chain/StarknetChainInterface.ts +165 -165
  114. package/src/starknet/chain/StarknetModule.ts +19 -19
  115. package/src/starknet/chain/modules/ERC20Abi.ts +1029 -1029
  116. package/src/starknet/chain/modules/StarknetAccounts.ts +25 -25
  117. package/src/starknet/chain/modules/StarknetAddresses.ts +22 -22
  118. package/src/starknet/chain/modules/StarknetBlocks.ts +75 -75
  119. package/src/starknet/chain/modules/StarknetEvents.ts +104 -104
  120. package/src/starknet/chain/modules/StarknetFees.ts +162 -154
  121. package/src/starknet/chain/modules/StarknetSignatures.ts +91 -91
  122. package/src/starknet/chain/modules/StarknetTokens.ts +120 -120
  123. package/src/starknet/chain/modules/StarknetTransactions.ts +392 -285
  124. package/src/starknet/contract/StarknetContractBase.ts +30 -30
  125. package/src/starknet/contract/StarknetContractModule.ts +16 -16
  126. package/src/starknet/contract/modules/StarknetContractEvents.ts +134 -134
  127. package/src/starknet/events/StarknetChainEvents.ts +67 -67
  128. package/src/starknet/events/StarknetChainEventsBrowser.ts +420 -420
  129. package/src/starknet/provider/RpcProviderWithRetries.ts +83 -83
  130. package/src/starknet/spv_swap/SpvVaultContractAbi.ts +656 -656
  131. package/src/starknet/spv_swap/StarknetSpvVaultContract.ts +591 -591
  132. package/src/starknet/spv_swap/StarknetSpvVaultData.ts +195 -195
  133. package/src/starknet/spv_swap/StarknetSpvWithdrawalData.ts +79 -79
  134. package/src/starknet/swaps/EscrowManagerAbi.ts +582 -582
  135. package/src/starknet/swaps/StarknetSwapContract.ts +668 -668
  136. package/src/starknet/swaps/StarknetSwapData.ts +455 -455
  137. package/src/starknet/swaps/StarknetSwapModule.ts +17 -17
  138. package/src/starknet/swaps/handlers/IHandler.ts +20 -20
  139. package/src/starknet/swaps/handlers/claim/ClaimHandlers.ts +23 -23
  140. package/src/starknet/swaps/handlers/claim/HashlockClaimHandler.ts +53 -53
  141. package/src/starknet/swaps/handlers/claim/btc/BitcoinNoncedOutputClaimHandler.ts +73 -73
  142. package/src/starknet/swaps/handlers/claim/btc/BitcoinOutputClaimHandler.ts +67 -67
  143. package/src/starknet/swaps/handlers/claim/btc/BitcoinTxIdClaimHandler.ts +50 -50
  144. package/src/starknet/swaps/handlers/claim/btc/IBitcoinClaimHandler.ts +102 -102
  145. package/src/starknet/swaps/handlers/refund/TimelockRefundHandler.ts +38 -38
  146. package/src/starknet/swaps/modules/StarknetLpVault.ts +147 -147
  147. package/src/starknet/swaps/modules/StarknetSwapClaim.ts +141 -141
  148. package/src/starknet/swaps/modules/StarknetSwapInit.ts +300 -300
  149. package/src/starknet/swaps/modules/StarknetSwapRefund.ts +196 -196
  150. package/src/starknet/wallet/StarknetBrowserSigner.ts +12 -0
  151. package/src/starknet/wallet/StarknetPersistentSigner.ts +311 -0
  152. package/src/starknet/wallet/StarknetSigner.ts +84 -55
  153. package/src/starknet/wallet/{StarknetKeypairWallet.ts → accounts/StarknetKeypairWallet.ts} +44 -44
  154. package/src/utils/Utils.ts +262 -251
@@ -1,286 +1,393 @@
1
- import {StarknetModule} from "../StarknetModule";
2
- import {
3
- Call,
4
- DeployAccountContractPayload, DeployAccountContractTransaction,
5
- Invocation, InvocationsSignerDetails,
6
- BigNumberish,
7
- ETransactionStatus,
8
- ETransactionExecutionStatus
9
- } from "starknet";
10
- import {StarknetSigner} from "../../wallet/StarknetSigner";
11
- import {calculateHash, timeoutPromise, toBigInt, toHex, tryWithRetries} from "../../../utils/Utils";
12
-
13
- export type StarknetTx = ({
14
- type: "DEPLOY_ACCOUNT",
15
- tx: DeployAccountContractPayload,
16
- signed?: DeployAccountContractTransaction
17
- } | {
18
- type: "INVOKE",
19
- tx: Array<Call>,
20
- signed?: Invocation
21
- }) & {
22
- details: InvocationsSignerDetails & {maxFee?: BigNumberish},
23
- txId?: string
24
- };
25
-
26
- const MAX_UNCONFIRMED_TXS = 25;
27
-
28
- export class StarknetTransactions extends StarknetModule {
29
-
30
- private readonly latestConfirmedNonces: {[address: string]: bigint} = {};
31
-
32
- private cbkBeforeTxSigned: (tx: StarknetTx) => Promise<void>;
33
-
34
- /**
35
- * Waits for transaction confirmation using WS subscription and occasional HTTP polling, also re-sends
36
- * the transaction at regular interval
37
- *
38
- * @param tx starknet transaction to wait for confirmation for & keep re-sending until it confirms
39
- * @param abortSignal signal to abort waiting for tx confirmation
40
- * @private
41
- */
42
- private async confirmTransaction(tx: StarknetTx, abortSignal?: AbortSignal) {
43
- let state = "pending";
44
- while(state==="pending" || state==="not_found") {
45
- await timeoutPromise(3000, abortSignal);
46
- state = await this._getTxIdStatus(tx.txId);
47
- if(state==="not_found" && tx.signed!=null) await this.sendSignedTransaction(tx).catch(e => {
48
- if(e.baseError?.code === 59) return; //Transaction already in the mempool
49
- this.logger.error("confirmTransaction(): Error on transaction re-send: ", e);
50
- });
51
- }
52
- if(state==="rejected") throw new Error("Transaction rejected!");
53
- const nextAccountNonce = toBigInt(tx.details.nonce) + 1n;
54
- const currentNonce = this.latestConfirmedNonces[tx.details.walletAddress];
55
- if(currentNonce==null || nextAccountNonce > currentNonce) {
56
- this.latestConfirmedNonces[tx.details.walletAddress] = nextAccountNonce;
57
- }
58
- if(state==="reverted") throw new Error("Transaction reverted!");
59
- }
60
-
61
- /**
62
- * Prepares starknet transactions, checks if the account is deployed, assigns nonces if needed & calls beforeTxSigned callback
63
- *
64
- * @param signer
65
- * @param txs
66
- * @private
67
- */
68
- private async prepareTransactions(signer: StarknetSigner, txs: StarknetTx[]): Promise<void> {
69
- let nonce: bigint = await signer.getNonce();
70
- const latestConfirmedNonce = this.latestConfirmedNonces[signer.getAddress()];
71
- if(latestConfirmedNonce!=null && latestConfirmedNonce > nonce) {
72
- this.logger.debug("prepareTransactions(): Using nonce from local cache!");
73
- nonce = latestConfirmedNonce;
74
- }
75
- if(nonce===BigInt(0) && signer.isWalletAccount()) {
76
- //Just increment the nonce by one and hope the wallet is smart enough to deploy account first
77
- nonce = BigInt(1);
78
- }
79
- const deployPayload = await signer.checkAndGetDeployPayload(nonce);
80
- if(deployPayload!=null) {
81
- txs.unshift(await this.root.Accounts.getAccountDeployTransaction(deployPayload));
82
- }
83
-
84
- for(let i=0;i<txs.length;i++) {
85
- const tx = txs[i];
86
- if(tx.details.nonce!=null) nonce = BigInt(tx.details.nonce); //Take the nonce from last tx
87
- if(nonce==null) nonce = BigInt(await this.root.provider.getNonceForAddress(signer.getAddress())); //Fetch the nonce
88
- if(tx.details.nonce==null) tx.details.nonce = nonce;
89
-
90
- this.logger.debug("sendAndConfirm(): transaction prepared ("+(i+1)+"/"+txs.length+"), nonce: "+tx.details.nonce);
91
-
92
- nonce += BigInt(1);
93
-
94
- if(this.cbkBeforeTxSigned!=null) await this.cbkBeforeTxSigned(tx);
95
- }
96
- }
97
-
98
- /**
99
- * Sends out a signed transaction to the RPC
100
- *
101
- * @param tx Starknet tx to send
102
- * @param onBeforePublish a callback called before every transaction is published
103
- * @param signer
104
- * @private
105
- */
106
- private async sendSignedTransaction(
107
- tx: StarknetTx,
108
- onBeforePublish?: (txId: string, rawTx: string) => Promise<void>,
109
- signer?: StarknetSigner
110
- ): Promise<string> {
111
- if(onBeforePublish!=null) await onBeforePublish(tx.txId, await this.serializeTx(tx));
112
- this.logger.debug("sendSignedTransaction(): sending transaction: ", tx.txId);
113
-
114
- if(tx.signed==null) {
115
- let txHash: string;
116
- switch(tx.type) {
117
- case "INVOKE":
118
- txHash = (await signer.account.execute(tx.tx, tx.details)).transaction_hash;
119
- break;
120
- case "DEPLOY_ACCOUNT":
121
- txHash = (await signer.account.deployAccount(tx.tx, tx.details)).transaction_hash;
122
- break;
123
- default:
124
- throw new Error("Unsupported tx type!");
125
- }
126
- tx.txId = txHash;
127
- return txHash;
128
- }
129
-
130
- let txResult: string;
131
- switch(tx.type) {
132
- case "INVOKE":
133
- txResult = await this.provider.channel.invoke(tx.signed, tx.details).then(res => res.transaction_hash);
134
- break;
135
- case "DEPLOY_ACCOUNT":
136
- txResult = await this.provider.channel.deployAccount(tx.signed, tx.details).then((res: any) => res.transaction_hash);
137
- break;
138
- default:
139
- throw new Error("Unsupported tx type!");
140
- }
141
- if(tx.txId!==txResult) this.logger.warn("sendSignedTransaction(): sent tx hash not matching the precomputed hash!");
142
- this.logger.info("sendSignedTransaction(): tx sent, expected txHash: "+tx.txId+", txHash: "+txResult);
143
- return txResult;
144
- }
145
-
146
- /**
147
- * Prepares, signs , sends (in parallel or sequentially) & optionally waits for confirmation
148
- * of a batch of starknet transactions
149
- *
150
- * @param signer
151
- * @param txs transactions to send
152
- * @param waitForConfirmation whether to wait for transaction confirmations (this also makes sure the transactions
153
- * are re-sent at regular intervals)
154
- * @param abortSignal abort signal to abort waiting for transaction confirmations
155
- * @param parallel whether the send all the transaction at once in parallel or sequentially (such that transactions
156
- * are executed in order)
157
- * @param onBeforePublish a callback called before every transaction is published
158
- */
159
- public async sendAndConfirm(signer: StarknetSigner, txs: StarknetTx[], waitForConfirmation?: boolean, abortSignal?: AbortSignal, parallel?: boolean, onBeforePublish?: (txId: string, rawTx: string) => Promise<void>): Promise<string[]> {
160
- await this.prepareTransactions(signer, txs);
161
- if(!signer.isWalletAccount()) {
162
- for(let i=0;i<txs.length;i++) {
163
- const tx = txs[i];
164
- switch(tx.type) {
165
- case "INVOKE":
166
- tx.signed = await signer.account.buildInvocation(tx.tx, tx.details);
167
- calculateHash(tx);
168
- break;
169
- case "DEPLOY_ACCOUNT":
170
- tx.signed = await signer.account.buildAccountDeployPayload(tx.tx, tx.details);
171
- calculateHash(tx);
172
- break;
173
- default:
174
- throw new Error("Unsupported tx type!");
175
- }
176
- this.logger.debug("sendAndConfirm(): transaction signed ("+(i+1)+"/"+txs.length+"): "+tx.txId);
177
- }
178
- }
179
-
180
- this.logger.debug("sendAndConfirm(): sending transactions, count: "+txs.length+
181
- " waitForConfirmation: "+waitForConfirmation+" parallel: "+parallel);
182
-
183
- const txIds: string[] = [];
184
- if(parallel) {
185
- let promises: Promise<void>[] = [];
186
- for(let i=0;i<txs.length;i++) {
187
- const signedTx = txs[i];
188
- const txId = await this.sendSignedTransaction(signedTx, onBeforePublish, signer);
189
- if(waitForConfirmation) promises.push(this.confirmTransaction(signedTx, abortSignal));
190
- txIds.push(txId);
191
- this.logger.debug("sendAndConfirm(): transaction sent ("+(i+1)+"/"+txs.length+"): "+signedTx.txId);
192
- if(promises.length >= MAX_UNCONFIRMED_TXS) {
193
- await Promise.all(promises);
194
- promises = [];
195
- }
196
- }
197
- if(promises.length>0) await Promise.all(promises);
198
- } else {
199
- for(let i=0;i<txs.length;i++) {
200
- const signedTx = txs[i];
201
- const txId = await this.sendSignedTransaction(signedTx, onBeforePublish, signer);
202
- const confirmPromise = this.confirmTransaction(signedTx, abortSignal);
203
- this.logger.debug("sendAndConfirm(): transaction sent ("+(i+1)+"/"+txs.length+"): "+signedTx.txId);
204
- //Don't await the last promise when !waitForConfirmation
205
- if(i<txs.length-1 || waitForConfirmation) await confirmPromise;
206
- txIds.push(txId);
207
- }
208
- }
209
-
210
- this.logger.info("sendAndConfirm(): sent transactions, count: "+txs.length+
211
- " waitForConfirmation: "+waitForConfirmation+" parallel: "+parallel);
212
-
213
- return txIds;
214
- }
215
-
216
- /**
217
- * Serializes the solana transaction, saves the transaction, signers & last valid blockheight
218
- *
219
- * @param tx
220
- */
221
- public serializeTx(tx: StarknetTx): Promise<string> {
222
- return Promise.resolve(JSON.stringify(tx, (key, value) => {
223
- if(typeof(value)==="bigint") return toHex(value);
224
- return value;
225
- }));
226
- }
227
-
228
- /**
229
- * Deserializes saved solana transaction, extracting the transaction, signers & last valid blockheight
230
- *
231
- * @param txData
232
- */
233
- public deserializeTx(txData: string): Promise<StarknetTx> {
234
- return Promise.resolve(JSON.parse(txData));
235
- }
236
-
237
- /**
238
- * Gets the status of the raw starknet transaction
239
- *
240
- * @param tx
241
- */
242
- public async getTxStatus(tx: string): Promise<"pending" | "success" | "not_found" | "reverted"> {
243
- const parsedTx: StarknetTx = await this.deserializeTx(tx);
244
- return await this.getTxIdStatus(parsedTx.txId);
245
- }
246
-
247
- /**
248
- * Gets the status of the starknet transaction with a specific txId
249
- *
250
- * @param txId
251
- */
252
- public async _getTxIdStatus(txId: string): Promise<"pending" | "success" | "not_found" | "reverted" | "rejected"> {
253
- const status = await this.provider.getTransactionStatus(txId).catch(e => {
254
- if(e.message!=null && e.message.includes("29: Transaction hash not found")) return null;
255
- throw e;
256
- });
257
- if(status==null) return "not_found";
258
- if(status.finality_status===ETransactionStatus.RECEIVED) return "pending";
259
- if(status.finality_status===ETransactionStatus.REJECTED) return "rejected";
260
- if(status.execution_status===ETransactionExecutionStatus.SUCCEEDED){
261
- return "success";
262
- }
263
- return "reverted";
264
- }
265
-
266
- /**
267
- * Gets the status of the starknet transaction with a specific txId
268
- *
269
- * @param txId
270
- */
271
- public async getTxIdStatus(txId: string): Promise<"pending" | "success" | "not_found" | "reverted"> {
272
- const status = await this._getTxIdStatus(txId);
273
- if(status==="rejected") return "reverted";
274
- return status;
275
- }
276
-
277
- public onBeforeTxSigned(callback: (tx: StarknetTx) => Promise<void>): void {
278
- this.cbkBeforeTxSigned = callback;
279
- }
280
-
281
- public offBeforeTxSigned(callback: (tx: StarknetTx) => Promise<void>): boolean {
282
- this.cbkBeforeTxSigned = null;
283
- return true;
284
- }
285
-
1
+ import {StarknetModule} from "../StarknetModule";
2
+ import {
3
+ Call,
4
+ DeployAccountContractPayload, DeployAccountContractTransaction,
5
+ Invocation, InvocationsSignerDetails,
6
+ BigNumberish,
7
+ ETransactionStatus,
8
+ ETransactionExecutionStatus, BlockTag
9
+ } from "starknet";
10
+ import {StarknetSigner} from "../../wallet/StarknetSigner";
11
+ import {calculateHash, timeoutPromise, toBigInt, toHex, tryWithRetries} from "../../../utils/Utils";
12
+
13
+ export type StarknetTxBase = {
14
+ details: InvocationsSignerDetails & {maxFee?: BigNumberish},
15
+ txId?: string
16
+ };
17
+
18
+ export type StarknetTxInvoke = StarknetTxBase & {
19
+ type: "INVOKE",
20
+ tx: Array<Call>,
21
+ signed?: Invocation
22
+ };
23
+
24
+ export function isStarknetTxInvoke(obj: any): obj is StarknetTxInvoke {
25
+ return typeof(obj)==="object" &&
26
+ typeof(obj.details)==="object" &&
27
+ (obj.txId==null || typeof(obj.txId)==="string") &&
28
+ obj.type==="INVOKE" &&
29
+ Array.isArray(obj.tx) &&
30
+ (obj.signed==null || typeof(obj.signed)==="object");
31
+ }
32
+
33
+ export type StarknetTxDeployAccount = StarknetTxBase & {
34
+ type: "DEPLOY_ACCOUNT",
35
+ tx: DeployAccountContractPayload,
36
+ signed?: DeployAccountContractTransaction
37
+ };
38
+
39
+ export function isStarknetTxDeployAccount(obj: any): obj is StarknetTxDeployAccount {
40
+ return typeof(obj)==="object" &&
41
+ typeof(obj.details)==="object" &&
42
+ (obj.txId==null || typeof(obj.txId)==="string") &&
43
+ obj.type==="DEPLOY_ACCOUNT" &&
44
+ Array.isArray(obj.tx) &&
45
+ (obj.signed==null || typeof(obj.signed)==="object");
46
+ }
47
+
48
+ export type StarknetTx = StarknetTxInvoke | StarknetTxDeployAccount;
49
+
50
+ const MAX_UNCONFIRMED_TXS = 25;
51
+
52
+ export class StarknetTransactions extends StarknetModule {
53
+
54
+ private readonly latestConfirmedNonces: {[address: string]: bigint} = {};
55
+ private readonly latestPendingNonces: {[address: string]: bigint} = {};
56
+ private readonly latestSignedNonces: {[address: string]: bigint} = {};
57
+
58
+ readonly _cbksBeforeTxReplace: ((oldTx: string, oldTxId: string, newTx: string, newTxId: string) => Promise<void>)[] = [];
59
+ private readonly cbksBeforeTxSigned: ((tx: StarknetTx) => Promise<void>)[] = [];
60
+
61
+ readonly _knownTxSet: Set<string> = new Set();
62
+
63
+ sendTransaction(tx: StarknetTx): Promise<string> {
64
+ switch(tx.type) {
65
+ case "INVOKE":
66
+ return this.provider.channel.invoke(tx.signed, tx.details).then(res => res.transaction_hash);
67
+ case "DEPLOY_ACCOUNT":
68
+ return this.provider.channel.deployAccount(tx.signed, tx.details).then((res: any) => res.transaction_hash);
69
+ default:
70
+ throw new Error("Unsupported tx type!");
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Returns the nonce of the account or 0, if the account is not deployed yet
76
+ *
77
+ * @param address
78
+ */
79
+ async getNonce(address: string): Promise<bigint> {
80
+ try {
81
+ return BigInt(await this.provider.getNonceForAddress(address, BlockTag.PRE_CONFIRMED));
82
+ } catch (e) {
83
+ if(e.message!=null && e.message.includes("20: Contract not found")) {
84
+ return BigInt(0);
85
+ }
86
+ throw e;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Waits for transaction confirmation using WS subscription and occasional HTTP polling, also re-sends
92
+ * the transaction at regular interval
93
+ *
94
+ * @param tx starknet transaction to wait for confirmation for & keep re-sending until it confirms
95
+ * @param abortSignal signal to abort waiting for tx confirmation
96
+ * @private
97
+ */
98
+ private async confirmTransaction(tx: StarknetTx, abortSignal?: AbortSignal): Promise<string> {
99
+ const checkTxns: Set<string> = new Set([tx.txId]);
100
+
101
+ const txReplaceListener = (oldTx: string, oldTxId: string, newTx: string, newTxId: string) => {
102
+ if(checkTxns.has(oldTxId)) checkTxns.add(newTxId);
103
+ return Promise.resolve();
104
+ };
105
+ this.onBeforeTxReplace(txReplaceListener);
106
+
107
+ let state = "pending";
108
+ let confirmedTxId: string = null;
109
+ while(state==="pending" || state==="not_found") {
110
+ await timeoutPromise(3000, abortSignal);
111
+ for(let txId of checkTxns) {
112
+ //TODO: Rebroadcast latest tx if possible, we might need to do that in case we use 2 different RPCs on the backend
113
+ // as the other one might not have the tx in their mempool
114
+ // if(state==="not_found" && tx.signed!=null) await this.sendSignedTransaction(tx).catch(e => {
115
+ // if(e.baseError?.code === 59) return; //Transaction already in the mempool
116
+ // this.logger.error("confirmTransaction(): Error on transaction re-send: ", e);
117
+ // });
118
+ state = await this._getTxIdStatus(txId);
119
+ if(state==="rejected" || state==="reverted" || state==="success") {
120
+ confirmedTxId = txId;
121
+ break;
122
+ }
123
+ }
124
+ }
125
+
126
+ this.offBeforeTxReplace(txReplaceListener);
127
+
128
+ if(state==="rejected") throw new Error("Transaction rejected!");
129
+
130
+ const nextAccountNonce = toBigInt(tx.details.nonce) + 1n;
131
+ const currentConfirmedNonce = this.latestConfirmedNonces[toHex(tx.details.walletAddress)];
132
+ if(currentConfirmedNonce==null || nextAccountNonce > currentConfirmedNonce) {
133
+ this.latestConfirmedNonces[toHex(tx.details.walletAddress)] = nextAccountNonce;
134
+ }
135
+ if(state==="reverted") throw new Error("Transaction reverted!");
136
+
137
+ return confirmedTxId;
138
+ }
139
+
140
+ /**
141
+ * Prepares starknet transactions, checks if the account is deployed, assigns nonces if needed & calls beforeTxSigned callback
142
+ *
143
+ * @param signer
144
+ * @param txs
145
+ * @private
146
+ */
147
+ private async prepareTransactions(signer: StarknetSigner, txs: StarknetTx[]): Promise<void> {
148
+ let nonce: bigint = await this.getNonce(signer.getAddress());
149
+ const latestPendingNonce = this.latestPendingNonces[toHex(signer.getAddress())];
150
+ if(latestPendingNonce!=null && latestPendingNonce > nonce) {
151
+ this.logger.debug("prepareTransactions(): Using 'pending' nonce from local cache!");
152
+ nonce = latestPendingNonce;
153
+ }
154
+
155
+ //Add deploy account tx
156
+ if(nonce===0n) {
157
+ const deployPayload = await signer.getDeployPayload();
158
+ if(deployPayload!=null) txs.unshift(await this.root.Accounts.getAccountDeployTransaction(deployPayload));
159
+ }
160
+
161
+ if(!signer.isManagingNoncesInternally) {
162
+ if(nonce===0n) {
163
+ //Just increment the nonce by one and hope the wallet is smart enough to deploy account first
164
+ nonce = 1n;
165
+ }
166
+
167
+ for(let i=0;i<txs.length;i++) {
168
+ const tx = txs[i];
169
+ if(tx.details.nonce!=null) nonce = BigInt(tx.details.nonce); //Take the nonce from last tx
170
+ if(nonce==null) nonce = BigInt(await this.root.provider.getNonceForAddress(signer.getAddress())); //Fetch the nonce
171
+ if(tx.details.nonce==null) tx.details.nonce = nonce;
172
+
173
+ this.logger.debug("sendAndConfirm(): transaction prepared ("+(i+1)+"/"+txs.length+"), nonce: "+tx.details.nonce);
174
+
175
+ nonce += BigInt(1);
176
+ }
177
+ }
178
+
179
+ for(let tx of txs) {
180
+ for(let callback of this.cbksBeforeTxSigned) {
181
+ await callback(tx);
182
+ }
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Sends out a signed transaction to the RPC
188
+ *
189
+ * @param tx Starknet tx to send
190
+ * @param onBeforePublish a callback called before every transaction is published
191
+ * @private
192
+ */
193
+ private async sendSignedTransaction(
194
+ tx: StarknetTx,
195
+ onBeforePublish?: (txId: string, rawTx: string) => Promise<void>
196
+ ): Promise<string> {
197
+ if(onBeforePublish!=null) await onBeforePublish(tx.txId, StarknetTransactions.serializeTx(tx));
198
+ this.logger.debug("sendSignedTransaction(): sending transaction: ", tx.txId);
199
+
200
+ const txResult: string = await this.sendTransaction(tx);
201
+ if(tx.txId!==txResult) this.logger.warn("sendSignedTransaction(): sent tx hash not matching the precomputed hash!");
202
+ this.logger.info("sendSignedTransaction(): tx sent, expected txHash: "+tx.txId+", txHash: "+txResult);
203
+ return txResult;
204
+ }
205
+
206
+ /**
207
+ * Prepares, signs , sends (in parallel or sequentially) & optionally waits for confirmation
208
+ * of a batch of starknet transactions
209
+ *
210
+ * @param signer
211
+ * @param txs transactions to send
212
+ * @param waitForConfirmation whether to wait for transaction confirmations (this also makes sure the transactions
213
+ * are re-sent at regular intervals)
214
+ * @param abortSignal abort signal to abort waiting for transaction confirmations
215
+ * @param parallel whether the send all the transaction at once in parallel or sequentially (such that transactions
216
+ * are executed in order)
217
+ * @param onBeforePublish a callback called before every transaction is published
218
+ */
219
+ public async sendAndConfirm(signer: StarknetSigner, txs: StarknetTx[], waitForConfirmation?: boolean, abortSignal?: AbortSignal, parallel?: boolean, onBeforePublish?: (txId: string, rawTx: string) => Promise<void>): Promise<string[]> {
220
+ await this.prepareTransactions(signer, txs);
221
+ const signedTxs: StarknetTx[] = [];
222
+
223
+ //Don't separate the signing process from the sending when using browser-based wallet
224
+ if(signer.signTransaction!=null) for(let i=0;i<txs.length;i++) {
225
+ const tx = txs[i];
226
+ const signedTx = await signer.signTransaction(tx);
227
+ signedTxs.push(signedTx);
228
+ this.logger.debug("sendAndConfirm(): transaction signed ("+(i+1)+"/"+txs.length+"): "+signedTx.txId);
229
+
230
+ const nextAccountNonce = BigInt(signedTx.details.nonce) + 1n;
231
+ const currentSignedNonce = this.latestSignedNonces[toHex(signedTx.details.walletAddress)];
232
+ if(currentSignedNonce==null || nextAccountNonce > currentSignedNonce) {
233
+ this.latestSignedNonces[toHex(signedTx.details.walletAddress)] = nextAccountNonce;
234
+ }
235
+ }
236
+
237
+ this.logger.debug("sendAndConfirm(): sending transactions, count: "+txs.length+
238
+ " waitForConfirmation: "+waitForConfirmation+" parallel: "+parallel);
239
+
240
+ const txIds: string[] = [];
241
+ if(parallel) {
242
+ let promises: Promise<string>[] = [];
243
+ for(let i=0;i<txs.length;i++) {
244
+ let tx: StarknetTx;
245
+ if(signer.signTransaction==null) {
246
+ const txId = await signer.sendTransaction(txs[i], onBeforePublish);
247
+ tx = txs[i];
248
+ tx.txId = txId;
249
+ } else {
250
+ const signedTx = signedTxs[i];
251
+ await this.sendSignedTransaction(signedTx, onBeforePublish);
252
+ tx = signedTx;
253
+ }
254
+
255
+ if(tx.details.nonce!=null) {
256
+ const nextAccountNonce = BigInt(tx.details.nonce) + 1n;
257
+ const currentPendingNonce = this.latestPendingNonces[toHex(tx.details.walletAddress)];
258
+ if(currentPendingNonce==null || nextAccountNonce > currentPendingNonce) {
259
+ this.latestPendingNonces[toHex(tx.details.walletAddress)] = nextAccountNonce;
260
+ }
261
+ }
262
+
263
+ promises.push(this.confirmTransaction(tx, abortSignal));
264
+ if(!waitForConfirmation) txIds.push(tx.txId);
265
+ this.logger.debug("sendAndConfirm(): transaction sent ("+(i+1)+"/"+txs.length+"): "+tx.txId);
266
+ if(promises.length >= MAX_UNCONFIRMED_TXS) {
267
+ if(waitForConfirmation) txIds.push(...await Promise.all(promises));
268
+ promises = [];
269
+ }
270
+ }
271
+ if(waitForConfirmation && promises.length>0) {
272
+ txIds.push(...await Promise.all(promises));
273
+ }
274
+ } else {
275
+ for(let i=0;i<txs.length;i++) {
276
+ let tx: StarknetTx;
277
+ if(signer.signTransaction==null) {
278
+ const txId = await signer.sendTransaction(txs[i], onBeforePublish);
279
+ tx = txs[i];
280
+ tx.txId = txId;
281
+ } else {
282
+ const signedTx = signedTxs[i];
283
+ await this.sendSignedTransaction(signedTx, onBeforePublish);
284
+ tx = signedTx;
285
+ }
286
+
287
+ if(tx.details.nonce!=null) {
288
+ const nextAccountNonce = BigInt(tx.details.nonce) + 1n;
289
+ const currentPendingNonce = this.latestPendingNonces[toHex(tx.details.walletAddress)];
290
+ if(currentPendingNonce==null || nextAccountNonce > currentPendingNonce) {
291
+ this.latestPendingNonces[toHex(tx.details.walletAddress)] = nextAccountNonce;
292
+ }
293
+ }
294
+
295
+ const confirmPromise = this.confirmTransaction(tx, abortSignal);
296
+ this.logger.debug("sendAndConfirm(): transaction sent ("+(i+1)+"/"+txs.length+"): "+tx.txId);
297
+ //Don't await the last promise when !waitForConfirmation
298
+ let txHash = tx.txId;
299
+ if(i<txs.length-1 || waitForConfirmation) txHash = await confirmPromise;
300
+ txIds.push(txHash);
301
+ }
302
+ }
303
+
304
+ this.logger.info("sendAndConfirm(): sent transactions, count: "+txs.length+
305
+ " waitForConfirmation: "+waitForConfirmation+" parallel: "+parallel);
306
+
307
+ return txIds;
308
+ }
309
+
310
+ /**
311
+ * Serializes the solana transaction, saves the transaction, signers & last valid blockheight
312
+ *
313
+ * @param tx
314
+ */
315
+ public static serializeTx(tx: StarknetTx): string {
316
+ return JSON.stringify(tx, (key, value) => {
317
+ if(typeof(value)==="bigint") return toHex(value);
318
+ return value;
319
+ });
320
+ }
321
+
322
+ /**
323
+ * Deserializes saved solana transaction, extracting the transaction, signers & last valid blockheight
324
+ *
325
+ * @param txData
326
+ */
327
+ public static deserializeTx(txData: string): StarknetTx {
328
+ return JSON.parse(txData);
329
+ }
330
+
331
+ /**
332
+ * Gets the status of the raw starknet transaction
333
+ *
334
+ * @param tx
335
+ */
336
+ public async getTxStatus(tx: string): Promise<"pending" | "success" | "not_found" | "reverted"> {
337
+ const parsedTx: StarknetTx = StarknetTransactions.deserializeTx(tx);
338
+ return await this.getTxIdStatus(parsedTx.txId);
339
+ }
340
+
341
+ /**
342
+ * Gets the status of the starknet transaction with a specific txId
343
+ *
344
+ * @param txId
345
+ */
346
+ public async _getTxIdStatus(txId: string): Promise<"pending" | "success" | "not_found" | "reverted" | "rejected"> {
347
+ const status = await this.provider.getTransactionStatus(txId).catch(e => {
348
+ if(e.message!=null && e.message.includes("29: Transaction hash not found")) return null;
349
+ throw e;
350
+ });
351
+ if(status==null) return this._knownTxSet.has(txId) ? "pending" : "not_found";
352
+ if(status.finality_status===ETransactionStatus.RECEIVED) return "pending";
353
+ if(status.finality_status===ETransactionStatus.REJECTED) return "rejected";
354
+ if(status.execution_status===ETransactionExecutionStatus.SUCCEEDED){
355
+ return "success";
356
+ }
357
+ return "reverted";
358
+ }
359
+
360
+ /**
361
+ * Gets the status of the starknet transaction with a specific txId
362
+ *
363
+ * @param txId
364
+ */
365
+ public async getTxIdStatus(txId: string): Promise<"pending" | "success" | "not_found" | "reverted"> {
366
+ const status = await this._getTxIdStatus(txId);
367
+ if(status==="rejected") return "reverted";
368
+ return status;
369
+ }
370
+
371
+ onBeforeTxReplace(callback: (oldTx: string, oldTxId: string, newTx: string, newTxId: string) => Promise<void>): void {
372
+ this._cbksBeforeTxReplace.push(callback);
373
+ }
374
+
375
+ offBeforeTxReplace(callback: (oldTx: string, oldTxId: string, newTx: string, newTxId: string) => Promise<void>): boolean {
376
+ const index = this._cbksBeforeTxReplace.indexOf(callback);
377
+ if(index===-1) return false;
378
+ this._cbksBeforeTxReplace.splice(index, 1);
379
+ return true;
380
+ }
381
+
382
+ public onBeforeTxSigned(callback: (tx: StarknetTx) => Promise<void>): void {
383
+ this.cbksBeforeTxSigned.push(callback);
384
+ }
385
+
386
+ public offBeforeTxSigned(callback: (tx: StarknetTx) => Promise<void>): boolean {
387
+ const index = this.cbksBeforeTxSigned.indexOf(callback);
388
+ if(index===-1) return false;
389
+ this.cbksBeforeTxSigned.splice(index, 1);
390
+ return true;
391
+ }
392
+
286
393
  }