Search code examples
ethereumgettersolidity

Access variables through auto-generated getters from a different contract


I am storing the variables of my token outside of the main contract in a contract called Storage and, therefore, need to access the auto generated getters of the publicly declared variables from a different contract than the one in which they are declared.

contract Storage {

    mapping (address => uint256) public balanceOf;
    mapping (address => mapping (address => uint256)) public allowance;

}

contract TokenA {

    address public storageAddress;

    function getAllowance(address _owner, address _spender) public returns (uint256) {
        return Storage(storageAddress). allowance( /** ? */);
    }

}

How could I access the variable allowance without specifically defining a getter inside the contract Storage?


Solution

  • You just need to pass it in as if you were calling a function:

    function getAllowance(address _owner, address _spender) public view returns (uint256) {
        Storage s = Storage(storageAddress);
        return s.allowance(_owner, _sender);
    }
    

    Be careful of the order. You may have to swap it depending on how you're handling storage.