0

I'm trying to write a contract which reads the token balance of an address. The token contract is already deployed. What would I need to do to read data from another contract?

Assume I'm trying to read the GNT balance of an address, this is how I'm trying to reference the Golem contract:

 GolemNetworkToken temp = GolemNetworkToken(0xa74476443119A942dE498590Fe1f2454d7D4aC0d);

However this doesn't seem to be valid Solidity syntax.

EDIT: with suggestions:

 pragma solidity ^0.4.16;


contract ERC20Basic {
  uint256 public totalSupply;
  function balanceOf(address who) constant returns (uint256);
  function transfer(address to, uint256 value) returns (bool);
  event Transfer(address indexed from, address indexed to, uint256 value);
}

contract ERC20 is ERC20Basic {
  function allowance(address owner, address spender) constant returns (uint256);
  function transferFrom(address from, address to, uint256 value) returns (bool);
  function approve(address spender, uint256 value) returns (bool);
  event Approval(address indexed owner, address indexed spender, uint256 value);
}

contract test{

  ERC20 myToken = ERC20(0xa74476443119A942dE498590Fe1f2454d7D4aC0d);

  function getTokenBalanceOf(address a) constant returns (uint balance) {
    return myToken.balanceOf(a);
  }
}
1

You need to reference the token and then the syntax that you used should work. In fact, that is what we have the ERC20 standard for: You dont need to include the specific token but just the token interface.

import "./ERC20.sol";

contract myTest {

  ERC20 myToken;

  function setToken(address tokenAddress) {
    myToken = ERC20(tokenAddress);
  }

  function getTokenBalanceOf(address h0dler) constant returns (uint balance) {
    return myToken.balanceOf(h0dler);
  }
}
3
  • I'm confused, can you edit your example so that it does the same for Golem? What would I import? Or would I just change tokenAddress? – ninesalt Aug 30 '17 at 17:58
  • 1
    If you deploy the example contract that's given in the answer, you'd then create a transaction to that new contract with setToken(0xa74476443119A942dE498590Fe1f2454d7D4aC0d) to set it to look at the Golem token. Then queries of getTokenBalanceOf(0x1234...) would return that address' GNT balance. – MidnightLightning Aug 30 '17 at 18:07
  • I just tried it and I'm getting an invalid opcode error. I have updated the post. – ninesalt Aug 30 '17 at 18:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.