今天來規劃另一個題目區塊鏈留言板。

留言板其實很簡單,但是會比昨天的投票系統結構稍微複雜一點,我們先來看看合約該怎麼寫。

我們一樣先建立一個資料夾 dapp-guestbook ,然後進去資料夾裡面下

truffle init

透過 truffle 把目錄結構產生出來後,就可以進去 contract 資料夾,新增一個 Guestbook.sol,檔案內容如下。

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <0.7.0;

contract Guestbook {

    //定義一個 struct 裡面會有文字、誰留言的、留言時間
    struct Item {
        string word;
        address who;
        uint when ;
    }

    //定義一個 陣列,儲存上面的 item
    Item[] private allWords;

    function save(string memory s, uint t) public {
        allWords.push(Item({
            word: s,
            who: msg.sender,
            when: t
        }));
    }

    查詢陣列長度
    function getSize() public view returns (uint){
        return allWords.length;
    }

    查詢留言板內的內容
    function queryGusetbook(uint index) public view returns (string memory, address, uint) {
        //如果長度為0 則直接回傳
        if(allWords.length==0){
            return ("", msg.sender, 0);
        }else{
            Item storage result = allWords[index];
            return (result.word, result.who, result.when);
        }
    }
}

這樣我們就完成了一個留言板合約,明天我們來把剩下的 html & js 完成。