UNPKG

tnb-hd-wallet

Version:

A hd wallet that derives public and private keys from a 12 word mnemonic phrase with support

90 lines (89 loc) 3.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseHdWallet = void 0; const slip0010_1 = require("../slip0010"); const bip39_1 = require("bip39"); const models_1 = require("../models"); const crypto_currencies_1 = require("../crypto-currencies"); class BaseHdWallet { constructor(mnemonicOrSeed, coinDetails, configOptions) { this._addressGapLimit = 20; /** * Takes in an account and address index and returns its derivatiion path * * @param accountIndex The account location for the path * * @param addressIndex The last */ this.getPath = (accountIndex, addressIndex = 0, isInternalChain = false) => { if (this.curve === "ed25519") { return `m/${this.purpose}'/${this.coinType}'/${accountIndex}'/${Number(isInternalChain)}'/${addressIndex}'`; } return `m/${this.purpose}'/${this.coinType}'/${accountIndex}'/${Number(isInternalChain)}/${addressIndex}`; }; if (bip39_1.validateMnemonic(mnemonicOrSeed)) { this.mnemonic = mnemonicOrSeed; this.seed = bip39_1.mnemonicToSeedSync(this.mnemonic).toString("hex"); } else if (mnemonicOrSeed.length >= 32 && mnemonicOrSeed.length <= 128) { this.mnemonic = null; this.seed = mnemonicOrSeed; } else { throw new Error(`Invalid seed: Seed Length has to be between 32 (128 bits) and 128 (516 bits) \nSeed: ${mnemonicOrSeed} \nSeedLength: ${mnemonicOrSeed.length}`); } if (typeof coinDetails === "string") { const crypto = coinDetails; const details = crypto_currencies_1.cryptoCurrencies[crypto]; if (!details) throw new Error(`'${crypto}' is' Not Supported`); this.cryptocurrency = crypto; const { purpose, coinType, curve } = details; this.purpose = purpose; this.coinType = coinType; this.curve = curve; } else { this.cryptocurrency = null; const { purpose, coinType, curve } = coinDetails; this.purpose = purpose; this.coinType = coinType; this.curve = curve; } this.slip10 = new slip0010_1.Slip10Derivation(this.curve, this.seed); this.masterKey = this.slip10.masterKey; this.addressGapLimit = 20; } set addressGapLimit(gapLimit) { if (gapLimit > 0 && gapLimit <= models_1.MAX_ADDRESS_GAP) { this._addressGapLimit = gapLimit; } } get addressGapLimit() { return this._addressGapLimit; } /** * Gets an address object from a specified path * * @param path The derivation path * * @returns an address object containing all the derived keys */ getAddressFromPath(path) { return this.slip10.derivePath(path); } /** * Gets an address object from a specified account and address index * * @param accountIndex * * @param addressIndex * * @returns an address object containing all the derived keys */ getAddress(accountIndex, addressIndex = 0) { const path = this.getPath(accountIndex, addressIndex); return this.getAddressFromPath(path); } } exports.BaseHdWallet = BaseHdWallet;