0

I have two contracts Vase and Box

contract Vase {
    uint256 public vase1;
    event VaseValueChanged(uint256 newValue);

    function createVase(uint256 newValue) public {
        vase1 = newValue;
        emit VaseValueChanged(newValue);
    }

    // Reads the last stored value
    function retrieveVase() external view returns (uint256) {
        return vase1;
    }
}

contract Box {
    uint256 private value;



    // Stores a new value in the contract
    function store(uint256 newValue, uint256 breadth) public {
        value = newValue;
    }


}

Both are upgradable smartcontracts and I am using the openzeppelin library and using its CLI for upgrading these contracts.

How can I call retrieveVase() method of Vase contract from Box contract. I don't want to inherit Vase in Box contract.

1
  • I'm not quite sure how this is related to upgradable contracts? Or is this simply a question about "how can I reference another contract in my contract"? – Lauri Peltonen Sep 23 '20 at 7:52
1

You can use one of the 2 following options:

  1. Via interface contract:

ContractA.sol:

pragma solidity ^0.5.11;

contract A {
    uint256 public testVariable = 5;
    
    function getTestVariable() public view returns(uint256) {
        return testVariable;
    }
}

ContractB.sol:

pragma solidity ^0.5.11;

contract B {
    A a_contract_instance;
    constructor(address _a_contract_address) public {
        a_contract_instance = A(_a_contract_address);
    }
    
    function callToContractA() public view returns(uint256) {
        return a_contract_instance.getTestVariable();
    }
}

interface A {
    function getTestVariable() external view returns(uint256);
}
  1. Via .call() function:
pragma solidity ^0.5.0;

contract ExistingContract  {
    uint256 test_val;
    address test_addr;
    
    function getA() public view returns (uint256, address) {
        return (test_val, test_addr);
    }
    
    function setA(uint256 _val) public {
        test_val = _val;
        test_addr = msg.sender;
    }
}

contract Caller {
    function externalCallGetA(address _addr) public returns(uint256) {
        (bool success, bytes memory result) = address(_addr).call(abi.encodeWithSignature("getA()"));
        require(success);
        
        return abi.decode(result, (uint256));
    }
    
    function externalCallSetA(address _addr, uint256 _var) public{
        (bool success,) = address(_addr).call(abi.encodeWithSignature("setA(uint256)", _var));
        require(success);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.