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

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

1. 安裝node.js 8.11.2 LTSweb

2. 安裝Trufflenpm

$ npm install -g truffle

3. 建立項目框架

您能夠建立項目模板,但對於新手,更好的選擇是使用Truffle Boxes—示例應用程序和項目模板。咱們將使用MetaCoin box, 該例子建立可在賬戶之間轉移的token:區塊鏈

$ mkdir MetaCoin
$ cd MetaCoin

下載("unbox") Metacoin box:測試

$ truffle unbox metacoin

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

$ truffle test TestMetacoin.sol

報錯,把warning按提示修改後,還有Error:命令行

出錯緣由是沒有切換到到test目錄中,切換目錄再執行測試命令:3d

5. 編譯智能合約code

$ 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框架部署智能合約的基本過程。

相關文章
相關標籤/搜索