[Ethereum] External function call solidity

solidity

Assuming that I don’t know the contract A, I just know its address, and that it has a setNumber method that I want to call it from contract B.

I want to call the function setNumber in contract A, using the method callsetNumbercontractA in contract B.

How to reproduce:

  • Deploy both contracts
  • Copy contract A address and use the function setcontract in contract B
  • Now try to use the function callsetNumbercontractA in contract B

It will fail and I can't get why.

pragma solidity 0.5.12;
contract A {
    event lmao (string);
    uint public x;
    function hello () public {
        emit lmao ('YES');
    }
    function setNumber (uint n) public {
        x=n;
    }
} 

pragma solidity 0.5.12;
contract B{
    address public to;    
    function callcontractA () public {
       to.call(abi.encodeWithSignature("hello()"));
    }   
    function setcontract (address x) public{
        to = x;
    }   
    function callsetNumbercontractA () public {
        // I wanna set var x (in A) to 10
       to.call(abi.encodeWithSignature("setNumber(uint)",10));
    }
}

Ropsten transactions:

Best Answer

There is no reasoning in your question for not using this:

contract IA {
    function setNumber(uint n) public;
}

contract B {
    IA public a;    
    function setContract(IA _a) public {
        a = _a;
    }   
    function setNumber() public {
        a.setNumber(10);
    }
}
Related Topic