wallet.ts 789 B

12345678910111213141516171819202122
  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. const raw = new Uint8Array(JSON.parse(wallet))
  9. return Keypair.fromSecretKey(raw);
  10. }
  11. // most likely someone pasted mnemonic
  12. if (wallet.split(' ').length > 1) {
  13. const seed = mnemonicToSeedSync(wallet, '');
  14. const path = `m/44'/501'/0'/0'`; // we assume it's first path
  15. return Keypair.fromSeed(derivePath(path, seed.toString('hex')).key);
  16. }
  17. // most likely someone pasted base58 encoded private key
  18. return Keypair.fromSecretKey(bs58.decode(wallet));
  19. }