import { EthereumHDKey, fromMasterSeed, Wallet } from "ethereumjs-wallet/hdkey"; import {mnemonicToSeedSync} from "bip39"; import {ConfigurationService} from "./ConfigurationService"; import {WalletCacheService} from "./WalletCacheService"; import {injectable} from "tsyringe"; import {ReflauntWallet} from "../../models/ReflauntWallet"; @injectable() export class HdWalletService { maxWallet: number = 2000000000; hdKey: EthereumHDKey; walletCache: WalletCacheService; constructor(configurationService: ConfigurationService, walletCacheService: WalletCacheService) { const mnemonic = configurationService.config.mnemonic; this.hdKey = fromMasterSeed(mnemonicToSeedSync(mnemonic)); this.walletCache = walletCacheService; } getWalletPath(id: number) { const accountNo = Math.floor(id / this.maxWallet); const indexNo = id - (this.maxWallet * accountNo); return `m/44'/60'/${accountNo}'/0/${indexNo}`; } generateWallet(id: number) { const wallet: Wallet = this.hdKey.derivePath(this.getWalletPath(id)).getWallet(); this.walletCache.cache(new ReflauntWallet({ id, address: '0x' + wallet.getAddress().toString('hex'), wallet })) } getWallet(id: number) { if (!this.walletCache.isExist(id)) { this.generateWallet(id); } return this.walletCache.get(id); } }