2

I'm stuck between a rock and a hard place right now.

I'm developing an app with react native, and users need to be able to import their wallets via their private keys (and hopefully mnemonic phrases)

However, when I use the eas toolchain to build my app, I run into an issue with the ethers package I was using to do this.

My current code is this:

import * as eth from 'ethers';

export function deriveEthAddressFromPhrase(mnemonic: string): string {
    const wallet = eth.Wallet.fromPhrase(mnemonic);
    return wallet.address;
}

export function deriveEthAddressFromKey(privateKey: string): string {
    const wallet = new eth.Wallet(privateKey.toString().trim());
    return wallet.address;
}

How can I do this without the use of ethers?

1
  • Can you describe what's your problem exactly? The code doesn't work as expected, it doesn't work at all, it does something you don't understand. It is clear what the issue is.
    – Ismael
    Commented Aug 7, 2023 at 1:07

1 Answer 1

0

If you're having trouble with the ethers library, you can also use the web3.js library to accomplish the same thing. Here is how you can modify your code to use web3.js:

First, install the web3 and ethereumjs-wallet packages:

npm install web3 ethereumjs-wallet

Then modify your code

import Web3 from 'web3';
import { fromPrivateKey, fromMnemonic } from 'ethereumjs-wallet';

export function deriveEthAddressFromPhrase(mnemonic: string): string {
    const hdwallet = fromMnemonic(mnemonic);
    const wallet = hdwallet.getWallet();
    return '0x' + wallet.getAddress().toString('hex');
}

export function deriveEthAddressFromKey(privateKey: string): string {
    const wallet = fromPrivateKey(Buffer.from(privateKey, 'hex'));
    return '0x' + wallet.getAddress().toString('hex');
}

Here, fromMnemonic function generates an Ethereum wallet from a mnemonic phrase, and fromPrivateKey generates an Ethereum wallet from a private key. Both functions return a Wallet object, from which you can get the address.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.