2

I have a function in a contract to retrieve ETH balance for a given address, which is:

function getEthBalance(address _addr) constant public returns(uint) {
      return _addr.balance;
}

Is there a way to retrieve token balance of the contract for a given address, just like the function above?

EDIT: Let's suppose the contract issues a token named TKN, and I have 10 TKN in my ETH address, is there a way to retrieve the balance of those 10 TKN in my address with a function? Something like:

function getTKNBalance(address _addr) constant public returns(uint) {
      return _addr.TKN.balance; 
}

2 Answers 2

2

Yes, it's totally doable. Assuming the token its ERC20 and you know the address you can do the following:

pragma solidity ^0.4.9;

contract ERC20 { // This doesn't have to match the real contract name. Call it what you like.
   function tokenExchangeRate() returns(uint); // No implementation, just the function signature. This is just so Solidity can work out how to call it.
}

contract TokenBalance {

    function getBalance(address tokenAddress) view returns (uint){

        ERC20 t = ERC20(tokenAddress); // BAT's is 0x0D8775F648430679A709E98d2b0Cb6250d2887EF
        uint bal = t.tokenExchangeRate();

        return bal;
    }
}

In this case I'm actually retrieving BAT's token exchange rate, but the same logic applies to calling any other function.

You just need need to create a contract that contains the function signature you will want to call from the main contract. Then, in your main contract you can instantiate the contract with the actual token address and call the functions you specified in the interface.

To retrieve the token balance of any given account you eould have to call the token's balanceOf(address) function. https://theethereum.wiki/w/index.php/ERC20_Token_Standard

0
0

No, retrieving of a token balance of the contract for a given address is not possible from your contract.

return _addr.balance; retrieves actual ether balance of the address. If you pass contract address you will get ether balance of the contract.

The token contract needs to voluntarily expose a function that returns the balance of the token is the only way to get token balance.

1
  • Thank you for your reply. Maybe I asked in a wrong way. I didn't mean to get the token balance of the contract itself, but the token balance of an account who already has the token. Suppose the contract issues a token named TKN, and I have 10 TKN in my ETH address, is there a way to retrieve the balance of those TKN in my address with a function? Something like: function getTKNBalance(address _addr) constant public returns(uint) {return _addr.TKN.balance;}. Thank you again
    – user19489
    Nov 2, 2017 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.