Create a function to add eth or cosmos account from hd path

This commit is contained in:
IshaVenikar 2024-02-19 17:43:34 +05:30
parent 49613ef52f
commit 25f9243d85

View File

@ -124,36 +124,70 @@ const addAccount = async (network: string): Promise<Account | undefined> => {
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,
};