accounts.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { byteArray2hexStr } from './bytes.js';
  2. import { getBase58CheckAddress, genPriKey, getAddressFromPriKey, getPubKeyFromPriKey, pkToAddress } from './crypto.js';
  3. import { ethersHDNodeWallet, Mnemonic } from './ethersUtils.js';
  4. import { TRON_BIP39_PATH_INDEX_0 } from './address.js';
  5. const INVALID_TRON_PATH_ERROR_MSG = 'Invalid tron path provided';
  6. export function generateAccount() {
  7. const priKeyBytes = genPriKey();
  8. const pubKeyBytes = getPubKeyFromPriKey(priKeyBytes);
  9. const addressBytes = getAddressFromPriKey(priKeyBytes);
  10. const privateKey = byteArray2hexStr(priKeyBytes);
  11. const publicKey = byteArray2hexStr(pubKeyBytes);
  12. return {
  13. privateKey,
  14. publicKey,
  15. address: {
  16. base58: getBase58CheckAddress(addressBytes),
  17. hex: byteArray2hexStr(addressBytes),
  18. },
  19. };
  20. }
  21. export function generateRandom(password = '', path = TRON_BIP39_PATH_INDEX_0, wordlist) {
  22. const account = ethersHDNodeWallet.createRandom(password, path, wordlist);
  23. const result = {
  24. mnemonic: account.mnemonic,
  25. privateKey: account.privateKey,
  26. publicKey: account.signingKey.publicKey,
  27. address: pkToAddress(account.privateKey.replace(/^0x/, '')),
  28. path: account.path,
  29. };
  30. return result;
  31. }
  32. export function generateAccountWithMnemonic(mnemonic, path = TRON_BIP39_PATH_INDEX_0, password = '', wordlist = null) {
  33. // eslint-disable-next-line no-useless-escape
  34. if (!String(path).match(/^m\/44\'\/195\'/)) {
  35. throw new Error(INVALID_TRON_PATH_ERROR_MSG);
  36. }
  37. const account = ethersHDNodeWallet.fromMnemonic(Mnemonic.fromPhrase(mnemonic, password, wordlist), path);
  38. const result = {
  39. mnemonic: account.mnemonic,
  40. privateKey: account.privateKey,
  41. publicKey: account.signingKey.publicKey,
  42. address: pkToAddress(account.privateKey.replace(/^0x/, '')),
  43. };
  44. return result;
  45. }
  46. //# sourceMappingURL=accounts.js.map