Truffle是以太坊(Ethereum)智能合約開發的瑞士軍刀,小巧好用,上手簡單。
本篇文章主要展示如何用Truffle 開發第一個Ethereum智能合約。
1.准備工作:(本人針對window環境,如果是mac 或linux可以自行搜索其他教程)
a.安裝git bash :http://gitforwindows.org/
b.安裝npm:https://jingyan.baidu.com/article/a17d528506d7f58098c8f2b0.html
2.安裝Truffle。
按照Truffle的官網指示:http://truffleframework.com/docs/getting_started/installation
在git bash命令行輸入如下 命令:
npm install -g truffle
3.開發智能合約
安裝完好,運行:
mkdir simple-storage cd simple-storage
然后運行:
truffle init
這個命令會建立 兩個目錄:contracts/和migrations/
其中contracts/是智能合約所在的目錄,而migrations/是把合約部暑到以太坊的
相關命令。
打開 目錄:contracts/,創建一個新文件:Store.sol,文件內容如下 :
pragma solidity ^0.4.17; contract SimpleStorage { uint myVariable; function set(uint x) public { myVariable = x; } function get() constant public returns (uint) { return myVariable; } }
打開目錄:migrations/,創建一個文件2_deploy_contracts.js,內容如下 :
var SimpleStorage = artifacts.require("SimpleStorage"); module.exports = function(deployer) { deployer.deploy(SimpleStorage); };
保存好。
回到命令行,運行命令:truffle compile
打開另一個git bash 窗口進入相同目錄,運行:
truffle develop
然后運行:
migrate
窗口會出現如下信息:
Running migration: 1_initial_migration.js
Replacing Migrations...
... 0xe4f911d95904c808a81f28de1e70a377968608348b627a66efa60077a900fb4c
Migrations: 0x3ed10fd31b3fbb2c262e6ab074dd3c684b8aa06b
Saving successful migration to network...
... 0x429a40ee574664a48753a33ea0c103fc78c5ca7750961d567d518ff7a31eefda
Saving artifacts...
Running migration: 2_deploy_contracts.js
Replacing SimpleStorage...
... 0x6783341ba67d5c0415daa647513771f14cb8a3103cc5c15dab61e86a7ab0cfd2
SimpleStorage: 0x377bbcae5327695b32a1784e0e13bedc8e078c9c
Saving successful migration to network...
... 0x6e25158c01a403d33079db641cb4d46b6245fd2e9196093d9e5984e45d64a866
Saving artifacts...
繼續在truffle develop窗口運行如下 代碼:SimpleStorage.deployed().then(function(instance){return instance.get.call();}).then(function(value){return value.toNumber()});
這條命令結果如下
0
繼續在truffle develop窗口運行如下代碼:
SimpleStorage.deployed().then(function(instance){return instance.set(4);});
這是會出現如下信息:
{ tx: '0x7f799ad56584199db36bd617b77cc1d825ff18714e80da9d2d5a0a9fff5b4d42', receipt: { transactionHash: '0x7f799ad56584199db36bd617b77cc1d825ff18714e80da9d2d5a0a9fff5b4d42', transactionIndex: 0, blockHash: '0x60adbf0523622dc1be52c627f37644ce0a343c8e7c8955b34c5a592da7d7c651', blockNumber: 5, gasUsed: 41577, cumulativeGasUsed: 41577, contractAddress: null, logs: [] }, logs: [] }
這里的tx是交易的ID,可能你窗口顯示的ID會不一樣。
這里說明,你的交易成功,帳本已經成功設置為4.
好,現在我們來驗證下,運行如下 命令:
SimpleStorage.deployed().then(function(instance){return instance.get.call();}).then(function(value){return value.toNumber()});
結果返回為:
4
成功了!
你已經學會開發智能合約!
恭喜你!!!!!
工作與合作,請加微信/qq:360369487
