[Ethereum] Understanding nameReg.call(“register”, “MyName”) style call between contracts

abicontract-invocationfallback-functionsolidity

Here's an example from solidity docs on Address type methods(call method specifically):

address nameReg = 0x72ba7d8e73fe8eb666ea66babc8116a41bfb10e2;

nameReg.call("register", "MyName");

nameReg.call(bytes4(sha3("fun(uint256)")), a);

I can't understand what the second line does. Does it call the fallback function with these two arguments? Or does it pass string MyName to function register on nameReg contract?

Best Answer

From the link in the question, the important part about nameReg.call("register", "MyName") is (bold mine):

to interface with contracts that do not adhere to the ABI, the function call is provided which takes an arbitrary number of arguments of any type. These arguments are padded to 32 bytes and concatenated.

See the note here:

Note: the ABI is an abstraction that is not part of the core Ethereum protocol. Anyone can define their own ABI for their contracts, and any callers of such contracts would have to comply with that ABI to get meaningful results. However, it is simpler for all developers to use Solidity, Serpent, and web3.js which all comply with the ABI above.

nameReg.call("register", "MyName") will not invoke register on a nameReg contract compiled by Solidity. The reason is that Solidity does not use "register" to lookup "functions" (it uses the first 4 bytes as the method id. For example EVM pseudocode that Solidity produces, see this). Here's code for a quick test:

contract NameReg {
    bytes32 public nn;
    bytes public calldata;

    function register(bytes32 name) {
      nn = name;    
    }

    function() {
        calldata = msg.data;
    }

    function doesNotCallRegister() {
        this.call("register", "MyName");
    }
 }

With anameReg contract compiled by Solidity, nameReg.call("register", "MyName") will invoke the fallback function where msg.data will be "register", "MyName" padded to 32 bytes and concatenated: 0x72656769737465720000000000000000000000000000000000000000000000004d794e616d650000000000000000000000000000000000000000000000000000.

Related Topic