以太坊開發框架Truffle學習筆記


from http://truffleframework.com/docs/getting_started/project

1. 安裝node.js 8.11.2 LTS

2. 安裝Truffle

$ npm install -g truffle

3. 創建項目

您可以創建項目模板,但對於新手,更好的選擇是使用Truffle Boxes—示例應用程序和項目模板。我們將使用MetaCoin box, 該例子創建可在帳戶之間轉移的token:

$ mkdir MetaCoin
$ cd MetaCoin

下載("unbox") Metacoin box:

$ truffle unbox metacoin

4. 測試,運行solidity測試文件

$ truffle test TestMetacoin.sol

報錯,把warning按提示修改后,還有Error:

出錯原因是沒有切換到到test目錄中,切換目錄再執行測試命令:

5. 編譯智能合約

$ truffle compile

6. 部署智能合約

要部署我們的智能合約,我們需要一個客戶端來與區塊鏈進行交互。推薦使用Ganache-cli(Ganache命令行版,原ethereumjs-testrpc), 是一個適用於開發時使用的客戶端,是Tuffle套件中的一部分。

6.1 下載安裝

$ sudo npm install -g ganache-cli

6.2 修改Tuffle.js文件為以下內容:(port不是7545,在6.3圖中看出是8545,估計ganache的默認端口為7545,ganache-cli默認端口為8545)

module.exports = {
    networks: {
        development: {
            host: "127.0.0.1",
            port: 8545,
            network_id: "*"
        }
    }
};    

6.3 啟動Ganache-cli,創建區塊鏈

$ ganache-cli

創建了與區塊鏈交互時可以使用的10個帳戶(及其私鑰),默認發送賬戶為第一個

6.4 將合約遷移到由Ganache-cli創建的區塊鏈

$ truffle migrate

顯示了已部署合約的交易ID和地址

7. 與智能合約進行交互

可以用Truffle console來與智能合約進行交互

$ truffle console

通過以下方式使用Truffle控制台與合同進行交互:

  • 查看部署合約的賬戶metacoin余額:
    MetaCoin.deployed().then(function(instance){return instance.getBalance(web3.eth.accounts[0]);}).then(function(value){return value.toNumber()});

  • 查看部署合約的賬戶以太幣余額,合約中定義的一個metacoin值2個以太幣:
    MetaCoin.deployed().then(function(instance){return instance.getBalanceInEth(web3.eth.accounts[0]);}).then(function(value){return value.toNumber()});
  • metacoin轉賬:
    MetaCoin.deployed().then(function(instance){return instance.sendCoin(web3.eth.accounts[1], 500);});

  • 查看接收方賬戶metacoin余額:

    MetaCoin.deployed().then(function(instance){return instance.getBalance(web3.eth.accounts[1]);}).then(function(value){return value.toNumber()});

  •  查看發送發賬戶metacoin余額:

以上就是用Truffle框架部署智能合約的基本過程。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM