diff --git a/utils.ts b/utils.ts index 83e7822..ad5f4fb 100644 --- a/utils.ts +++ b/utils.ts @@ -124,36 +124,70 @@ const addAccount = async (network: string): Promise => { indices, ); - return { pubKey, address, id, hdPath: hdPath }; + return { id, pubKey, address, hdPath }; } catch (error) { console.error('Error creating account:', error); } }; -const accountFromHDPath = async ( +const createAccountFromHDPath = async ( + hdPath: string, +): Promise<{ pubKey: string; address: string } | undefined> => { + try { + const account = await accountInfoFromHDPath(hdPath); + if (!account) throw new Error('Error while creating account'); + + const { privKey, pubKey, address } = account; + + const parts = hdPath.split('/'); + const id = parts[5]; + const coinType = parts[2]; + const path = parts.slice(-3).join('/'); + + const accountInfo = `${path},${privKey}`; + + switch (coinType) { + case '60': + await setInternetCredentials( + `Eth:keyServer:${id}`, + `Eth:key:${id}`, + accountInfo, + ); + break; + case '118': + await setInternetCredentials( + `Cosmos:keyServer${id}`, + `Cosmos:key:${id}`, + accountInfo, + ); + break; + } + + return { pubKey, address }; + } catch (error) { + console.error('Error creating account:', error); + return undefined; + } +}; + +const accountInfoFromHDPath = async ( hdPath: string, ): Promise< - | { - pubKey: string; - address: string; - } - | undefined + { privKey: string; pubKey: string; address: string } | undefined > => { try { const mnemonicStore = await getInternetCredentials('mnemonicServer'); - if (!mnemonicStore) { - throw new Error('Mnemonic not found!'); - } + if (!mnemonicStore) throw new Error('Mnemonic not found!'); const mnemonic = mnemonicStore.password; const hdNode = HDNode.fromMnemonic(mnemonic); - const node = hdNode.derivePath(hdPath); + const privKey = node.privateKey; const pubKey = node.publicKey; const address = node.address; - return { pubKey, address }; + return { privKey, pubKey, address }; } catch (error) { console.error('Error creating account:', error); return undefined; @@ -288,5 +322,6 @@ export { addAccount, signMessage, resetWallet, - accountFromHDPath, + accountInfoFromHDPath, + createAccountFromHDPath, };