wallet.ts 753 B

123456789101112131415161718192021
  1. import { Keypair } from '@solana/web3.js';
  2. import bs58 from 'bs58';
  3. import { mnemonicToSeedSync } from 'bip39';
  4. import { derivePath } from 'ed25519-hd-key';
  5. export function getWallet(wallet: string): Keypair {
  6. // most likely someone pasted the private key in binary format
  7. if (wallet.startsWith('[')) {
  8. return Keypair.fromSecretKey(JSON.parse(wallet));
  9. }
  10. // most likely someone pasted mnemonic
  11. if (wallet.split(' ').length > 1) {
  12. const seed = mnemonicToSeedSync(wallet, '');
  13. const path = `m/44'/501'/0'/0'`; // we assume it's first path
  14. return Keypair.fromSeed(derivePath(path, seed.toString('hex')).key);
  15. }
  16. // most likely someone pasted base58 encoded private key
  17. return Keypair.fromSecretKey(bs58.decode(wallet));
  18. }