Solidity CALL – Difference Between Direct Call and Creating Contract Object

contract-developmentsolidity

What's the difference between these two forms of calling methods on external contracts?

contract A {
    function foo() {
    }
}

contract B {

  function createFoo (address _contractAddress){
    Contract A = A(_contractAddress);
    A.foo();
  }

  function callFoo (address _contractAddress) {
    address newAddress = _contractAddress;
    newAddress.call(bytes4(sha3("foo()")));
  }
}

createFoo and callFoo seem to do the same thing. How are they different?

Best Answer

There's a huge difference between them

function createFoo (address _contractAddress){
    Contract A = A(_contractAddress);
    A.foo();
}

If foo() fails the call to createFoo() will also fail and it will propagate reversing any change you have made.

Another difference is you can retrieve the value returned by foo(). If the function returned an address you can assign to a variable.

address who = A.foo();

In the second case if foo() fails, call will return false. But it will not reverse changes you have made, you have to explicitely call revert().

function callFoo (address _contractAddress) {
    address newAddress = _contractAddress;
    newAddress.call(bytes4(sha3("foo()")));
}

And you do not have access to the value returned by foo(), call only return true if it executed successfully or false if it has failed.