Ethers.js: How do I connect to Ganache (formerly TestRPC)?

Created on 26 Jul 2018  Â·  3Comments  Â·  Source: ethers-io/ethers.js

Hi,

I am using ethers to connect to local ganache testnet, getting wrong balance.

  getBalance(privateKey) {
    return new Promise((resolve, reject) => {
      if(!privateKey) {
        return reject(new Error('no privateKey'));
      }
      const wallet = new ethers.Wallet(privateKey);
      wallet.provider = ethers.providers.getDefaultProvider(providers.networks.testnet);
      console.log('getting balance');
      let balancePromise = wallet.getBalance(/*address*/);
      balancePromise
                .then(balance => {
                  console.log(`resolve(${balance})`);
                  resolve(balance.toString());
                })
                .catch(err => reject(err));
    });
  }

Running ganache-cli:
ganache-cli -b 3

screen shot 2018-07-26 at 10 53 31 am

Then running this code from post man results to zero balance

screen shot 2018-07-26 at 10 49 56 am

While the true balance showed in MetaMask is 100 eth

screen shot 2018-07-26 at 10 52 39 am

It looks like a bug to me, but I may be missing something or it just maybe ganache-cli issue,
Any Idea?

discussion

Most helpful comment

The default provider for “testnet” is Ropsten, not a local Dev network. You probably want to use new ethers.providers.JsonRpcProvider(“http://localhost:8545”, ethers.networks.unspecified);

If you are using v4 you can just use new ethers.providers.JsonRpcProvider() and it will automatically detect the network.

Let me know if that still doesn’t work for you.

All 3 comments

The default provider for “testnet” is Ropsten, not a local Dev network. You probably want to use new ethers.providers.JsonRpcProvider(“http://localhost:8545”, ethers.networks.unspecified);

If you are using v4 you can just use new ethers.providers.JsonRpcProvider() and it will automatically detect the network.

Let me know if that still doesn’t work for you.

Thanks that's worked using v 4.0

  getBalance(privateKey, address) {
    return new Promise((resolve, reject) => {
      if(!privateKey) {
        return reject(new Error('no privateKey'));
      }
      let provider = new ethers.providers.JsonRpcProvider();
      let balancePromise = provider.getBalance(address);
      balancePromise
                .then(balance => {
                  resolve(ethers.utils.formatEther(balance));
                })
                .catch(err => reject(err));
    });
  }

Sounds like everything is working now, I'm closing this now. If you are still having problems, please feel free to re-open the issue.

Was this page helpful?
0 / 5 - 0 ratings