Search code examples
solidityweb3js

How to get web3 accounts in solc?


My blockchain project with solc version ^0.4.6 . Has been throwing errors when given the command of being web3.eth.accounts.

web3.eth.accounts

Uncaught Error: Invalid JSON RPC response: undefined at Object.InvalidResponse (E:\techdot-master\node_modules\web3\lib\web3\errors.js:38:16) at HttpProvider.send (E:\techdot-master\node_modules\web3\lib\web3\httpprovider.js:91:22) at RequestManager.send (E:\techdot-master\node_modules\web3\lib\web3\requestmanager.js:58:32) at Eth.get [as accounts] (E:\techdot-master\node_modules\web3\lib\web3\property.js:107:62).

I have tried reading the docs and tried other commands. Still unable to resolve the issue!


Solution

  • "Invalid JSON RPC response" means you are not connected to the node. In order to connect to a node, you need a provider. You can get an infura account and create a provider HdWalletProvider

    const HDWalletProvider = require("@truffle/hdwallet-provider");
    const provider = new HDWalletProvider({
      mnemonic: {
        phrase: metamask_mnemonic, 
      },
      providerOrUrl: ropsten_network,//infura endpoint here
    });
    

    Or if you are using ganache-cli

    const ganache = require('ganache-cli');
    const provider = ganache.provider()
    

    Then create web3

       const web3 = new Web3(provider);
    

    I think instead of accounts, should be getAccounts

       const accounts = await web3.eth.getAccounts();