Search code examples
ethereumsolidityweb3js

web3 balanceOf always 0


I'm trying to get the balance of an address on my smart contract using web3, but the balance is always 0. Using metamask on Rinkeby since my contract is deployed on rinkeby. https://rinkeby.etherscan.io/address/0x8e3a88be716ce7c8119c36558ec97bc634592255

You can verify the wallet has a balance by putting it in the balanceOf function on etherScan. Use the address 0x8b54A82a12bD5A7bA33B4842cA677E55f78a8612

let provider = web3.currentProvider;
web3 = new Web3(provider);
let abi = 'too long of a string to post here';
let MyContract = web3.eth.contract(JSON.parse(abi));
let myContractInstance = MyContract.at('0x8e3a88be716ce7c8119c36558ec97bc634592255');
let address = '0x8b54A82a12bD5A7bA33B4842cA677E55f78a8612';

function balanceOf(address) {
    if (!address) {
        return;
    }

    this.myContractInstance.balanceOf.call(address, function(error, balance) {
      if (error) {
        return;
      }

      alert(balance.c[0] + ' RHC');
    });
}

balanceOf(address);

Here is the getBalance function on my contract

function balanceOf(address _owner) public view returns (uint256 balance) {
    return balances[_owner];
}

Website implemented on http://robinhoodcoin.net/metamask.html

Code https://github.com/robinhoodcoin/robinhoodcoin.github.io/blob/master/metamask.html

When I change the provider to be the following:

var web3 = new Web3(new Web3.providers.HttpProvider('https://rinkeby.infura.io/'));

I am able to get the balance. SO there is something up with using metamask as the provider.


Solution

  • The line at https://github.com/robinhoodcoin/robinhoodcoin.github.io/blob/master/metamask.html#L118 has a typo. It reads:

    self.myContractInstance = self.MyContract.at(self.address);
    

    but the address is stored at self.contractAddress, so it should read:

    self.myContractInstance = self.MyContract.at(self.contractAddress);
    

    After making that fix, the page works fine for me with MetaMask.