Day 13 :
在Day12 編譯了SimpleStorage合約之後,在Terminal中啟動geth控制台,佈署合約並呼叫測試。
-開啟geth 控制台
解鎖佈署合約的帳戶 :
personal.unlockAccount(eth.accounts[0],”123456”)
-佈署合約
輸入:
> var simplecontract = eth.contract(JSON.parse("[{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]")).new({from:eth.accounts[0],data:"0x608060405234801561001057600080fd5b5060bf8061001f6000396000f30060806040526004361060485763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166360fe47b18114604d5780636d4ce63c146064575b600080fd5b348015605857600080fd5b5060626004356088565b005b348015606f57600080fd5b506076608d565b60408051918252519081900360200190f35b600055565b600054905600a165627a7a723058201b1ac848def04a12fe60651863449af427bb408c4d623d63684777366daedfeb0029",gas:5000000});
說明 :
var simplecontract (將simplecontract設定成返回的合約地址)
eth.contract().new() :
1.參數為合約的abi內容,。
2. from=佈署合約的帳戶,data=合約中的二進制碼,因為是以十六進位表示,作為參數傳入時要加上0x
為開頭,gas=佈署合約的手續費。
JSON.parse() :
將JSON字串解析為物件。
- 查看合約內容
輸入 :
> simplecontract
{
abi: [{
constant: false,
inputs: [{...}],
name: "set",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function"
}, {
constant: true,
inputs: [],
name: "get",
outputs: [{...}],
payable: false,
stateMutability: "view",
type: "function"
}],
address: undefined,
transactionHash: "0x47bd325bcdaaebad6469416957c3cc3aa6df16fa57747d30eedd6a084a19eb6e"
}
合約資訊和交易雜湊值,因為交易還沒有被確認,所以address還是未定義的。
-查看交易
> txpool.inspect.pending
{
0x4ca5F4A1612EBe48d8E48c7dF7B2f0d2839EbC56: {
2: "contract creation: 0 wei + 5000000 gas × 1000000000 wei"
}
}
交易尚在緩衝區中等待。
- 確認交易 ,開啟挖礦
> miner.start(1);admin.sleepBlocks(1);miner.stop();
挖礦成功之後,查看合約。
-查看合約內容
> simplecontract
{
abi: [{
constant: false,
inputs: [{...}],
name: "set",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function"
}, {
constant: true,
inputs: [],
name: "get",
outputs: [{...}],
payable: false,
stateMutability: "view",
type: "function"
}],
address: "0x2231a1d1e604cac2eb0ac86680a5384d3c940c16",
transactionHash: "0x47bd325bcdaaebad6469416957c3cc3aa6df16fa57747d30eedd6a084a19eb6e",
allEvents: function(),
get: function(),
set: function()
}
在合約佈署成功之後,會出現合約地址和可以呼叫的Method。