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