How to call contract function from other contract in Ethereum

I have a deployed contract "greeter" in Ethereum

contract mortal {
    address owner;
    function mortal() { owner = msg.sender; }

    function kill() { if (msg.sender == owner) selfdestruct(owner); }
}

contract greeter is mortal {
    string greeting;

    function greeter(string _greeting) public {
        greeting = _greeting;
    }
    function greet() constant returns (string) {
        return greeting;
    }
}

And I want to create another contract, which will call function "kill" from my first contract. The main idea is that this 2 contracts is different. I publish contract A and then publish contract B, which calls A.

How I can do that? Something like this, but from contract...

var contract = web3.eth.contract(contractAddress, ABI);
contract.call().kill();

Upvotes: 1

Views: 1094

Answers (1)

Rob Hitchens
Rob Hitchens

Reputation: 1059

Approximately like this, but there's a catch.

pragma solidity ^0.4.6;

contract Mortal {
  address owner;
  function Mortal() { owner = msg.sender; }

  function kill() { if (msg.sender == owner) selfdestruct(owner); }
}

contract Greeter is Mortal {
  string greeting;

  function Greeter(string _greeting) public {
    greeting = _greeting;
  }
  function greet() constant returns (string) {
    return greeting;
  }
}

contract Killer {

  function destroyVictim(address victim) {
    Greeter g = Greeter(victim);
    g.kill();
  }
}

That's a basic syntax. The ABI gets picked up by including Greeter in the source file along with Killer; that is, the compiler can "see it".

So far, so good.

The issue that arises is that Greeter is going to ignore the command, owing to if(msg.sender==owner). It won't be. It will be whatever address Killer got.

A possible solution to this before Greeter is deployed is to anticipate the need for a changeOwner() function, usually reserved for only the current owner.

Hope it helps.

Upvotes: 1

Related Questions