bip39#generateMnemonic TypeScript Examples

The following examples show how to use bip39#generateMnemonic. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: walletGenerator.ts    From core with MIT License 6 votes vote down vote up
/**
   * Generates a string containing the 12 words used as a mnemonic
   * to create the private and public wallet keys.
   *
   * @static
   * @param {number} [size=128] Or use 256 for 24 words
   * @return {string} The mnemonic
   * @memberof WalletGenerator
   */
  static generateMnemonic(size = 128): string {
    return generateMnemonic(size);
  }
Example #2
Source File: flow.sdk.wallet.ts    From tatum-js with MIT License 6 votes vote down vote up
flowWallet = () => {
  return {
    generateAddressFromXPub: (xpub: string, i: number): string => {
      const w = fromBase58(xpub).derivePath(String(i))
      const s = new elliptic.ec('secp256k1').keyFromPublic(w.publicKey).getPublic().encode('hex', false)
      return s.slice(2)
    },
    generateAddressFromPrivateKey: (privateKey: string): string => {
      const s = new elliptic.ec('secp256k1').keyFromPrivate(privateKey).getPublic().encode('hex', false)
      return s.slice(2)
    },
    generateWallet: async (mnemonic?: string) => {
      mnemonic ||= generateMnemonic(256)
      const hdwallet = hdkey.fromMasterSeed(await mnemonicToSeed(mnemonic))
      return {
        mnemonic,
        xpub: hdwallet.derive(DERIVATION_PATH.FLOW).toJSON().xpub,
      }
    },
    generatePrivateKeyFromMnemonic: async (mnemonic: string, i: number) => {
      const key = fromSeed(await mnemonicToSeed(mnemonic))
        .derivePath(DERIVATION_PATH.FLOW)
        .derive(i).privateKey
      if (!key) throw new Error('No key generated')
      return new elliptic.ec('secp256k1').keyFromPrivate(key).getPrivate().toString(16)
    },
  }
}
Example #3
Source File: solana.wallet.ts    From tatum-js with MIT License 6 votes vote down vote up
solanaWallet = () => {
  return {
    wallet: (privateKey?: string): { mnemonic?: string; privateKey: string; address: string } => {
      const mnemonic = generateMnemonic(256)
      let keypair
      if (privateKey) {
        keypair = Keypair.fromSecretKey(
          privateKey.length === 128 ? Buffer.from(privateKey, 'hex') : decode(privateKey),
        )
      } else {
        return { mnemonic, ...generateAddressFromMnemonic(mnemonic, 0) }
      }
      return { address: keypair.publicKey.toBase58(), privateKey: encode(keypair.secretKey) }
    },
    generateAddressFromMnemonic,
  }
}
Example #4
Source File: btc-based.wallet.utils.ts    From tatum-js with MIT License 6 votes vote down vote up
btcBasedWalletUtils = {
  generateAddressFromXPub: (
    blockchain: BtcBasedBlockchain,
    xpub: string,
    i: number,
    options?: { testnet: boolean },
  ): string => {
    const network = blockchainUtils.getNetworkConfig(blockchain, options)
    const w = fromBase58(xpub, network).derivePath(String(i))
    return payments.p2pkh({ pubkey: w.publicKey, network }).address as string
  },
  generatePrivateKeyFromMnemonic: async (
    blockchain: BtcBasedBlockchain,
    mnemonic: string,
    i: number,
    options?: { testnet: boolean },
  ): Promise<string> => {
    const derivationPath = blockchainUtils.getDerivationPath(blockchain, options)
    const network = blockchainUtils.getNetworkConfig(blockchain, options)
    return fromSeed(await mnemonicToSeed(mnemonic), network)
      .derivePath(derivationPath)
      .derive(i)
      .toWIF()
  },
  generateAddressFromPrivateKey: (
    blockchain: BtcBasedBlockchain,
    privateKey: string,
    options?: { testnet: boolean },
  ): string => {
    const network = blockchainUtils.getNetworkConfig(blockchain, options)
    const keyPair = ECPair.fromWIF(privateKey, network)
    return payments.p2pkh({ pubkey: keyPair.publicKey, network }).address as string
  },
  async generateBlockchainWallet(
    blockchain: BtcBasedBlockchain,
    mnemonic?: string,
    options?: { testnet: boolean },
  ): Promise<TronWallet> {
    const derivationPath = blockchainUtils.getDerivationPath(blockchain, options)
    const mnem = mnemonic ?? generateMnemonic(256)
    const hdwallet = hdkey.fromMasterSeed(
      await mnemonicToSeed(mnem),
      blockchainUtils.getNetworkConfig(blockchain, options).bip32,
    )
    return {
      mnemonic: mnem,
      xpub: hdwallet.derive(derivationPath).toJSON().xpub,
    }
  },
}
Example #5
Source File: evm-based.utils.ts    From tatum-js with MIT License 6 votes vote down vote up
evmBasedUtils = {
  generateAddressFromXPub: (xpub: string, i: number): string => {
    const w = ethHdKey.fromExtendedKey(xpub)
    const wallet = w.deriveChild(i).getWallet()
    return ADDRESS_PREFIX.EVM + wallet.getAddress().toString('hex').toLowerCase()
  },
  generatePrivateKeyFromMnemonic: async (
    blockchain: EvmBasedBlockchain,
    mnemonic: string,
    i: number,
    options?: { testnet: boolean },
  ): Promise<string> => {
    const derivationPath = getDerivationPath(blockchain, options)
    const hdwallet = ethHdKey.fromMasterSeed(await mnemonicToSeed(mnemonic))
    const derivePath = hdwallet.derivePath(derivationPath).deriveChild(i)
    return derivePath.getWallet().getPrivateKeyString()
  },
  generateAddressFromPrivateKey: (blockchain: EvmBasedBlockchain, privateKey: string): string => {
    const wallet = ethWallet.fromPrivateKey(Buffer.from(privateKey.replace(ADDRESS_PREFIX.EVM, ''), 'hex'))
    return wallet.getAddressString() as string
  },
  generateBlockchainWallet: async (
    blockchain: EvmBasedBlockchain,
    mnemonic?: string,
    options?: { testnet: boolean },
  ): Promise<TronWallet> => {
    const mnem = mnemonic ?? generateMnemonic(256)
    const derivationPath = getDerivationPath(blockchain, options)
    const hdwallet = ethHdKey.fromMasterSeed(await mnemonicToSeed(mnem))
    const derivePath = hdwallet.derivePath(derivationPath)
    return {
      xpub: derivePath.publicExtendedKey().toString(),
      mnemonic: mnem,
    }
  },
  prepareSignedTransactionAbstraction: async (
    client: Web3,
    transaction: TransactionConfig,
    web3: EvmBasedWeb3,
    signatureId?: string,
    fromPrivateKey?: string,
    gasLimit?: string,
    gasPrice?: string,
  ) => {
    const gasPriceDefined = gasPrice ? client.utils.toWei(gasPrice, 'gwei') : await web3.getGasPriceInWei()
    const tx = {
      ...transaction,
      gasPrice: gasPriceDefined,
    }

    tx.gas = gasLimit ?? (await client.eth.estimateGas(tx))

    if (signatureId) {
      return JSON.stringify(tx)
    }

    if (!fromPrivateKey) {
      throw new Error('signatureId or fromPrivateKey has to be defined')
    }

    tx.from = tx.from || client.eth.defaultAccount || 0
    const signedTransaction = await client.eth.accounts.signTransaction(tx, fromPrivateKey)

    if (!signedTransaction.rawTransaction) {
      throw new Error('Unable to get signed tx data')
    }

    return signedTransaction.rawTransaction
  },

  transformAmount: (amount: string, unit = 'ether') => {
    return toWei(amount, unit as Unit)
  },

  decimals: async (contractAddress: string, web3: EvmBasedWeb3, provider?: string) => {
    const client = web3.getClient(provider)

    return new client.eth.Contract(Erc20Token.abi as any, contractAddress).methods.decimals().call()
  },
}
Example #6
Source File: multisig.identity.test.ts    From ldk with MIT License 6 votes vote down vote up
validOpts: IdentityOpts<MultisigOpts> = {
  chain: 'regtest',
  type: IdentityType.Multisig,
  ecclib: ecc,
  opts: {
    signer: {
      mnemonic: generateMnemonic(),
      baseDerivationPath: DEFAULT_BASE_DERIVATION_PATH,
    }, // 1 signer
    cosigners: cosigners.map(m => m.getXPub()), // 2 co signers
    requiredSignatures: 2, // need 2 signatures among 3 pubkeys
  },
}
Example #7
Source File: multisig.identity.test.ts    From ldk with MIT License 6 votes vote down vote up
invalidOpts: IdentityOpts<MultisigOpts> = {
  ...validOpts,
  opts: {
    signer: {
      mnemonic: generateMnemonic(),
      baseDerivationPath: DEFAULT_BASE_DERIVATION_PATH,
    }, // 1 signer
    cosigners: cosigners.map(m => m.getXPub()),
    requiredSignatures: 10000000,
  },
}
Example #8
Source File: index.tsx    From marina with MIT License 6 votes vote down vote up
WalletCreate: React.FC = () => {
  const dispatch = useDispatch<ProxyStoreDispatch>();
  const history = useHistory();

  const onSubmit = async ({
    password,
    makeSecurityAccount,
  }: {
    password: string;
    makeSecurityAccount: boolean;
  }) => {
    await dispatch(
      setPasswordAndOnboardingMnemonic(password, generateMnemonic(), makeSecurityAccount)
    );
    history.push(INITIALIZE_SEED_PHRASE_ROUTE);
  };

  return (
    <Shell className="space-y-10">
      <h1 className="mb-5 text-3xl font-medium">Create password</h1>
      <OnboardingForm onSubmit={onSubmit} />
    </Shell>
  );
}
Example #9
Source File: test.utils.ts    From marina with MIT License 6 votes vote down vote up
export function makeRandomMnemonic(): Mnemonic {
  const mnemo = generateMnemonic();
  return new Mnemonic({ type: IdentityType.Mnemonic, chain: 'regtest', opts: { mnemonic: mnemo } });
}
Example #10
Source File: mnemonic-phrase.service.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
generateMnemonicPhrase(): string {
    return generateMnemonic(256);
  }
Example #11
Source File: moon-key.ts    From moonbeam with GNU General Public License v3.0 5 votes vote down vote up
mnemonic = argv["mnemonic"] || generateMnemonic(strength)
Example #12
Source File: egld.wallet.ts    From tatum-js with MIT License 5 votes vote down vote up
egldWallet = () => {
  return {
    /**
     * Generate EGLD wallet
     * @param mnem mnemonic seed to use
     * @returns wallet
     */
    generateBlockchainWallet: async (mnem: string): Promise<Wallet> => {
      return {
        mnemonic: mnem,
        xpub: '',
      }
    },
    /**
     * Generate wallet
     * @param mnemonic optional mnemonic seed to use. If not present, new one will be generated
     * @returns wallet or a combination of address and private key
     */
    generateWallet: (mnemonic?: string) => {
      mnemonic ||= generateMnemonic(256)
      return ApiServices.blockchain.elgo.egldGenerateWallet(mnemonic)
    },

    /**
     * Generate private key from mnemonic seed
     * @param testnet testnet or mainnet version of address
     * @param mnemonic mnemonic to generate private key from
     * @param i derivation index of private key to generate.
     * @returns blockchain private key to the address
     */
    generatePrivateKeyFromMnemonic: (testnet: boolean, mnemonic: string, i: number) => {
      return generatePrivateKey(testnet, mnemonic, i)
    },

    /**
     * Generate address from private key
     * @param privateKey private key to use
     * @returns blockchain private key to the address
     */
    generateAddress: async (testnet: boolean, mnemonic: string, i: number) => {
      const privateKey = await generatePrivateKey(testnet, mnemonic, i)
      return convertPrivateKey(privateKey)
    },
  }
}
Example #13
Source File: tron.wallet.ts    From tatum-js with MIT License 5 votes vote down vote up
tronWallet = (args: { tronWeb: ITronWeb }) => {
  return {
    /**
     * Generate Tron wallet
     * @returns mnemonic for the wallet
     */
    generateBlockchainWallet,
    /**
     * Generate wallet
     * @param mnemonic optional mnemonic seed to use. If not present, new one will be generated
     * @returns wallet or a combination of address and private key
     */
    async generateWallet(mnemonic?: string): Promise<TronWallet> {
      return generateBlockchainWallet(mnemonic ?? generateMnemonic(256))
    },
    /**
     * Generate address
     * @param xpub extended public key to generate address from
     * @param i derivation index of address to generate. Up to 2^31 addresses can be generated.
     * @returns blockchain address
     */
    generateAddressFromXPub(xpub: string, i: number): string {
      const w = fromPublicKey(Buffer.from(xpub.slice(0, 66), 'hex'), Buffer.from(xpub.slice(-64), 'hex'))
      return TronWeb.address.fromHex(generateAddress(w.derive(i).publicKey))
    },
    /**
     * Generate private key from mnemonic seed
     * @param mnemonic mnemonic to generate private key from
     * @param i derivation index of private key to generate.
     * @returns blockchain private key to the address
     */
    async generatePrivateKeyFromMnemonic(mnemonic: string, i: number): Promise<string> {
      return (
        fromSeed(await mnemonicToSeed(mnemonic))
          .derivePath(DERIVATION_PATH[Blockchain.TRON])
          .derive(i)
          .privateKey?.toString('hex') ?? ''
      )
    },
    /**
     * Generate address from private key
     * @param privateKey private key to use
     * @returns blockchain private key to the address
     */
    generateAddressFromPrivatekey(privateKey: string): string {
      return TronWeb.address.fromPrivateKey(privateKey)
    },
    custodial: tronCustodial(args),
  }
}