I have seen several examples, in the example they defined a contract shown below

contract ForeignToken {
    function balanceOf(address _owner) constant returns (uint256);
    function transfer(address _to, uint256 _value) returns (bool);

And in another contract, they used the previous defined ForeignToken.

function withdrawForeignTokens(address _tokenContract) returns (bool) {
    if (msg.sender != owner) { throw; }

    ForeignToken token = ForeignToken(_tokenContract);

    uint256 amount = token.balanceOf(address(this));
    return token.transfer(owner, amount);

I can't understand how the second contract could use the balanceOf and transfer function, since I assume the ForeignToken doesn't see implement any interface or has its own implementations.

the code example is seen in both




1 Answer 1


That's the whole point of interfaces, it makes it easy to call functions on other contracts without having to know all the contract code.

This line:

  ForeignToken token = ForeignToken(_tokenContract);

Is assuming that the contract at _tokenContract is a contract which implements the ForeignToken interface. So when it calls this function:


it has no way of knowing (and no real need to know) how the balanceOf function works internally. But assuming the token contract has implemented ForeignToken interface, it knows that it will return a uint256.

Different impementations of ForeignToken could work differently, but by declaring token as an instance of ForeignToken, it means the person who wrote the second contract can use the token.balanceOf method in their contract and the compiler won't have an issue with it.

Your Answer

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

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