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