【Solidity】OpenZeppelinのOwnableコントラクトとは

【はじめに】

この記事はSolidityを勉強する為にCryptoZombiesで学んだ事を自分用のメモとして書いています。

【CryptoZombiesとは】

Solidityでスマートコントラクトの構築を学習できるサイト
日本語で丁寧に説明してくれるので、プログラミングやったことない人でも学習できる。

cryptozombies.io

【OpenZeppelinのOwnableコントラクトとは】

Lesson3でOpenZeppelinのOwnableコントラクトが出てきました。
Solidityの勉強で重要と思いましたので記事にしておきます。

OpenZeppelinとは?

Ethereum上で安全なスマートコントラクトを実装するためのフレームワーク

github.com

Ownableコントラクトとは?

OpenZeppelinの1つで、コントラクトの実行権限を限定することができる。
実行権限を管理しておかないと誰でも実行できる状態になり悪用される恐れがある。
Ownableコントラクトを継承すれば、コントラクトを作成した人しか実行できないようにすることが可能。

【Ownableコントラクト】

/**
 * @title Ownable
 * @dev The Ownable contract has an owner address, and provides basic authorization control
 * functions, this simplifies the implementation of "user permissions".
 */
contract Ownable {
  address public owner;

  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;
  }

  /**
   * @dev Throws if called by any account other than the owner.
   */
  modifier onlyOwner() {
    require(msg.sender == 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) public onlyOwner {
    _transferOwnership(_newOwner);
  }

  /**
   * @dev Transfers control of the contract to a newOwner.
   * @param _newOwner The address to transfer ownership to.
   */
  function _transferOwnership(address _newOwner) internal {
    require(_newOwner != address(0));
    emit OwnershipTransferred(owner, _newOwner);
    owner = _newOwner;
  }
}

constructor

Ownableコントラクトのコンストラク
コントラクト作成時に1度だけ実行されるので、作成者のアドレスをownerに格納することができる。

modifier onlyOwner

onlyOwnerを関数につけることで使用できる。
コントラクトを呼び出したアドレスと作成者のアドレスが同じでない場合、エラーになる。
つまり、作成者以外が呼び出しても実行できなくなる。

transferOwnership

ownerのアドレスを変更することで実行権限を移行することができる。

【まとめ】

OpenZeppelinはSolidityの開発で頻繁に使われているので、自分で作成するよりもセキュリティ面で安心して使用できます。
Ownable以外にも便利なコントラクトがありそうなので、もっと勉強しなければ。