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

Then running this code from post man results to zero balance

While the true balance showed in MetaMask is 100 eth

It looks like a bug to me, but I may be missing something or it just maybe ganache-cli issue,
Any Idea?
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.
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.