@deserialize/multi-vm-wallet 1.0.2 → 1.0.4

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