user938363
user938363

Reputation: 10350

How to set owner address when deploying a smart contract

Here is simple smart contract with owner:

pragma ^0.7.2

contract simple {
  address owner;

  constructor() public {
    //do something 
  }

  modifier() {
    require(
      owner == msg.sender,
      'No sufficient right'
    )
  }

  function setOwner() ownerOnly external {
     owner = msg.sender;
  }
}

My question is how to securely set owner address to the address of the smart contract owner?

Upvotes: 4

Views: 7918

Answers (1)

Vladyslav Munin
Vladyslav Munin

Reputation: 686

You should set owner address directly in the constructor. msg.sender field will represent the contract creator.

constructor ()  {
       owner = msg.sender;
   }

And your function setOwner doesn't have a lot of sense, because even in case owner was set during creation, it can not be changed. Modifier will reject all transactions, that are sent not from owner. Otherwise it will just reassign owner to msg.sender who is also owner. It should look like this:

function setOwner(address newOwner) ownerOnly external {
     owner = newOwner;
  }

Upvotes: 6

Related Questions