今日、簡単なスマートコントラクトを書きました。
コード
libraryContract.sol
pragma solidity ^0.4.25;
contract LibraryContract {
  struct Book {
    string title;
    bool isBorrowed;
    address holder;
  }
  Book[] bookCollection;
  function addBook(string _title) public {
    bookCollection.push(Book(_title, false, address(0)));
  }
  function borrowBook(uint _index) public {
    require(!bookCollection[_index].isBorrowed);
    bookCollection[_index].isBorrowed = true;
    bookCollection[_index].holder = msg.sender;
  }
  function returnBook(uint _index) public {
    require(bookCollection[_index].isBorrowed);
    require(bookCollection[_index].holder == msg.sender);
    bookCollection[_index].isBorrowed = false;
    bookCollection[_index].holder = address(0);
  }
  
  function getBookHolder(uint _index) public view returns (address) {
    require(bookCollection[_index].isBorrowed);
    return bookCollection[_index].holder;
  }
  function isBookAvailable(uint _index) public view returns (bool) {
    return !bookCollection[_index].isBorrowed;
  }
}
このコードは単純な図書館システム。本を追加したり、借りれたり、返せたりすることができます。
スタートとBook(本) struct
pragma solidity ^0.4.25;
contract LibraryContract {
  struct Book {
    string title;
    bool isBorrowed;
    address holder;
  }
  Book[] bookCollection;
  ...
}
最初の行にSolidityのバージョンを入れます。次の行から最後まで、スマートコントラクトは「LibraryContract」でくくります。次に、「Book」というstructでBook objectとは何かを定義しています。「title」という変数に本の題名を含めています。誰かが本を借りたら、「isBorrowed」という変数はtrueになります。「holder」という変数に本の借人を含めています。そして、「bookCollection」というBook同位列があります。
本を付け加えて借りて返せてにする
pragma solidity ^0.4.25;
contract LibraryContract {
  ...
  function addBook(string _title) public {
    bookCollection.push(Book(_title, false, address(0)));
  }
  function borrowBook(uint _index) public {
    require(!bookCollection[_index].isBorrowed);
    bookCollection[_index].isBorrowed = true;
    bookCollection[_index].holder = msg.sender;
  }
  function returnBook(uint _index) public {
    require(bookCollection[_index].isBorrowed);
    require(bookCollection[_index].holder == msg.sender);
    bookCollection[_index].isBorrowed = false;
    bookCollection[_index].holder = address(0);
  }
  ...
}
最初の関数で本を加えられます。次の関数で本を借りられます。最後の関数で本を返せます。本を借りられるか返せるかどうかをチェックします。
補足
pragma solidity ^0.4.25;
contract LibraryContract {
  ...
  function getBookHolder(uint _index) public view returns (address) {
    require(bookCollection[_index].isBorrowed);
    return bookCollection[_index].holder;
  }
  function isBookAvailable(uint _index) public view returns (bool) {
    return !bookCollection[_index].isBorrowed;
  }
}
この補足の関数は「本の借人は誰ですか?」と「この本を借りれりますか?」という質問に答えるものです。
EthFiddleでこのコードを見ることもできます。
