0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[ETH-MEETUP] Solidityでアドレス帳を作った

Last updated at Posted at 2019-07-01

Ethereumのミートアップの課題「アドレス帳を作ろう」

2019/07/06 SingularityHIVE 開催
Ethereum Solidity入門課題

仕様

  • set(string, uint8): 送信者は名前と年齢を登録する.
  • getAge(address, a): アドレスに登録された年齢を得る.
  • getName(address, a): アドレスに登録された名前を得る.
  • getDate(address, a): アドレスに登録された日付を得る.
  • hello(): 送信者へ挨拶を返す.「Hello, xxx!!」(xxxは予め登録されている名前).

アドレス帳のコード例

AddressBook.sol
pragma solidity >=0.4.22 <0.6.0;
contract AddressBook {
    // 登録情報の構築
    struct Info {
        string name;
        uint8 age;
        uint date;
    }
    // アドレスと登録情報を紐付ける
    mapping(address => Info) book;
    // 挨拶の雛形
    string left;
    string right;
    
    // 雛形を初期化
    constructor() public {
        left = "Hello, ";
        right = "!!";
    }
    // 送信者情報を登録
    function set(string name, uint8 age) public {
        Info storage info = book[msg.sender];
        info.name = name;
        info.age = age;
        info.date = now;
    }
    // アドレスに登録された名前を取得
    function getName(address a) public view returns(string name){
        Info memory info = book[a];
        name = info.name;
    }
    // アドレスに登録された年齢を取得
    function getAge(address a) public view returns(uint8 age){
        Info memory info = book[a];
        age = info.age;
    }
    // 情報が登録されたを日時を取得
    function getDate(address a) public view returns(uint date) {
        Info memory info = book[a];
        date = info.date;
    }
    // 送信者に挨拶を返す
    function hello() public view returns(string greet) {
        Info memory sender = book[msg.sender];
        
        string memory name = sender.name;
        string memory hellox = strConnect(left, name);
        greet = strConnect(hellox, right);
    }
    // 文字列の結合を行う
    function strConnect(string str1, string str2) private pure returns(string){

        bytes memory strbyte1 = bytes(str1);
        bytes memory strbyte2 = bytes(str2);

        bytes memory str = new bytes(strbyte1.length + strbyte2.length);

        uint8 point = 0;

        for(uint8 j = 0; j < strbyte1.length;j++){
            str[point] = strbyte1[j];
            point++;
        }
        for(uint8 k = 0; k < strbyte2.length;k++){
            str[point] = strbyte2[k];
            point++;
        }
        return string(str);
    }
}

軽く解説

mappingでアドレスと登録情報を紐づけ
登録情報はstructで一括管理(名前,年齢,登録日時)
挨拶の雛形としてleftとrightを定義し,コンストラクタで初期化
文字列の結合を行うstrConnectメソッドを実装(参考: Solidityで文字列連結

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?