0

I want to write a smart contract where it would check it is owner of the deployed contract is trying to instantiate the contract or not. And by doing to i want to allow only the owner to call smart contract. How can i do so?

pragma solidity ^0.5.0;

contract Storage {
  string Hash;

  function set(string memory x) public {
    Hash = x;
  }

  function get() public view returns (string memory) {
    return Hash;
  }
}

This is my smart contract where i am using setter and getter method.

3
  • Terminology: a deployed contract is already instantiated. Deploying a contract is another word for instantiating. "evoking". Did you mean "invoking? Can you review your wording around "is trying to instantiate the contract"? Oct 28, 2019 at 10:07
  • 1
    Otherwise, what I think you are looking for is the well-known Ownable / Owned pattern. You may Google "OpenZeppelin" for examples. Oct 28, 2019 at 10:08
  • @XavierLeprêtreB9lab yeah i am looking for Ownable pattern. Oct 28, 2019 at 10:19

1 Answer 1

1
contract Storage {
  address private owner;
  bytes32 private hash;

  constructor () public {
    owner = msg.sender; // Whoever deploys smart contract becomes the owner
  }

  function set (bytes32 _hash) public {
    require (msg.sender == owner); // Ensure smart contract is called by the owner
    hash = _hash;
  }

  function get () public view returns (bytes32) {
    return hash;
  }
}

Note, that I changed type of hash from string to bytes32 because bytes32 seems to be more appropriate type for storing hashes.

4
  • Vlad imirov Thanks for exact answer.Do i need to provide contract owner address everytime or its checks on its own? Oct 28, 2019 at 11:11
  • 1
    No, you don't need to provider it at all. Smart contract just checks transaction origin. You implicitly provide your address every time you sign Ethereum transaction with your private key. Oct 28, 2019 at 12:11
  • My hash is more than 32, that's why i used string otherwise it gives error. can i store more than 32 positions hash in other way? Oct 28, 2019 at 13:01
  • 32 bytes is 64 hexadecimal digits looking like this: 0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef. Oct 28, 2019 at 13:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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