0

I'm working with a solidity contract that declares a state variable in the constructor like this this:

    constructor(
    address vault,
    address proxy
)
    public
    MarginAdmin()
{
    state = MarginState.State({
        VAULT: vault,
        PROXY: proxy
    });
}

My understanding is that this state variable is internal and will not have a getter created. How do I access this state variable from outside the contract like from a dApp?

1

You should simply include those variables outside of the constructor function as a global variable for the contract.

Take a look at a pretty simple to understand, and very commonly used ownable contract: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol

contract Ownable {
  address public owner;


  event OwnershipRenounced(address indexed previousOwner);
  event OwnershipTransferred(
    address indexed previousOwner,
    address indexed newOwner
  );


  /**
   * @dev The Ownable constructor sets the original `owner` of the contract to the sender
   * account.
   */
  constructor() public {
    owner = msg.sender;
}
...

As you can see the address public owner variable lives outside the constructor function, and instead just gets set (rather than declared) within the constructor.

Would this pattern work for your scenario, or is there some specific need to initialize the variable as a part of the constructor function?

  • I'm working to build a dApp on top of a deployed smart contract so I don't have any ability to edit the contract. – J.McLaren Jul 12 '18 at 22:52
0

State variables cannot be declared inside a constructor (or other function). They have to be declared at the contract level. The code you shared seems to make use of an already-declared variable.

Presumably you'll see something like MarginState public state; outside of the constructor. That's where the state variable called state is declared.

To fetch it from outside the contract, just call the automatically-generated getter state(). Note that if state is not declared as public, then you won't be able to do this.

See https://programtheblockchain.com/posts/2018/01/02/making-smart-contracts-with-public-variables/ for more about public state variables.

  • Thanks you're right that it was declared elsewhere outside the constructor, but it was not declared as public. How is it best to read from variables that aren't public? – J.McLaren Jul 12 '18 at 23:17
  • From another contract, you basically can't. From outside the blockchain, you can use getStorageAt. The blog post I linked to gives an example of that, but you'll need to figure out where in storage that data is found. (If you share the full contract, I can help more.) – user19510 Jul 12 '18 at 23:20

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.