@deserialize/multi-vm-wallet 1.0.371 → 1.1.0

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