Search code examples
node.jsweb3js

How to import ethereum account in web3 if I know address and private key?


I start ganache-gui and see lot of accounts, they have private keys and mnemonic phrase. Then I connect to this testnet with nodejs and web3 1.x.x, so my wallet.length is 0. I want to import all wallet from ganache by mnemonic phrase or better import one address using private key. Could I do this? I tried web3.eth.accounts.privateKeyToAccount(privateKey); but returns new account. How does it work? Metamask can do this just by privateKey.


Solution

  • To access the ganache accounts, you have to do the following:

        const ganache = require('ganache-cli');
        const Web3 = require('web3');
    
       //ganache client running on port 7545
        var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
    
        const getAccounts = async () =>{
    
       //To get all accounts
        let accounts = await web3.eth.getAccounts();
    
        //To get accounts with private key
        let account = await web3.eth.accounts.privateKeyToAccount('0x'+privateKey);
        //privateKey is the key that you get from Ganache client
        }
    
        getAccounts();