0

I'm new to programming languages and trying to dive into solidity smart contracts, but does this mean that this contract could be taken over by anyone calling it due to it being public?

Sorry if this is a bad question

contract Ownable {
  address public owner;

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

  /**
    @dev Throws if called by any account other than the owner.
   /
  modifier onlyOwner() {
    require(msg.sender == owner, "Ownable: caller is not the owner");
    _;
  }

  /*
   * @dev Allows the current owner to transfer control of the contract to a newOwner.
    @param newOwner The address to transfer ownership to.
   /
  function transferOwnership(address newOwner) external onlyOwner {
    if (newOwner != address(0)) {
      owner = newOwner;
2
  • No „address public owner“ does not mean anyone can change it, u can’t change a state without using a method. hope someone provide a detailed answer, cause I’m using my phone
    – Majd TL
    Commented Jul 16, 2021 at 21:22
  • Solidity is a little bit different from other languages, I would not start with it as first programming language, and before understanding solidity :) u need to understand very well how ethereum works
    – Majd TL
    Commented Jul 16, 2021 at 21:28

2 Answers 2

2

No, this code is safe. constructor(...) is a special function, which can only be called once on the contract deployment to initialize the contract params.

After the constructor has run, the final code of the contract is deployed to the blockchain.

Ref: https://docs.soliditylang.org/en/v0.8.6/contracts.html#constructor

1

In fact what protects the contract ownership transfer is this line below:

modifier onlyOwner() {
  require(msg.sender == owner, "Ownable: caller is not the owner");
  _;
}

and then applied on the transferOwnership function

function transferOwnership(address newOwner) external onlyOwner {
  if (newOwner != address(0)) {
    owner = newOwner;
  }
} 

try remove onlyOwner from above function and anyone will can take ownership of this contract!

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.