Reputation: 113
I would like to get my ethereum wallet balance so i made an app with web3.js and an ethereum node running with go-ethereum.
I have some ethers on my wallet and the node is synced, but my balance always show 0 ether.
This is my app :
var Web3 = require('web3');
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
balance = web3.eth.getBalance('0x...');
console.log(balance);
The node is started with this command :
geth --rpc --rpccorsdomain "*"
Status of the node with web3.js :
API Version : 0.19.0
Node Version : Geth/v1.7.2-stable-1db4ecdc/darwin-amd64/go1.9.1
Network Version : 1
Ethereum Version : 63
isConnected : true
{host: "http://localhost:8545", timeout: 0}
Listening : true
Peer Count : 25
{currentBlock: 4507134, highestBlock: 4507228, knownStates: 6019923, pulledStates: 6004673, startingBlock: 4506690}
When i fetch a transaction with
web3.eth.getTransaction('0x..')
I can see a transfer of some ethers on my wallet. When i check on etherscan, I still have theses ethers on my wallet, but the balance from web3.js is still returning 0.
When i check the last block :
web3.eth.getBlock("latest").number;
Or with :
web3.eth.blockNumber;
It's returning 0. It doesn't seems normal ?!
Thanks.
Upvotes: 4
Views: 3547
Reputation: 23
This code should work:
await window.ethereum.request({ method: "eth_requestAccounts"}) //open metamask
const web3 = new Web3(window.ethereum);
const accounts = await web3.eth.getAccounts();
const address = (accounts[0]);
const balance = await web3.eth.getBalance(address)
console.log(balance/1000000000000000000)
Upvotes: 0
Reputation: 61
Geth uses "fast" sync by default. So you have to wait until it completely synced the blockchain data to get all the known state entries so it's normal to have to wait a couple of hours longer.
In your example, you can see that the highest block is 4507228 and current block is 4507134.
Which means that the blockchain data is not completelly synced but as I mentioned above this won't be enough for the node to give account balance information or give you the latest block information.
In order to get the updated balance for an account it also needs to sync the state of the blockchain, which is showing to have pulled 6004673 states already but it's still needs to fetch 15250 states to reach the number of known states of 6019923.
This might seem cumbersome but it's still faster than running a "full" sync which would fetch 10x more data, as the big difference is that it saves the state of the blockchain for every single block, while the "fast" sync only saves the latest state, hence why it won't return any values for the web3.eth module.
Upvotes: 6