@deserialize/multi-vm-wallet 1.2.0 → 1.2.2

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 (60) hide show
  1. package/dist/bip32Old.d.ts +0 -51
  2. package/dist/bip32Old.js +876 -845
  3. package/dist/bip32Old.js.map +1 -1
  4. package/dist/bip32Small.d.ts +0 -9
  5. package/dist/bip32Small.js +78 -113
  6. package/dist/bip32Small.js.map +1 -1
  7. package/dist/constant.d.ts +16 -0
  8. package/dist/constant.js +19 -3
  9. package/dist/constant.js.map +1 -1
  10. package/dist/english.d.ts +1 -0
  11. package/dist/english.js +2052 -0
  12. package/dist/english.js.map +1 -0
  13. package/dist/evm/evm.d.ts +6 -1
  14. package/dist/evm/evm.js +36 -45
  15. package/dist/evm/evm.js.map +1 -1
  16. package/dist/evm/transactionParsing.d.ts +3687 -0
  17. package/dist/evm/transactionParsing.js +441 -0
  18. package/dist/evm/transactionParsing.js.map +1 -0
  19. package/dist/evm/utils.d.ts +2 -9
  20. package/dist/evm/utils.js +19 -22
  21. package/dist/evm/utils.js.map +1 -1
  22. package/dist/helpers/index.d.ts +4 -0
  23. package/dist/helpers/index.js +13 -0
  24. package/dist/helpers/index.js.map +1 -0
  25. package/dist/svm/constant.d.ts +15 -0
  26. package/dist/svm/constant.js +25 -0
  27. package/dist/svm/constant.js.map +1 -0
  28. package/dist/svm/svm.d.ts +5 -2
  29. package/dist/svm/svm.js +10 -0
  30. package/dist/svm/svm.js.map +1 -1
  31. package/dist/svm/transactionParsing.d.ts +28 -0
  32. package/dist/svm/transactionParsing.js +207 -0
  33. package/dist/svm/transactionParsing.js.map +1 -0
  34. package/dist/svm/utils.d.ts +4 -3
  35. package/dist/svm/utils.js +83 -10
  36. package/dist/svm/utils.js.map +1 -1
  37. package/dist/test.d.ts +1 -1
  38. package/dist/test.js +47 -9
  39. package/dist/test.js.map +1 -1
  40. package/dist/types.d.ts +5 -1
  41. package/dist/types.js.map +1 -1
  42. package/dist/walletBip32.js +1 -1
  43. package/dist/walletBip32.js.map +1 -1
  44. package/package.json +4 -2
  45. package/utils/IChainWallet.ts +1 -1
  46. package/utils/bip32Old.ts +988 -988
  47. package/utils/bip32Small.ts +78 -78
  48. package/utils/constant.ts +22 -4
  49. package/utils/english.ts +2048 -0
  50. package/utils/evm/evm.ts +54 -48
  51. package/utils/evm/transactionParsing.ts +639 -0
  52. package/utils/evm/utils.ts +29 -33
  53. package/utils/helpers/index.ts +11 -0
  54. package/utils/svm/constant.ts +29 -0
  55. package/utils/svm/svm.ts +14 -2
  56. package/utils/svm/transactionParsing.ts +294 -0
  57. package/utils/svm/utils.ts +105 -14
  58. package/utils/test.ts +56 -6
  59. package/utils/types.ts +6 -1
  60. package/utils/walletBip32.ts +1 -1
package/dist/bip32Old.js CHANGED
@@ -1,855 +1,886 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.SoonClass = exports.chain = void 0;
40
- /* eslint-disable @typescript-eslint/no-explicit-any */
41
- const bip39 = __importStar(require("@scure/bip39"));
42
- const buffer_1 = require("buffer"); // Import the polyfill
43
- window.Buffer = buffer_1.Buffer; // Inject Buffer into the global scope
44
- const crypto_js_1 = __importDefault(require("crypto-js"));
45
- const english_1 = require("@scure/bip39/wordlists/english");
46
- const hmac_1 = require("@noble/hashes/hmac");
47
- const sha2_1 = require("@noble/hashes/sha2");
48
- const web3_js_1 = require("@solana/web3.js");
49
- exports.chain = {
50
- name: "SOON TESTNET",
51
- symbol: "SOON",
52
- chainDecimals: web3_js_1.LAMPORTS_PER_SOL.toString(),
53
- explorer: "https://explorer.testnet.soo.network",
54
- http: ["https://rpc.testnet.soo.network/rpc"],
55
- ws: "",
56
- nativeTokenProfitSpreed: "0.04",
57
- chainTokenExplorer: "https://explorer.testnet.soo.network/",
58
- isEvm: false,
59
- isDevnet: true,
60
- };
61
- class MasterSmartWalletClass {
62
- constructor(mnemonic, chain) {
63
- this.isDevnet = false;
64
- const seed = bip39.mnemonicToSeedSync(mnemonic);
65
- this.seed = seed.toString();
66
- this.chain = chain;
67
- const nn = Math.floor(Math.random() * this.chain.http.length);
68
- this.connection = new web3_js_1.Connection(this.chain.http[nn], "confirmed");
69
- this.masterKeyPair = this.deriveChildPrivateKey(0);
70
- this.isDevnet = this.chain.isDevnet;
71
- this.masterAddress = this.masterKeyPair.publicKey;
72
- }
73
- // static validateAddress(address: string) {
74
- // try {
75
- // new PublicKey(address);
76
- // return true;
77
- // } catch (e) {
78
- // console.log("e: ", e);
79
- // return false;
80
- // }
81
- // }
82
- // validateAddress(address: string) {
83
- // try {
84
- // new PublicKey(address);
85
- // return true;
86
- // } catch (e) {
87
- // console.log("e: ", e);
88
- // return false;
89
- // }
90
- // }
91
- // static async createSendConfirmRetryDeserializedTransaction(
92
- // deserializedBuffer: Buffer,
93
- // senderKeypairs: Keypair[],
94
- // connection: Connection,
95
- // latestBlockhash: Readonly<{
96
- // blockhash: string;
97
- // lastValidBlockHeight: number;
98
- // }>
99
- // ) {
100
- // let status = false;
101
- // const transaction = VersionedTransaction.deserialize(deserializedBuffer);
102
- // transaction.sign(senderKeypairs);
103
- // const explorerUrl = "";
104
- // console.log("sending transaction...");
105
- // // We first simulate whether the transaction would be successful
106
- // const { value: simulatedTransactionResponse } =
107
- // await connection.simulateTransaction(transaction, {
108
- // replaceRecentBlockhash: true,
109
- // commitment: "processed",
110
- // });
111
- // const { err, logs } = simulatedTransactionResponse;
112
- // if (err) {
113
- // // Simulation error, we can check the logs for more details
114
- // // If you are getting an invalid account error, make sure that you have the input mint account to actually swap from.
115
- // console.error("Simulation Error:");
116
- // console.error(err);
117
- // console.error(logs);
118
- // return { status, error: err };
119
- // }
120
- // // Execute the transaction
121
- // const serializedTransaction = Buffer.from(transaction.serialize());
122
- // const blockhash = transaction.message.recentBlockhash;
123
- // console.log("blockhash: ", blockhash);
124
- // const transactionResponse = await transactionSenderAndConfirmationWaiter({
125
- // connection,
126
- // serializedTransaction,
127
- // blockhashWithExpiryBlockHeight: {
128
- // blockhash,
129
- // lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
130
- // },
131
- // });
132
- // // If we are not getting a response back, the transaction has not confirmed.
133
- // if (!transactionResponse) {
134
- // console.error("Transaction not confirmed");
135
- // // !WE SHOULD RETRY THE TRANSACTION AGAIN HERE
136
- // throw new TransactionNotConfirmedError({});
137
- // }
138
- // if (transactionResponse.meta?.err) {
139
- // console.error(transactionResponse.meta?.err);
140
- // }
141
- // console.log("View transaction on explorer:", explorerUrl);
142
- // status = true;
143
- // return { status, signature: transactionResponse.transaction.signatures };
144
- // }
145
- static generateSalt() {
146
- return crypto_js_1.default.lib.WordArray.random(16).toString(); // 128-bit salt
147
- }
148
- static deriveKey(password, salt, iterations = 10000, keySize = 256 / 32) {
149
- return crypto_js_1.default.PBKDF2(password, crypto_js_1.default.enc.Hex.parse(salt), {
150
- keySize: keySize,
151
- iterations: iterations,
152
- }).toString();
153
- }
154
- static encryptSeedPhrase(seedPhrase, password) {
155
- const salt = this.generateSalt(); // Generate a unique salt for this encryption
156
- const key = this.deriveKey(password, salt); // Derive a key using PBKDF2
157
- // Encrypt the seed phrase with AES using the derived key
158
- const encrypted = crypto_js_1.default.AES.encrypt(seedPhrase, key).toString();
159
- // Return the encrypted data and the salt (needed for decryption)
160
- return { encrypted, salt };
161
- }
162
- static decryptSeedPhrase(encryptedSeedPhrase, password, salt) {
163
- try {
164
- const key = this.deriveKey(password, salt); // Derive the key using the same salt
165
- const bytes = crypto_js_1.default.AES.decrypt(encryptedSeedPhrase, key);
166
- const seedPhrase = bytes.toString(crypto_js_1.default.enc.Utf8);
167
- // Check if decryption was successful
168
- if (!seedPhrase)
169
- throw new Error("Decryption failed.");
170
- return seedPhrase;
171
- }
172
- catch (e) {
173
- console.error("Invalid password or corrupted data:", e.message);
174
- return null;
175
- }
176
- }
177
- // getNativeBalance = async () => {
178
- // const connection = new Connection(
179
- // this.chain.http[Math.floor(Math.random() * this.chain.http.length)]
180
- // );
181
- // try {
182
- // const publicKey = new PublicKey(this.masterAddress);
183
- // const bal = await connection.getBalance(publicKey);
184
- // return bal / LAMPORTS_PER_SOL;
185
- // } catch (error: any) {
186
- // console.log("error: ", error);
187
- // console.log("error message: ", error.message);
188
- // throw new Error(
189
- // `the address passed is not a valid solana address : ${this.masterAddress}`
190
- // );
191
- // }
192
- // };
193
- // getTokenBalance = async (token: string) => {
194
- // try {
195
- // // Get the balance from the token account
196
- // const tokenAccount = await this._getTokenAccountAccount(token);
197
- // console.log("token: ", token);
198
- // const tokenBalance = await this.connection.getTokenAccountBalance(
199
- // tokenAccount.address
200
- // );
201
- // console.log(`User Token Balance: ${tokenBalance.value.uiAmount}`);
202
- // //convert tokenBalance bigInt to decimal
203
- // const tokenBalanceDecimal = tokenBalance.value.uiAmount;
204
- // if (tokenBalanceDecimal == null) {
205
- // throw new Error("could not get balance");
206
- // }
207
- // return tokenBalanceDecimal / LAMPORTS_PER_SOL;
208
- // } catch (error) {
209
- // console.log("error: ", error);
210
- // return 0;
211
- // }
212
- // };
213
- // _getTokenAccountAccount = async (token: string): Promise<Account> => {
214
- // try {
215
- // // Create PublicKey objects for user and token mint
216
- // const userPublicKeyObj = new PublicKey(this.masterAddress);
217
- // const tokenMintAddressObj = new PublicKey(token);
218
- // // Get the associated token account address for the user and the token mint
219
- // const associatedTokenAccount = await getAssociatedTokenAddress(
220
- // tokenMintAddressObj, // The token mint address
221
- // userPublicKeyObj // The user's public key
222
- // );
223
- // // Fetch the token account information
224
- // const tokenAccount = await getAccount(
225
- // this.connection,
226
- // associatedTokenAccount
227
- // );
228
- // return tokenAccount;
229
- // } catch (error) {
230
- // console.error("Error getting token balance:", error);
231
- // throw error;
232
- // }
233
- // };
234
- // async createSendConfirmRetryDeserializedTransaction(
235
- // deserializedBuffer: Buffer,
236
- // senderKeypairs: Keypair[],
237
- // connection: Connection,
238
- // latestBlockhash: Readonly<{
239
- // blockhash: string;
240
- // lastValidBlockHeight: number;
241
- // }>
242
- // ) {
243
- // let status = false;
244
- // const transaction = VersionedTransaction.deserialize(deserializedBuffer);
245
- // transaction.sign(senderKeypairs);
246
- // let explorerUrl = "";
247
- // console.log("sending transaction...");
248
- // // We first simulate whether the transaction would be successful
249
- // const { value: simulatedTransactionResponse } =
250
- // await connection.simulateTransaction(transaction, {
251
- // replaceRecentBlockhash: true,
252
- // commitment: "processed",
253
- // });
254
- // const { err, logs } = simulatedTransactionResponse;
255
- // if (err) {
256
- // // Simulation error, we can check the logs for more details
257
- // // If you are getting an invalid account error, make sure that you have the input mint account to actually swap from.
258
- // console.error("Simulation Error:");
259
- // console.error(err);
260
- // console.error(logs);
261
- // return { status, error: err };
262
- // }
263
- // // Execute the transaction
264
- // const serializedTransaction = Buffer.from(transaction.serialize());
265
- // const blockhash = transaction.message.recentBlockhash;
266
- // console.log("blockhash: ", blockhash);
267
- // const transactionResponse = await transactionSenderAndConfirmationWaiter({
268
- // connection,
269
- // serializedTransaction,
270
- // blockhashWithExpiryBlockHeight: {
271
- // blockhash,
272
- // lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
273
- // },
274
- // });
275
- // // If we are not getting a response back, the transaction has not confirmed.
276
- // if (!transactionResponse) {
277
- // console.error("Transaction not confirmed");
278
- // //!WE SHOULD RETRY THE TRANSACTION AGAIN HERE
279
- // throw new TransactionNotConfirmedError({});
280
- // }
281
- // if (transactionResponse.meta?.err) {
282
- // console.error(transactionResponse.meta?.err);
283
- // }
284
- // explorerUrl = `${this.chain.explorer}/tx/${transactionResponse.transaction.signatures}`;
285
- // console.log("View transaction on explorer:", explorerUrl);
286
- // status = true;
287
- // return {
288
- // signature: `${transactionResponse.transaction.signatures}`,
289
- // status,
290
- // };
291
- // }
292
- // async sendTransaction(
293
- // recipientAddress: string,
294
- // amount: number,
295
- // senderSecretKey: Uint8Array
296
- // ) {
297
- // /**
298
- // * internal method for sending sol transaction
299
- // */
300
- // const connection = this.connection;
301
- // const senderKeypair = Keypair.fromSecretKey(senderSecretKey);
302
- // try {
303
- // new PublicKey(recipientAddress);
304
- // } catch (error: any) {
305
- // console.log(
306
- // "the recipientAddress is not a valid public key",
307
- // recipientAddress
308
- // );
309
- // throw new error();
310
- // }
311
- // const senderBalance = await connection.getBalance(senderKeypair.publicKey);
312
- // console.log("senderBalance: ", senderBalance);
313
- // if (senderBalance < amount * LAMPORTS_PER_SOL) {
314
- // console.log(
315
- // "insufficient funds: sender balance is less than the amount to send"
316
- // );
317
- // throw new Error(
318
- // "insufficient funds: sender balance is less than the amount to send"
319
- // );
320
- // }
321
- // const amountPlusFees = amount * LAMPORTS_PER_SOL + 20045;
322
- // if (senderBalance < amountPlusFees) {
323
- // console.log(
324
- // "insufficient funds + gass : sender balance is less than the amount Plus gass to send"
325
- // );
326
- // throw new Error(
327
- // "insufficient funds + gass : sender balance is less than the amount Plus gass to send"
328
- // );
329
- // }
330
- // // request a specific compute unit budget
331
- // const modifyComputeUnits = ComputeBudgetProgram.setComputeUnitLimit({
332
- // units: 1500,
333
- // });
334
- // // set the desired priority fee
335
- // const addPriorityFee = ComputeBudgetProgram.setComputeUnitPrice({
336
- // microLamports: 30000,
337
- // });
338
- // const instructions: TransactionInstruction[] = [
339
- // addPriorityFee,
340
- // modifyComputeUnits,
341
- // SystemProgram.transfer({
342
- // fromPubkey: senderKeypair.publicKey,
343
- // toPubkey: new PublicKey(recipientAddress),
344
- // lamports: LAMPORTS_PER_SOL * amount,
345
- // }),
346
- // ];
347
- // const latestBlockhash = await connection.getLatestBlockhash();
348
- // const messageV0 = new TransactionMessage({
349
- // payerKey: senderKeypair.publicKey,
350
- // recentBlockhash: latestBlockhash.blockhash,
351
- // instructions,
352
- // }).compileToV0Message();
353
- // return await this.createSendConfirmRetryTransaction(
354
- // messageV0,
355
- // [senderKeypair],
356
- // connection,
357
- // latestBlockhash,
358
- // senderKeypair,
359
- // instructions
360
- // );
361
- // }
362
- // async SendTransaction(recipientAddress: string, amount: number) {
363
- // /**
364
- // * master wallet sends a transaction to @param recipientAddress of @param amount
365
- // */
366
- // const masterKeyPair = this.masterKeyPair.privateKey;
367
- // return await this.sendTransaction(recipientAddress, amount, masterKeyPair);
368
- // }
369
- // async getAddressWithBalance(addresses: IAddress[], connection: Connection) {
370
- // const rentExemptionThreshold =
371
- // await connection.getMinimumBalanceForRentExemption(0);
372
- // const addressThatHasBalance: IAddress[] = [];
373
- // for (const address of addresses) {
374
- // const senderBalance = await connection.getBalance(
375
- // new PublicKey(address.address)
376
- // );
377
- // if (senderBalance > rentExemptionThreshold) {
378
- // addressThatHasBalance.push(address);
379
- // }
380
- // }
381
- // return addressThatHasBalance;
382
- // }
383
- // async sweepBatchTransaction(
384
- // destinationAddress: string,
385
- // sendersPrivateKeys: Uint8Array[]
386
- // ) {
387
- // const connection: Connection = this.connection;
388
- // const masterKeys = this.masterKeyPair;
389
- // let recipientPublicKey: PublicKey;
390
- // try {
391
- // recipientPublicKey = new PublicKey(destinationAddress);
392
- // } catch (error: unknown) {
393
- // console.error(
394
- // "The recipient address is not a valid public key:",
395
- // masterKeys.publicKey
396
- // );
397
- // throw error;
398
- // }
399
- // const senderKeypairs: Keypair[] = [];
400
- // for (const senderPrivateKey of sendersPrivateKeys) {
401
- // const senderKeypair = Keypair.fromSecretKey(senderPrivateKey);
402
- // senderKeypairs.push(senderKeypair);
403
- // }
404
- // // const GAS_FEE = 5000; // Adjusted gas fee 5005000
405
- // const rentExemptionThreshold =
406
- // await connection.getMinimumBalanceForRentExemption(0);
407
- // // Request a specific compute unit budget
408
- // const modifyComputeUnits = ComputeBudgetProgram.setComputeUnitLimit({
409
- // units: 1500,
410
- // });
411
- // // Set the desired priority fee
412
- // const addPriorityFee = ComputeBudgetProgram.setComputeUnitPrice({
413
- // microLamports: 30000, // Adjusted priority fee 10000000000
414
- // });
415
- // const initialInstructions: TransactionInstruction[] = [
416
- // modifyComputeUnits,
417
- // addPriorityFee,
418
- // ];
419
- // for (const senderKeypair of senderKeypairs) {
420
- // const senderBalance = await connection.getBalance(
421
- // senderKeypair.publicKey
422
- // );
423
- // const amountToSend = senderBalance - rentExemptionThreshold;
424
- // if (amountToSend > 0) {
425
- // const transferInstruction: TransactionInstruction =
426
- // SystemProgram.transfer({
427
- // fromPubkey: senderKeypair.publicKey,
428
- // toPubkey: recipientPublicKey,
429
- // lamports: amountToSend,
430
- // });
431
- // initialInstructions.push(transferInstruction);
432
- // } else {
433
- // console.log(
434
- // `Skipping ${senderKeypair.publicKey.toBase58()} due to insufficient funds after rent exemption`
435
- // );
436
- // }
437
- // }
438
- // if (initialInstructions.length === 2) {
439
- // throw new Error(
440
- // "No valid transfer instructions. Ensure senders have sufficient balances."
441
- // );
442
- // }
443
- // const latestBlockhash = await connection.getLatestBlockhash();
444
- // const masterKeypair = Keypair.fromSecretKey(masterKeys.privateKey);
445
- // senderKeypairs.push(masterKeypair);
446
- // const messageV0 = new TransactionMessage({
447
- // payerKey: masterKeypair.publicKey,
448
- // recentBlockhash: latestBlockhash.blockhash,
449
- // instructions: initialInstructions,
450
- // }).compileToV0Message();
451
- // //create, send, confirm,retry a new trasaction
452
- // await this.createSendConfirmRetryTransaction(
453
- // messageV0,
454
- // senderKeypairs,
455
- // connection,
456
- // latestBlockhash,
457
- // masterKeypair,
458
- // initialInstructions
459
- // );
460
- // }
461
- // async withdrawToMasterAddress(addresses: IAddress[]) {
462
- // /**
463
- // * @param addresses this is the list of All addresses that exist
464
- // */
465
- // const addressThatHasBalance = await this.getAddressWithBalance(
466
- // addresses,
467
- // this.connection
468
- // );
469
- // try {
470
- // const privateKeysOfAddressThatHasBalance =
471
- // this.solGetPrivateKeyFromAddressArray(
472
- // addressThatHasBalance as IAddress[]
473
- // );
474
- // this.sweepBatchTransaction(
475
- // this.masterKeyPair.publicKey.toString(),
476
- // privateKeysOfAddressThatHasBalance
477
- // );
478
- // } catch (error) {
479
- // console.log(
480
- // "error:solGetPrivateKeyFromAddressArray orsweepBatchTransaction ",
481
- // error
482
- // );
483
- // }
484
- // }
485
- // async withdrawToSpecificAddress(addresses: IAddress[], address: string) {
486
- // /**
487
- // * @param addresses this is the list of All addresses that exist
488
- // */
489
- // let addr: PublicKey;
490
- // try {
491
- // addr = new PublicKey(address);
492
- // const addressThatHasBalance = await this.getAddressWithBalance(
493
- // addresses,
494
- // this.connection
495
- // );
496
- // console.log("addressThatHasBalance: ", addressThatHasBalance);
497
- // const privateKeysOfAddressThatHasBalance =
498
- // this.solGetPrivateKeyFromAddressArray(addressThatHasBalance);
499
- // this.sweepBatchTransaction(
500
- // addr.toString(),
501
- // privateKeysOfAddressThatHasBalance
502
- // );
503
- // } catch (error) {
504
- // console.log("error: not a valid address ", error);
505
- // }
506
- // }
507
- // async createSendConfirmRetryTransaction(
508
- // messageV0: MessageV0,
509
- // senderKeypairs: Keypair[],
510
- // connection: Connection,
511
- // latestBlockhash: Readonly<{
512
- // blockhash: string;
513
- // lastValidBlockHeight: number;
514
- // }>,
515
- // feePayerKeypair: Keypair,
516
- // initialInstructions: TransactionInstruction[]
517
- // ) {
518
- // const transaction = new VersionedTransaction(messageV0);
519
- // transaction.sign(senderKeypairs);
520
- // let signature: string;
521
- // let retries = 5;
522
- // let explorerUrl = "";
523
- // while (retries > 0) {
524
- // try {
525
- // console.log("sending transaction...");
526
- // signature = await connection.sendTransaction(transaction, {
527
- // maxRetries: 3,
528
- // });
529
- // const confirmation = await connection.confirmTransaction({
530
- // signature,
531
- // blockhash: latestBlockhash.blockhash,
532
- // lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
533
- // });
534
- // if (confirmation.value.err) {
535
- // console.error("An error occurred:", confirmation.value.err);
536
- // } else {
537
- // explorerUrl = `${this.chain.explorer}/tx/${signature}`;
538
- // console.log("View transaction on explorer:", explorerUrl);
539
- // }
540
- // return { status: true, signature: `${signature}`, explorerUrl };
541
- // break; // If successful, exit the loop
542
- // } catch (error: any) {
543
- // if (error.message.includes("block height exceeded")) {
544
- // retries -= 1;
545
- // if (retries === 0) {
546
- // console.error(
547
- // "Failed to send transaction after multiple retries due to TransactionExpiredBlockheightExceededError:",
548
- // error
549
- // );
550
- // throw error;
551
- // } else {
552
- // console.log(
553
- // "Retrying transaction due to TransactionExpiredBlockheightExceededError: block height exceeded ..."
554
- // );
555
- // // Update latestBlockhash for retry
556
- // latestBlockhash = await connection.getLatestBlockhash();
557
- // const newMessageV0 = new TransactionMessage({
558
- // payerKey: feePayerKeypair.publicKey,
559
- // recentBlockhash: latestBlockhash.blockhash,
560
- // instructions: initialInstructions,
561
- // }).compileToV0Message();
562
- // transaction.signatures = [];
563
- // transaction.message = newMessageV0;
564
- // transaction.sign(senderKeypairs);
565
- // }
566
- // } else {
567
- // console.error("Failed to send transaction:", error);
568
- // throw error;
569
- // }
570
- // }
571
- // }
572
- // }
573
- // async sweepBatchTransactionV2(
574
- // recipientAddress: PublicKeyInitData,
575
- // sendersPrivateKeys: Uint8Array[]
576
- // ) {
577
- // const connection: Connection = this.connection;
578
- // try {
579
- // new PublicKey(recipientAddress);
580
- // } catch (error: any) {
581
- // console.log(
582
- // "the recipientAddress is not a valid public key",
583
- // recipientAddress
584
- // );
585
- // throw new Error(error);
586
- // }
587
- // const GAS_FEE = 5005000;
588
- // // request a specific compute unit budget
589
- // const modifyComputeUnits = ComputeBudgetProgram.setComputeUnitLimit({
590
- // units: 500,
591
- // });
592
- // // set the desired priority fee
593
- // const addPriorityFee = ComputeBudgetProgram.setComputeUnitPrice({
594
- // microLamports: 10000000000,
595
- // });
596
- // const transaction = new Transaction()
597
- // .add(addPriorityFee)
598
- // .add(modifyComputeUnits);
599
- // const AllSenderArrayKeypair: Keypair[] = [];
600
- // for (const sender of sendersPrivateKeys) {
601
- // const senderArrayKeypair = Keypair.fromSecretKey(sender);
602
- // AllSenderArrayKeypair.push(senderArrayKeypair);
603
- // const senderBalance = await connection.getBalance(
604
- // new PublicKey(senderArrayKeypair.publicKey)
605
- // );
606
- // const amountToSend = senderBalance - GAS_FEE;
607
- // console.log("amountToSend: ", amountToSend);
608
- // transaction.add(
609
- // SystemProgram.transfer({
610
- // fromPubkey: senderArrayKeypair.publicKey,
611
- // toPubkey: new PublicKey(recipientAddress),
612
- // lamports: amountToSend,
613
- // })
614
- // );
615
- // }
616
- // console.log("got heereee2");
617
- // const estimatedfees = await transaction.getEstimatedFee(connection);
618
- // console.log("estimatedfees: ", estimatedfees);
619
- // transaction.recentBlockhash = (
620
- // await connection.getLatestBlockhash()
621
- // ).blockhash;
622
- // // Sign transaction, broadcast, and confirm
623
- // const signature = await sendAndConfirmTransaction(
624
- // connection,
625
- // transaction,
626
- // AllSenderArrayKeypair,
627
- // {
628
- // maxRetries: 5,
629
- // }
630
- // );
631
- // console.log("SIGNATURE", signature);
632
- // if (this.isDevnet) {
633
- // console.log(
634
- // "View tx on explorer:",
635
- // `https://explorer.solana.com/tx/${signature}?cluster=devnet`
636
- // );
637
- // } else {
638
- // console.log("View tx on explorer:", `https://solscan.io/tx/${signature}`);
639
- // }
640
- // }
641
- // //INTERNAL
642
- // solGetMasterAddress(): string {
643
- // return this.addressFromSeed(0);
644
- // }
645
- // solGetPrivateKeyFromAddressArray(AddressArray: IAddress[]) {
646
- // const privateKeys = AddressArray.map((address: IAddress) => {
647
- // const privateKey = this.solgetPrivateKeyFromSeed(address.index);
648
- // return privateKey;
649
- // });
650
- // return privateKeys;
651
- // }
652
- // //HELPERS
653
- // solGetMultiplePublicKeyFromSeed(start: number, end: number) {
654
- // const pubkeys: string[] = [];
655
- // for (let i = start; i <= end; i++) {
656
- // const publicKey = this.solGetPublicKeyFromSeed(i);
657
- // pubkeys.push(publicKey);
658
- // }
659
- // return pubkeys;
660
- // }
661
- // addressFromSeedMultiple(start: number, end: number) {
662
- // const addresses: IAddress[] = [];
663
- // for (let i = start; i <= end; i++) {
664
- // const _address = this.addressFromSeed(i);
665
- // const address = {
666
- // address: _address,
667
- // index: i,
668
- // };
669
- // addresses.push(address);
670
- // }
671
- // return addresses;
672
- // }
673
- // addressFromSeed(index: number) {
674
- // //address is same as public key
675
- // return this.solGetPublicKeyFromSeed(index);
676
- // }
677
- // solGetPublicKeyFromSeed(index: number) {
678
- // const keyPair = this.deriveChildPrivateKey(index);
679
- // return keyPair.publicKey;
680
- // }
681
- // solgetPrivateKeyFromSeed(index: number) {
682
- // const keyPair = this.deriveChildPrivateKey(index);
683
- // return keyPair.privateKey;
684
- // }
685
- static GenerateNewSeed() {
686
- const mnemonic = bip39.generateMnemonic(english_1.wordlist);
687
- return mnemonic;
688
- }
689
- solGetKeyPairFromSeed() {
690
- const restoredSeedBuffer = buffer_1.Buffer.from(this.seed, "hex").slice(0, 32);
691
- const seedPhraseKeypair = web3_js_1.Keypair.fromSeed(restoredSeedBuffer);
692
- return seedPhraseKeypair;
693
- }
694
- deriveChildPrivateKey(index) {
695
- const derivedKeyPair = this.deriveChildKeypair(index);
696
- const privateKey = derivedKeyPair.secretKey;
697
- const publicKey = derivedKeyPair.publicKey.toBase58();
698
- return { privateKey, publicKey };
699
- }
700
- deriveChildKeypair(index) {
701
- const path = `m/44'/501'/0'/0'/${index}'`;
702
- // Derive the key for the given path
703
- const derivedSeed = this.derivePath(path, buffer_1.Buffer.from(this.seed));
704
- // Create a Solana keypair from the derived seed
705
- const derivedKeyPair = web3_js_1.Keypair.fromSeed(derivedSeed);
706
- return derivedKeyPair;
707
- }
708
- derivePath(path, seed) {
709
- const segments = path
710
- .split("/")
711
- .slice(1)
712
- .map((seg) => {
713
- if (!seg.endsWith("'")) {
714
- throw new Error("Only hardened derivation is supported");
715
- }
716
- return parseInt(seg.slice(0, -1), 10) + 0x80000000;
717
- });
718
- let derived = seed;
719
- for (const segment of segments) {
720
- derived = this.hardenedDerivation(derived, segment);
721
- }
722
- return derived;
723
- }
724
- hardenedDerivation(parentKey, index) {
725
- const indexBuffer = new Uint8Array(4);
726
- new DataView(indexBuffer.buffer).setUint32(0, index, false);
727
- const hmacResult = (0, hmac_1.hmac)(sha2_1.sha512, parentKey, new Uint8Array([...parentKey, ...indexBuffer]));
728
- return hmacResult.slice(0, 32); // Take the first 32 bytes for the seed
729
- }
730
- }
731
- class SoonClass extends MasterSmartWalletClass {
732
- }
733
- exports.SoonClass = SoonClass;
734
- // const test = async () => {
735
- // const masterClass = new SoonClass();
736
- // const address = masterClass.solGetMasterAddress();
737
- // console.log("address: ", address);
738
- // const balance = await masterClass.getNativeBalance(address);
739
- // console.log("balance: ", balance);
740
- // //now to send transactions
741
- // const wallet1 = masterClass.addressFromSeed(1);
742
- // console.log("wallet1: ", wallet1);
743
- // // we will send sol from master to wallet1
744
- // const res = await masterClass.SendTransaction(wallet1, 0.001);
745
- // console.log("res: ", res);
746
- // //now for spl tokens
2
+ // /* eslint-disable @typescript-eslint/no-explicit-any */
3
+ // import * as bip39 from "@scure/bip39";
4
+ // import { } from "@scure/bip32"
5
+ // import { Buffer } from "buffer"; // Import the polyfill
6
+ // window.Buffer = Buffer; // Inject Buffer into the global scope
7
+ // import CryptoJS from "crypto-js";
8
+ // import { wordlist } from "@scure/bip39/wordlists/english";
9
+ // import { hmac } from "@noble/hashes/hmac";
10
+ // import { sha512 } from "@noble/hashes/sha2";
11
+ // import {
12
+ // Keypair,
13
+ // LAMPORTS_PER_SOL,
14
+ // Connection,
15
+ // PublicKey,
16
+ // TransactionInstruction,
17
+ // SystemProgram,
18
+ // TransactionMessage,
19
+ // VersionedTransaction,
20
+ // Transaction,
21
+ // PublicKeyInitData,
22
+ // sendAndConfirmTransaction,
23
+ // ComputeBudgetProgram,
24
+ // MessageV0,
25
+ // TransactionExpiredBlockheightExceededError,
26
+ // BlockhashWithExpiryBlockHeight,
27
+ // VersionedTransactionResponse,
28
+ // Commitment,
29
+ // } from "@solana/web3.js";
30
+ // // import bs58 from "bs58";
31
+ // // import { Buffer } from "buffer";
32
+ // // import * as ed25519 from "ed25519-hd-key";
33
+ // import promiseRetry from "promise-retry";
34
+ // // import CryptoJS from "crypto-js";
35
+ // import {
36
+ // getAssociatedTokenAddress,
37
+ // getAccount,
38
+ // Account,
39
+ // } from "@solana/spl-token";
40
+ // interface IAddress {
41
+ // address: string;
42
+ // index: number;
43
+ // }
44
+ // export type TransactionSenderAndConfirmationWaiterArgs = {
45
+ // connection: Connection;
46
+ // serializedTransaction: Buffer;
47
+ // blockhashWithExpiryBlockHeight: BlockhashWithExpiryBlockHeight;
747
48
  // };
748
- // export async function transactionSenderAndConfirmationWaiter({
749
- // connection,
750
- // serializedTransaction,
751
- // blockhashWithExpiryBlockHeight,
752
- // }: TransactionSenderAndConfirmationWaiterArgs): Promise<VersionedTransactionResponse | null> {
753
- // const txid = await connection.sendRawTransaction(
754
- // serializedTransaction,
755
- // SEND_OPTIONS
756
- // );
757
- // const controller = new AbortController();
758
- // const abortSignal = controller.signal;
759
- // const abortableResender = async () => {
760
- // while (true) {
761
- // await wait(2_000);
762
- // if (abortSignal.aborted) return;
763
- // try {
764
- // await connection.sendRawTransaction(
765
- // serializedTransaction,
766
- // SEND_OPTIONS
767
- // );
768
- // } catch (e) {
769
- // console.warn(`Failed to resend transaction: ${e}`);
770
- // }
771
- // }
772
- // };
773
- // try {
774
- // abortableResender();
775
- // const lastValidBlockHeight =
776
- // blockhashWithExpiryBlockHeight.lastValidBlockHeight - 150;
777
- // // this would throw TransactionExpiredBlockheightExceededError
778
- // await Promise.race([
779
- // connection.confirmTransaction(
780
- // {
781
- // ...blockhashWithExpiryBlockHeight,
782
- // lastValidBlockHeight,
783
- // signature: txid,
784
- // abortSignal,
785
- // },
786
- // "confirmed"
787
- // ),
788
- // new Promise(async (resolve) => {
789
- // // in case ws socket died
790
- // while (!abortSignal.aborted) {
791
- // await wait(2_000);
792
- // const tx = await connection.getSignatureStatus(txid, {
793
- // searchTransactionHistory: false,
794
- // });
795
- // if (tx?.value?.confirmationStatus === "confirmed") {
796
- // resolve(tx);
797
- // }
798
- // }
799
- // }),
800
- // ]);
801
- // } catch (e) {
802
- // if (e instanceof TransactionExpiredBlockheightExceededError) {
803
- // // we consume this error and getTransaction would return null
49
+ // export interface Chain {
50
+ // name: string;
51
+ // symbol: string;
52
+ // chainDecimals: string;
53
+ // explorer: string;
54
+ // http: string[];
55
+ // ws: string;
56
+ // nativeTokenProfitSpreed: string;
57
+ // chainTokenExplorer: string;
58
+ // isEvm: boolean;
59
+ // isDevnet: boolean;
60
+ // }
61
+ // export const chain: Chain = {
62
+ // name: "SOON TESTNET",
63
+ // symbol: "SOON",
64
+ // chainDecimals: LAMPORTS_PER_SOL.toString(),
65
+ // explorer: "https://explorer.testnet.soo.network",
66
+ // http: ["https://rpc.testnet.soo.network/rpc"],
67
+ // ws: "",
68
+ // nativeTokenProfitSpreed: "0.04",
69
+ // chainTokenExplorer: "https://explorer.testnet.soo.network/",
70
+ // isEvm: false,
71
+ // isDevnet: true,
72
+ // };
73
+ // class MasterSmartWalletClass {
74
+ // // Define the type for the config object
75
+ // chain: Chain;
76
+ // connection: Connection;
77
+ // masterKeyPair: { privateKey: Uint8Array; publicKey: string };
78
+ // isDevnet: boolean = false;
79
+ // seed: string;
80
+ // masterAddress: string;
81
+ // constructor(mnemonic: string, chain: Chain) {
82
+ // const seed = bip39.mnemonicToSeedSync(mnemonic);
83
+ // this.seed = seed.toString();
84
+ // this.chain = chain;
85
+ // const nn = Math.floor(Math.random() * this.chain.http.length);
86
+ // this.connection = new Connection(this.chain.http[nn], "confirmed");
87
+ // this.masterKeyPair = this.deriveChildPrivateKey(0);
88
+ // this.isDevnet = this.chain.isDevnet;
89
+ // this.masterAddress = this.masterKeyPair.publicKey;
90
+ // }
91
+ // // static validateAddress(address: string) {
92
+ // // try {
93
+ // // new PublicKey(address);
94
+ // // return true;
95
+ // // } catch (e) {
96
+ // // console.log("e: ", e);
97
+ // // return false;
98
+ // // }
99
+ // // }
100
+ // // validateAddress(address: string) {
101
+ // // try {
102
+ // // new PublicKey(address);
103
+ // // return true;
104
+ // // } catch (e) {
105
+ // // console.log("e: ", e);
106
+ // // return false;
107
+ // // }
108
+ // // }
109
+ // // static async createSendConfirmRetryDeserializedTransaction(
110
+ // // deserializedBuffer: Buffer,
111
+ // // senderKeypairs: Keypair[],
112
+ // // connection: Connection,
113
+ // // latestBlockhash: Readonly<{
114
+ // // blockhash: string;
115
+ // // lastValidBlockHeight: number;
116
+ // // }>
117
+ // // ) {
118
+ // // let status = false;
119
+ // // const transaction = VersionedTransaction.deserialize(deserializedBuffer);
120
+ // // transaction.sign(senderKeypairs);
121
+ // // const explorerUrl = "";
122
+ // // console.log("sending transaction...");
123
+ // // // We first simulate whether the transaction would be successful
124
+ // // const { value: simulatedTransactionResponse } =
125
+ // // await connection.simulateTransaction(transaction, {
126
+ // // replaceRecentBlockhash: true,
127
+ // // commitment: "processed",
128
+ // // });
129
+ // // const { err, logs } = simulatedTransactionResponse;
130
+ // // if (err) {
131
+ // // // Simulation error, we can check the logs for more details
132
+ // // // If you are getting an invalid account error, make sure that you have the input mint account to actually swap from.
133
+ // // console.error("Simulation Error:");
134
+ // // console.error(err);
135
+ // // console.error(logs);
136
+ // // return { status, error: err };
137
+ // // }
138
+ // // // Execute the transaction
139
+ // // const serializedTransaction = Buffer.from(transaction.serialize());
140
+ // // const blockhash = transaction.message.recentBlockhash;
141
+ // // console.log("blockhash: ", blockhash);
142
+ // // const transactionResponse = await transactionSenderAndConfirmationWaiter({
143
+ // // connection,
144
+ // // serializedTransaction,
145
+ // // blockhashWithExpiryBlockHeight: {
146
+ // // blockhash,
147
+ // // lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
148
+ // // },
149
+ // // });
150
+ // // // If we are not getting a response back, the transaction has not confirmed.
151
+ // // if (!transactionResponse) {
152
+ // // console.error("Transaction not confirmed");
153
+ // // // !WE SHOULD RETRY THE TRANSACTION AGAIN HERE
154
+ // // throw new TransactionNotConfirmedError({});
155
+ // // }
156
+ // // if (transactionResponse.meta?.err) {
157
+ // // console.error(transactionResponse.meta?.err);
158
+ // // }
159
+ // // console.log("View transaction on explorer:", explorerUrl);
160
+ // // status = true;
161
+ // // return { status, signature: transactionResponse.transaction.signatures };
162
+ // // }
163
+ // static generateSalt(): string {
164
+ // return CryptoJS.lib.WordArray.random(16).toString(); // 128-bit salt
165
+ // }
166
+ // static deriveKey(
167
+ // password: string,
168
+ // salt: string,
169
+ // iterations = 10000,
170
+ // keySize = 256 / 32
171
+ // ) {
172
+ // return CryptoJS.PBKDF2(password, CryptoJS.enc.Hex.parse(salt), {
173
+ // keySize: keySize,
174
+ // iterations: iterations,
175
+ // }).toString();
176
+ // }
177
+ // static encryptSeedPhrase(seedPhrase: string, password: string) {
178
+ // const salt = this.generateSalt(); // Generate a unique salt for this encryption
179
+ // const key = this.deriveKey(password, salt); // Derive a key using PBKDF2
180
+ // // Encrypt the seed phrase with AES using the derived key
181
+ // const encrypted = CryptoJS.AES.encrypt(seedPhrase, key).toString();
182
+ // // Return the encrypted data and the salt (needed for decryption)
183
+ // return { encrypted, salt };
184
+ // }
185
+ // static decryptSeedPhrase(
186
+ // encryptedSeedPhrase: string,
187
+ // password: string,
188
+ // salt: string
189
+ // ) {
190
+ // try {
191
+ // const key = this.deriveKey(password, salt); // Derive the key using the same salt
192
+ // const bytes = CryptoJS.AES.decrypt(encryptedSeedPhrase, key);
193
+ // const seedPhrase = bytes.toString(CryptoJS.enc.Utf8);
194
+ // // Check if decryption was successful
195
+ // if (!seedPhrase) throw new Error("Decryption failed.");
196
+ // return seedPhrase;
197
+ // } catch (e: any) {
198
+ // console.error("Invalid password or corrupted data:", e.message);
804
199
  // return null;
805
- // } else {
806
- // // invalid state from web3.js
807
- // throw e;
808
200
  // }
809
- // } finally {
810
- // controller.abort();
811
201
  // }
812
- // // in case rpc is not synced yet, we add some retries
813
- // const response = promiseRetry(
814
- // async (retry: (arg0: null) => void) => {
815
- // const response = await connection.getTransaction(txid, {
816
- // commitment: "confirmed",
817
- // maxSupportedTransactionVersion: 0,
202
+ // // getNativeBalance = async () => {
203
+ // // const connection = new Connection(
204
+ // // this.chain.http[Math.floor(Math.random() * this.chain.http.length)]
205
+ // // );
206
+ // // try {
207
+ // // const publicKey = new PublicKey(this.masterAddress);
208
+ // // const bal = await connection.getBalance(publicKey);
209
+ // // return bal / LAMPORTS_PER_SOL;
210
+ // // } catch (error: any) {
211
+ // // console.log("error: ", error);
212
+ // // console.log("error message: ", error.message);
213
+ // // throw new Error(
214
+ // // `the address passed is not a valid solana address : ${this.masterAddress}`
215
+ // // );
216
+ // // }
217
+ // // };
218
+ // // getTokenBalance = async (token: string) => {
219
+ // // try {
220
+ // // // Get the balance from the token account
221
+ // // const tokenAccount = await this._getTokenAccountAccount(token);
222
+ // // console.log("token: ", token);
223
+ // // const tokenBalance = await this.connection.getTokenAccountBalance(
224
+ // // tokenAccount.address
225
+ // // );
226
+ // // console.log(`User Token Balance: ${tokenBalance.value.uiAmount}`);
227
+ // // //convert tokenBalance bigInt to decimal
228
+ // // const tokenBalanceDecimal = tokenBalance.value.uiAmount;
229
+ // // if (tokenBalanceDecimal == null) {
230
+ // // throw new Error("could not get balance");
231
+ // // }
232
+ // // return tokenBalanceDecimal / LAMPORTS_PER_SOL;
233
+ // // } catch (error) {
234
+ // // console.log("error: ", error);
235
+ // // return 0;
236
+ // // }
237
+ // // };
238
+ // // _getTokenAccountAccount = async (token: string): Promise<Account> => {
239
+ // // try {
240
+ // // // Create PublicKey objects for user and token mint
241
+ // // const userPublicKeyObj = new PublicKey(this.masterAddress);
242
+ // // const tokenMintAddressObj = new PublicKey(token);
243
+ // // // Get the associated token account address for the user and the token mint
244
+ // // const associatedTokenAccount = await getAssociatedTokenAddress(
245
+ // // tokenMintAddressObj, // The token mint address
246
+ // // userPublicKeyObj // The user's public key
247
+ // // );
248
+ // // // Fetch the token account information
249
+ // // const tokenAccount = await getAccount(
250
+ // // this.connection,
251
+ // // associatedTokenAccount
252
+ // // );
253
+ // // return tokenAccount;
254
+ // // } catch (error) {
255
+ // // console.error("Error getting token balance:", error);
256
+ // // throw error;
257
+ // // }
258
+ // // };
259
+ // // async createSendConfirmRetryDeserializedTransaction(
260
+ // // deserializedBuffer: Buffer,
261
+ // // senderKeypairs: Keypair[],
262
+ // // connection: Connection,
263
+ // // latestBlockhash: Readonly<{
264
+ // // blockhash: string;
265
+ // // lastValidBlockHeight: number;
266
+ // // }>
267
+ // // ) {
268
+ // // let status = false;
269
+ // // const transaction = VersionedTransaction.deserialize(deserializedBuffer);
270
+ // // transaction.sign(senderKeypairs);
271
+ // // let explorerUrl = "";
272
+ // // console.log("sending transaction...");
273
+ // // // We first simulate whether the transaction would be successful
274
+ // // const { value: simulatedTransactionResponse } =
275
+ // // await connection.simulateTransaction(transaction, {
276
+ // // replaceRecentBlockhash: true,
277
+ // // commitment: "processed",
278
+ // // });
279
+ // // const { err, logs } = simulatedTransactionResponse;
280
+ // // if (err) {
281
+ // // // Simulation error, we can check the logs for more details
282
+ // // // If you are getting an invalid account error, make sure that you have the input mint account to actually swap from.
283
+ // // console.error("Simulation Error:");
284
+ // // console.error(err);
285
+ // // console.error(logs);
286
+ // // return { status, error: err };
287
+ // // }
288
+ // // // Execute the transaction
289
+ // // const serializedTransaction = Buffer.from(transaction.serialize());
290
+ // // const blockhash = transaction.message.recentBlockhash;
291
+ // // console.log("blockhash: ", blockhash);
292
+ // // const transactionResponse = await transactionSenderAndConfirmationWaiter({
293
+ // // connection,
294
+ // // serializedTransaction,
295
+ // // blockhashWithExpiryBlockHeight: {
296
+ // // blockhash,
297
+ // // lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
298
+ // // },
299
+ // // });
300
+ // // // If we are not getting a response back, the transaction has not confirmed.
301
+ // // if (!transactionResponse) {
302
+ // // console.error("Transaction not confirmed");
303
+ // // //!WE SHOULD RETRY THE TRANSACTION AGAIN HERE
304
+ // // throw new TransactionNotConfirmedError({});
305
+ // // }
306
+ // // if (transactionResponse.meta?.err) {
307
+ // // console.error(transactionResponse.meta?.err);
308
+ // // }
309
+ // // explorerUrl = `${this.chain.explorer}/tx/${transactionResponse.transaction.signatures}`;
310
+ // // console.log("View transaction on explorer:", explorerUrl);
311
+ // // status = true;
312
+ // // return {
313
+ // // signature: `${transactionResponse.transaction.signatures}`,
314
+ // // status,
315
+ // // };
316
+ // // }
317
+ // // async sendTransaction(
318
+ // // recipientAddress: string,
319
+ // // amount: number,
320
+ // // senderSecretKey: Uint8Array
321
+ // // ) {
322
+ // // /**
323
+ // // * internal method for sending sol transaction
324
+ // // */
325
+ // // const connection = this.connection;
326
+ // // const senderKeypair = Keypair.fromSecretKey(senderSecretKey);
327
+ // // try {
328
+ // // new PublicKey(recipientAddress);
329
+ // // } catch (error: any) {
330
+ // // console.log(
331
+ // // "the recipientAddress is not a valid public key",
332
+ // // recipientAddress
333
+ // // );
334
+ // // throw new error();
335
+ // // }
336
+ // // const senderBalance = await connection.getBalance(senderKeypair.publicKey);
337
+ // // console.log("senderBalance: ", senderBalance);
338
+ // // if (senderBalance < amount * LAMPORTS_PER_SOL) {
339
+ // // console.log(
340
+ // // "insufficient funds: sender balance is less than the amount to send"
341
+ // // );
342
+ // // throw new Error(
343
+ // // "insufficient funds: sender balance is less than the amount to send"
344
+ // // );
345
+ // // }
346
+ // // const amountPlusFees = amount * LAMPORTS_PER_SOL + 20045;
347
+ // // if (senderBalance < amountPlusFees) {
348
+ // // console.log(
349
+ // // "insufficient funds + gass : sender balance is less than the amount Plus gass to send"
350
+ // // );
351
+ // // throw new Error(
352
+ // // "insufficient funds + gass : sender balance is less than the amount Plus gass to send"
353
+ // // );
354
+ // // }
355
+ // // // request a specific compute unit budget
356
+ // // const modifyComputeUnits = ComputeBudgetProgram.setComputeUnitLimit({
357
+ // // units: 1500,
358
+ // // });
359
+ // // // set the desired priority fee
360
+ // // const addPriorityFee = ComputeBudgetProgram.setComputeUnitPrice({
361
+ // // microLamports: 30000,
362
+ // // });
363
+ // // const instructions: TransactionInstruction[] = [
364
+ // // addPriorityFee,
365
+ // // modifyComputeUnits,
366
+ // // SystemProgram.transfer({
367
+ // // fromPubkey: senderKeypair.publicKey,
368
+ // // toPubkey: new PublicKey(recipientAddress),
369
+ // // lamports: LAMPORTS_PER_SOL * amount,
370
+ // // }),
371
+ // // ];
372
+ // // const latestBlockhash = await connection.getLatestBlockhash();
373
+ // // const messageV0 = new TransactionMessage({
374
+ // // payerKey: senderKeypair.publicKey,
375
+ // // recentBlockhash: latestBlockhash.blockhash,
376
+ // // instructions,
377
+ // // }).compileToV0Message();
378
+ // // return await this.createSendConfirmRetryTransaction(
379
+ // // messageV0,
380
+ // // [senderKeypair],
381
+ // // connection,
382
+ // // latestBlockhash,
383
+ // // senderKeypair,
384
+ // // instructions
385
+ // // );
386
+ // // }
387
+ // // async SendTransaction(recipientAddress: string, amount: number) {
388
+ // // /**
389
+ // // * master wallet sends a transaction to @param recipientAddress of @param amount
390
+ // // */
391
+ // // const masterKeyPair = this.masterKeyPair.privateKey;
392
+ // // return await this.sendTransaction(recipientAddress, amount, masterKeyPair);
393
+ // // }
394
+ // // async getAddressWithBalance(addresses: IAddress[], connection: Connection) {
395
+ // // const rentExemptionThreshold =
396
+ // // await connection.getMinimumBalanceForRentExemption(0);
397
+ // // const addressThatHasBalance: IAddress[] = [];
398
+ // // for (const address of addresses) {
399
+ // // const senderBalance = await connection.getBalance(
400
+ // // new PublicKey(address.address)
401
+ // // );
402
+ // // if (senderBalance > rentExemptionThreshold) {
403
+ // // addressThatHasBalance.push(address);
404
+ // // }
405
+ // // }
406
+ // // return addressThatHasBalance;
407
+ // // }
408
+ // // async sweepBatchTransaction(
409
+ // // destinationAddress: string,
410
+ // // sendersPrivateKeys: Uint8Array[]
411
+ // // ) {
412
+ // // const connection: Connection = this.connection;
413
+ // // const masterKeys = this.masterKeyPair;
414
+ // // let recipientPublicKey: PublicKey;
415
+ // // try {
416
+ // // recipientPublicKey = new PublicKey(destinationAddress);
417
+ // // } catch (error: unknown) {
418
+ // // console.error(
419
+ // // "The recipient address is not a valid public key:",
420
+ // // masterKeys.publicKey
421
+ // // );
422
+ // // throw error;
423
+ // // }
424
+ // // const senderKeypairs: Keypair[] = [];
425
+ // // for (const senderPrivateKey of sendersPrivateKeys) {
426
+ // // const senderKeypair = Keypair.fromSecretKey(senderPrivateKey);
427
+ // // senderKeypairs.push(senderKeypair);
428
+ // // }
429
+ // // // const GAS_FEE = 5000; // Adjusted gas fee 5005000
430
+ // // const rentExemptionThreshold =
431
+ // // await connection.getMinimumBalanceForRentExemption(0);
432
+ // // // Request a specific compute unit budget
433
+ // // const modifyComputeUnits = ComputeBudgetProgram.setComputeUnitLimit({
434
+ // // units: 1500,
435
+ // // });
436
+ // // // Set the desired priority fee
437
+ // // const addPriorityFee = ComputeBudgetProgram.setComputeUnitPrice({
438
+ // // microLamports: 30000, // Adjusted priority fee 10000000000
439
+ // // });
440
+ // // const initialInstructions: TransactionInstruction[] = [
441
+ // // modifyComputeUnits,
442
+ // // addPriorityFee,
443
+ // // ];
444
+ // // for (const senderKeypair of senderKeypairs) {
445
+ // // const senderBalance = await connection.getBalance(
446
+ // // senderKeypair.publicKey
447
+ // // );
448
+ // // const amountToSend = senderBalance - rentExemptionThreshold;
449
+ // // if (amountToSend > 0) {
450
+ // // const transferInstruction: TransactionInstruction =
451
+ // // SystemProgram.transfer({
452
+ // // fromPubkey: senderKeypair.publicKey,
453
+ // // toPubkey: recipientPublicKey,
454
+ // // lamports: amountToSend,
455
+ // // });
456
+ // // initialInstructions.push(transferInstruction);
457
+ // // } else {
458
+ // // console.log(
459
+ // // `Skipping ${senderKeypair.publicKey.toBase58()} due to insufficient funds after rent exemption`
460
+ // // );
461
+ // // }
462
+ // // }
463
+ // // if (initialInstructions.length === 2) {
464
+ // // throw new Error(
465
+ // // "No valid transfer instructions. Ensure senders have sufficient balances."
466
+ // // );
467
+ // // }
468
+ // // const latestBlockhash = await connection.getLatestBlockhash();
469
+ // // const masterKeypair = Keypair.fromSecretKey(masterKeys.privateKey);
470
+ // // senderKeypairs.push(masterKeypair);
471
+ // // const messageV0 = new TransactionMessage({
472
+ // // payerKey: masterKeypair.publicKey,
473
+ // // recentBlockhash: latestBlockhash.blockhash,
474
+ // // instructions: initialInstructions,
475
+ // // }).compileToV0Message();
476
+ // // //create, send, confirm,retry a new trasaction
477
+ // // await this.createSendConfirmRetryTransaction(
478
+ // // messageV0,
479
+ // // senderKeypairs,
480
+ // // connection,
481
+ // // latestBlockhash,
482
+ // // masterKeypair,
483
+ // // initialInstructions
484
+ // // );
485
+ // // }
486
+ // // async withdrawToMasterAddress(addresses: IAddress[]) {
487
+ // // /**
488
+ // // * @param addresses this is the list of All addresses that exist
489
+ // // */
490
+ // // const addressThatHasBalance = await this.getAddressWithBalance(
491
+ // // addresses,
492
+ // // this.connection
493
+ // // );
494
+ // // try {
495
+ // // const privateKeysOfAddressThatHasBalance =
496
+ // // this.solGetPrivateKeyFromAddressArray(
497
+ // // addressThatHasBalance as IAddress[]
498
+ // // );
499
+ // // this.sweepBatchTransaction(
500
+ // // this.masterKeyPair.publicKey.toString(),
501
+ // // privateKeysOfAddressThatHasBalance
502
+ // // );
503
+ // // } catch (error) {
504
+ // // console.log(
505
+ // // "error:solGetPrivateKeyFromAddressArray orsweepBatchTransaction ",
506
+ // // error
507
+ // // );
508
+ // // }
509
+ // // }
510
+ // // async withdrawToSpecificAddress(addresses: IAddress[], address: string) {
511
+ // // /**
512
+ // // * @param addresses this is the list of All addresses that exist
513
+ // // */
514
+ // // let addr: PublicKey;
515
+ // // try {
516
+ // // addr = new PublicKey(address);
517
+ // // const addressThatHasBalance = await this.getAddressWithBalance(
518
+ // // addresses,
519
+ // // this.connection
520
+ // // );
521
+ // // console.log("addressThatHasBalance: ", addressThatHasBalance);
522
+ // // const privateKeysOfAddressThatHasBalance =
523
+ // // this.solGetPrivateKeyFromAddressArray(addressThatHasBalance);
524
+ // // this.sweepBatchTransaction(
525
+ // // addr.toString(),
526
+ // // privateKeysOfAddressThatHasBalance
527
+ // // );
528
+ // // } catch (error) {
529
+ // // console.log("error: not a valid address ", error);
530
+ // // }
531
+ // // }
532
+ // // async createSendConfirmRetryTransaction(
533
+ // // messageV0: MessageV0,
534
+ // // senderKeypairs: Keypair[],
535
+ // // connection: Connection,
536
+ // // latestBlockhash: Readonly<{
537
+ // // blockhash: string;
538
+ // // lastValidBlockHeight: number;
539
+ // // }>,
540
+ // // feePayerKeypair: Keypair,
541
+ // // initialInstructions: TransactionInstruction[]
542
+ // // ) {
543
+ // // const transaction = new VersionedTransaction(messageV0);
544
+ // // transaction.sign(senderKeypairs);
545
+ // // let signature: string;
546
+ // // let retries = 5;
547
+ // // let explorerUrl = "";
548
+ // // while (retries > 0) {
549
+ // // try {
550
+ // // console.log("sending transaction...");
551
+ // // signature = await connection.sendTransaction(transaction, {
552
+ // // maxRetries: 3,
553
+ // // });
554
+ // // const confirmation = await connection.confirmTransaction({
555
+ // // signature,
556
+ // // blockhash: latestBlockhash.blockhash,
557
+ // // lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
558
+ // // });
559
+ // // if (confirmation.value.err) {
560
+ // // console.error("An error occurred:", confirmation.value.err);
561
+ // // } else {
562
+ // // explorerUrl = `${this.chain.explorer}/tx/${signature}`;
563
+ // // console.log("View transaction on explorer:", explorerUrl);
564
+ // // }
565
+ // // return { status: true, signature: `${signature}`, explorerUrl };
566
+ // // break; // If successful, exit the loop
567
+ // // } catch (error: any) {
568
+ // // if (error.message.includes("block height exceeded")) {
569
+ // // retries -= 1;
570
+ // // if (retries === 0) {
571
+ // // console.error(
572
+ // // "Failed to send transaction after multiple retries due to TransactionExpiredBlockheightExceededError:",
573
+ // // error
574
+ // // );
575
+ // // throw error;
576
+ // // } else {
577
+ // // console.log(
578
+ // // "Retrying transaction due to TransactionExpiredBlockheightExceededError: block height exceeded ..."
579
+ // // );
580
+ // // // Update latestBlockhash for retry
581
+ // // latestBlockhash = await connection.getLatestBlockhash();
582
+ // // const newMessageV0 = new TransactionMessage({
583
+ // // payerKey: feePayerKeypair.publicKey,
584
+ // // recentBlockhash: latestBlockhash.blockhash,
585
+ // // instructions: initialInstructions,
586
+ // // }).compileToV0Message();
587
+ // // transaction.signatures = [];
588
+ // // transaction.message = newMessageV0;
589
+ // // transaction.sign(senderKeypairs);
590
+ // // }
591
+ // // } else {
592
+ // // console.error("Failed to send transaction:", error);
593
+ // // throw error;
594
+ // // }
595
+ // // }
596
+ // // }
597
+ // // }
598
+ // // async sweepBatchTransactionV2(
599
+ // // recipientAddress: PublicKeyInitData,
600
+ // // sendersPrivateKeys: Uint8Array[]
601
+ // // ) {
602
+ // // const connection: Connection = this.connection;
603
+ // // try {
604
+ // // new PublicKey(recipientAddress);
605
+ // // } catch (error: any) {
606
+ // // console.log(
607
+ // // "the recipientAddress is not a valid public key",
608
+ // // recipientAddress
609
+ // // );
610
+ // // throw new Error(error);
611
+ // // }
612
+ // // const GAS_FEE = 5005000;
613
+ // // // request a specific compute unit budget
614
+ // // const modifyComputeUnits = ComputeBudgetProgram.setComputeUnitLimit({
615
+ // // units: 500,
616
+ // // });
617
+ // // // set the desired priority fee
618
+ // // const addPriorityFee = ComputeBudgetProgram.setComputeUnitPrice({
619
+ // // microLamports: 10000000000,
620
+ // // });
621
+ // // const transaction = new Transaction()
622
+ // // .add(addPriorityFee)
623
+ // // .add(modifyComputeUnits);
624
+ // // const AllSenderArrayKeypair: Keypair[] = [];
625
+ // // for (const sender of sendersPrivateKeys) {
626
+ // // const senderArrayKeypair = Keypair.fromSecretKey(sender);
627
+ // // AllSenderArrayKeypair.push(senderArrayKeypair);
628
+ // // const senderBalance = await connection.getBalance(
629
+ // // new PublicKey(senderArrayKeypair.publicKey)
630
+ // // );
631
+ // // const amountToSend = senderBalance - GAS_FEE;
632
+ // // console.log("amountToSend: ", amountToSend);
633
+ // // transaction.add(
634
+ // // SystemProgram.transfer({
635
+ // // fromPubkey: senderArrayKeypair.publicKey,
636
+ // // toPubkey: new PublicKey(recipientAddress),
637
+ // // lamports: amountToSend,
638
+ // // })
639
+ // // );
640
+ // // }
641
+ // // console.log("got heereee2");
642
+ // // const estimatedfees = await transaction.getEstimatedFee(connection);
643
+ // // console.log("estimatedfees: ", estimatedfees);
644
+ // // transaction.recentBlockhash = (
645
+ // // await connection.getLatestBlockhash()
646
+ // // ).blockhash;
647
+ // // // Sign transaction, broadcast, and confirm
648
+ // // const signature = await sendAndConfirmTransaction(
649
+ // // connection,
650
+ // // transaction,
651
+ // // AllSenderArrayKeypair,
652
+ // // {
653
+ // // maxRetries: 5,
654
+ // // }
655
+ // // );
656
+ // // console.log("SIGNATURE", signature);
657
+ // // if (this.isDevnet) {
658
+ // // console.log(
659
+ // // "View tx on explorer:",
660
+ // // `https://explorer.solana.com/tx/${signature}?cluster=devnet`
661
+ // // );
662
+ // // } else {
663
+ // // console.log("View tx on explorer:", `https://solscan.io/tx/${signature}`);
664
+ // // }
665
+ // // }
666
+ // // //INTERNAL
667
+ // // solGetMasterAddress(): string {
668
+ // // return this.addressFromSeed(0);
669
+ // // }
670
+ // // solGetPrivateKeyFromAddressArray(AddressArray: IAddress[]) {
671
+ // // const privateKeys = AddressArray.map((address: IAddress) => {
672
+ // // const privateKey = this.solgetPrivateKeyFromSeed(address.index);
673
+ // // return privateKey;
674
+ // // });
675
+ // // return privateKeys;
676
+ // // }
677
+ // // //HELPERS
678
+ // // solGetMultiplePublicKeyFromSeed(start: number, end: number) {
679
+ // // const pubkeys: string[] = [];
680
+ // // for (let i = start; i <= end; i++) {
681
+ // // const publicKey = this.solGetPublicKeyFromSeed(i);
682
+ // // pubkeys.push(publicKey);
683
+ // // }
684
+ // // return pubkeys;
685
+ // // }
686
+ // // addressFromSeedMultiple(start: number, end: number) {
687
+ // // const addresses: IAddress[] = [];
688
+ // // for (let i = start; i <= end; i++) {
689
+ // // const _address = this.addressFromSeed(i);
690
+ // // const address = {
691
+ // // address: _address,
692
+ // // index: i,
693
+ // // };
694
+ // // addresses.push(address);
695
+ // // }
696
+ // // return addresses;
697
+ // // }
698
+ // // addressFromSeed(index: number) {
699
+ // // //address is same as public key
700
+ // // return this.solGetPublicKeyFromSeed(index);
701
+ // // }
702
+ // // solGetPublicKeyFromSeed(index: number) {
703
+ // // const keyPair = this.deriveChildPrivateKey(index);
704
+ // // return keyPair.publicKey;
705
+ // // }
706
+ // // solgetPrivateKeyFromSeed(index: number) {
707
+ // // const keyPair = this.deriveChildPrivateKey(index);
708
+ // // return keyPair.privateKey;
709
+ // // }
710
+ // static GenerateNewSeed() {
711
+ // const mnemonic = bip39.generateMnemonic(wordlist);
712
+ // return mnemonic;
713
+ // }
714
+ // solGetKeyPairFromSeed() {
715
+ // const restoredSeedBuffer = Buffer.from(this.seed, "hex").slice(0, 32);
716
+ // const seedPhraseKeypair = Keypair.fromSeed(restoredSeedBuffer);
717
+ // return seedPhraseKeypair;
718
+ // }
719
+ // deriveChildPrivateKey(index: number) {
720
+ // const derivedKeyPair = this.deriveChildKeypair(index);
721
+ // const privateKey = derivedKeyPair.secretKey;
722
+ // const publicKey = derivedKeyPair.publicKey.toBase58();
723
+ // return { privateKey, publicKey };
724
+ // }
725
+ // deriveChildKeypair(index: number): Keypair {
726
+ // const path = `m/44'/501'/0'/0'/${index}'`;
727
+ // // Derive the key for the given path
728
+ // const derivedSeed = this.derivePath(path, Buffer.from(this.seed));
729
+ // // Create a Solana keypair from the derived seed
730
+ // const derivedKeyPair = Keypair.fromSeed(derivedSeed);
731
+ // return derivedKeyPair;
732
+ // }
733
+ // private derivePath(path: string, seed: Uint8Array): Uint8Array {
734
+ // const segments = path
735
+ // .split("/")
736
+ // .slice(1)
737
+ // .map((seg) => {
738
+ // if (!seg.endsWith("'")) {
739
+ // throw new Error("Only hardened derivation is supported");
740
+ // }
741
+ // return parseInt(seg.slice(0, -1), 10) + 0x80000000;
818
742
  // });
819
- // if (!response) {
820
- // retry(response);
821
- // }
822
- // return response;
823
- // },
824
- // {
825
- // retries: 7,
826
- // minTimeout: 1e3,
743
+ // let derived = seed;
744
+ // for (const segment of segments) {
745
+ // derived = this.hardenedDerivation(derived, segment);
827
746
  // }
828
- // );
829
- // return response;
830
- // }
831
- // export const wait = (time: number) =>
832
- // new Promise((resolve) => setTimeout(resolve, time));
833
- // const SEND_OPTIONS = {
834
- // skipPreflight: true,
835
- // preflightCommitment: "processed" as Commitment,
836
- // };
837
- // export class TransactionNotConfirmedError extends Error {
838
- // readonly id: string = APPLICATION_ERROR.TRANSACTION_NOT_CONFIRMED_ERROR;
839
- // data: { [key: string]: string } | undefined;
840
- // message = "Transaction not confirmed";
841
- // name = `TransactionNotConfirmedError`;
842
- // statusCode = 500;
843
- // isOperational = true;
844
- // // base constructor only accepts string message as an argument
845
- // // we extend it here to accept an object, allowing us to pass other data
846
- // constructor(data: { [key: string]: string }) {
847
- // super(`Transaction not confirmed: ${JSON.stringify(data)}`);
848
- // this.data = data; // this property is defined in parent
747
+ // return derived;
849
748
  // }
749
+ // private hardenedDerivation(parentKey: Uint8Array, index: number): Uint8Array {
750
+ // const indexBuffer = new Uint8Array(4);
751
+ // new DataView(indexBuffer.buffer).setUint32(0, index, false);
752
+ // const hmacResult = hmac(
753
+ // sha512,
754
+ // parentKey,
755
+ // new Uint8Array([...parentKey, ...indexBuffer])
756
+ // );
757
+ // return hmacResult.slice(0, 32); // Take the first 32 bytes for the seed
758
+ // }
759
+ // // solConvertUint8ArrayToBase58(uint8Array: Uint8Array) {
760
+ // // const base58String = bs58.encode(uint8Array);
761
+ // // return base58String;
762
+ // // }
850
763
  // }
851
- // const APPLICATION_ERROR = {
852
- // TRANSACTION_NOT_CONFIRMED_ERROR: "transaction_not_confirmed",
853
- // };
854
- exports.default = MasterSmartWalletClass;
764
+ // export class SoonClass extends MasterSmartWalletClass { }
765
+ // // const test = async () => {
766
+ // // const masterClass = new SoonClass();
767
+ // // const address = masterClass.solGetMasterAddress();
768
+ // // console.log("address: ", address);
769
+ // // const balance = await masterClass.getNativeBalance(address);
770
+ // // console.log("balance: ", balance);
771
+ // // //now to send transactions
772
+ // // const wallet1 = masterClass.addressFromSeed(1);
773
+ // // console.log("wallet1: ", wallet1);
774
+ // // // we will send sol from master to wallet1
775
+ // // const res = await masterClass.SendTransaction(wallet1, 0.001);
776
+ // // console.log("res: ", res);
777
+ // // //now for spl tokens
778
+ // // };
779
+ // // export async function transactionSenderAndConfirmationWaiter({
780
+ // // connection,
781
+ // // serializedTransaction,
782
+ // // blockhashWithExpiryBlockHeight,
783
+ // // }: TransactionSenderAndConfirmationWaiterArgs): Promise<VersionedTransactionResponse | null> {
784
+ // // const txid = await connection.sendRawTransaction(
785
+ // // serializedTransaction,
786
+ // // SEND_OPTIONS
787
+ // // );
788
+ // // const controller = new AbortController();
789
+ // // const abortSignal = controller.signal;
790
+ // // const abortableResender = async () => {
791
+ // // while (true) {
792
+ // // await wait(2_000);
793
+ // // if (abortSignal.aborted) return;
794
+ // // try {
795
+ // // await connection.sendRawTransaction(
796
+ // // serializedTransaction,
797
+ // // SEND_OPTIONS
798
+ // // );
799
+ // // } catch (e) {
800
+ // // console.warn(`Failed to resend transaction: ${e}`);
801
+ // // }
802
+ // // }
803
+ // // };
804
+ // // try {
805
+ // // abortableResender();
806
+ // // const lastValidBlockHeight =
807
+ // // blockhashWithExpiryBlockHeight.lastValidBlockHeight - 150;
808
+ // // // this would throw TransactionExpiredBlockheightExceededError
809
+ // // await Promise.race([
810
+ // // connection.confirmTransaction(
811
+ // // {
812
+ // // ...blockhashWithExpiryBlockHeight,
813
+ // // lastValidBlockHeight,
814
+ // // signature: txid,
815
+ // // abortSignal,
816
+ // // },
817
+ // // "confirmed"
818
+ // // ),
819
+ // // new Promise(async (resolve) => {
820
+ // // // in case ws socket died
821
+ // // while (!abortSignal.aborted) {
822
+ // // await wait(2_000);
823
+ // // const tx = await connection.getSignatureStatus(txid, {
824
+ // // searchTransactionHistory: false,
825
+ // // });
826
+ // // if (tx?.value?.confirmationStatus === "confirmed") {
827
+ // // resolve(tx);
828
+ // // }
829
+ // // }
830
+ // // }),
831
+ // // ]);
832
+ // // } catch (e) {
833
+ // // if (e instanceof TransactionExpiredBlockheightExceededError) {
834
+ // // // we consume this error and getTransaction would return null
835
+ // // return null;
836
+ // // } else {
837
+ // // // invalid state from web3.js
838
+ // // throw e;
839
+ // // }
840
+ // // } finally {
841
+ // // controller.abort();
842
+ // // }
843
+ // // // in case rpc is not synced yet, we add some retries
844
+ // // const response = promiseRetry(
845
+ // // async (retry: (arg0: null) => void) => {
846
+ // // const response = await connection.getTransaction(txid, {
847
+ // // commitment: "confirmed",
848
+ // // maxSupportedTransactionVersion: 0,
849
+ // // });
850
+ // // if (!response) {
851
+ // // retry(response);
852
+ // // }
853
+ // // return response;
854
+ // // },
855
+ // // {
856
+ // // retries: 7,
857
+ // // minTimeout: 1e3,
858
+ // // }
859
+ // // );
860
+ // // return response;
861
+ // // }
862
+ // // export const wait = (time: number) =>
863
+ // // new Promise((resolve) => setTimeout(resolve, time));
864
+ // // const SEND_OPTIONS = {
865
+ // // skipPreflight: true,
866
+ // // preflightCommitment: "processed" as Commitment,
867
+ // // };
868
+ // // export class TransactionNotConfirmedError extends Error {
869
+ // // readonly id: string = APPLICATION_ERROR.TRANSACTION_NOT_CONFIRMED_ERROR;
870
+ // // data: { [key: string]: string } | undefined;
871
+ // // message = "Transaction not confirmed";
872
+ // // name = `TransactionNotConfirmedError`;
873
+ // // statusCode = 500;
874
+ // // isOperational = true;
875
+ // // // base constructor only accepts string message as an argument
876
+ // // // we extend it here to accept an object, allowing us to pass other data
877
+ // // constructor(data: { [key: string]: string }) {
878
+ // // super(`Transaction not confirmed: ${JSON.stringify(data)}`);
879
+ // // this.data = data; // this property is defined in parent
880
+ // // }
881
+ // // }
882
+ // // const APPLICATION_ERROR = {
883
+ // // TRANSACTION_NOT_CONFIRMED_ERROR: "transaction_not_confirmed",
884
+ // // };
885
+ // export default MasterSmartWalletClass;
855
886
  //# sourceMappingURL=bip32Old.js.map