前天搭建了以太坊的私有鏈環(huán)境彬向,今天本來想建立一個基于以太坊的智能合約Demo,發(fā)現(xiàn)很多過去的文檔都已經(jīng)過時了(包括github官網(wǎng))攻冷,折騰了半天娃胆,終于搞定了,現(xiàn)記錄如下等曼。
安裝智能合約編譯器
brew tap ethereum/ethereum
brew install solidity
創(chuàng)建智能合約
新建一個contract文件夾里烦,在文件夾中創(chuàng)建一個demo.sol智能合約文件
pragma solidity ^0.4.20;
contract Demo {
function print(string str) returns (string content) {
content = str;
}
}
編譯,會多出兩個文件禁谦,abi文件就是智能合約相關的接口招驴,bin文件就是智能合約編譯代碼。
> solc -o . --bin --abi demo.sol
> ls
Demo.abi Demo.bin demo.sol
在geth中加載這些文件很復雜枷畏,這里我們修改下剛生成的文件
Demo.abi 文件內(nèi)容修改成
var demoContract = eth.contract([{"constant":false,"inputs":[{"name":"str","type":"string"}],"name":"print","outputs":[{"name":"content","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"function"}])
Demo.bin 文件內(nèi)容修改成
personal.unlockAccount(eth.accounts[0])
var demo = demoContract.new({
from: eth.accounts[0],
data: "0x6060604052341561000f57600080fd5b61016c8061001e6000396000f300606060405260043610610041576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806311114af114610046575b600080fd5b341561005157600080fd5b6100a1600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190505061011c565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100e15780820151818401526020810190506100c6565b50505050905090810190601f16801561010e5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61012461012c565b819050919050565b6020604051908101604052806000815250905600a165627a7a72305820e95348d1ac4b8934c8fcf9f894565bd48f2452fd4a62d0048a7d82c4b788e4a00029",
gas: 500000
})
注意:別忘了data必須0x開頭别厘,New合約就得解鎖自己的賬戶,這里解鎖也寫在這里了
回到geth拥诡,加載剛修改的文件触趴,加載bin文件需要輸入賬戶密碼
文件夾contract就運行在geth命令的目錄
> loadScript("contract/Demo.abi")
true
> loadScript("contract/Demo.bin")
Unlock account 0x0416f04c403099184689990674f5b4259dc46bd8
Passphrase:
true
現(xiàn)在智能合約已經(jīng)部署到區(qū)塊鏈上了,但是要挖礦才能生效渴肉,挖完就可以調(diào)用合約方法了
> demo
{
abi: [{
constant: false,
inputs: [{...}],
name: "print",
outputs: [{...}],
payable: false,
stateMutability: "nonpayable",
type: "function"
}],
address: undefined,
transactionHash: "0xbe51755e1901b037dfd3e9a597a99111ce58d42da2f9fadf18e0909a5fb688fc"
}
> demo.print
undefined
> miner.start(1);admin.sleepBlocks(1);miner.stop();
INFO [03-01|11:01:52] Updated mining threads threads=1
INFO [03-01|11:01:52] Transaction pool price threshold updated price=18000000000
INFO [03-01|11:01:52] Starting mining operation
INFO [03-01|11:01:52] Commit new mining work number=73 txs=1 uncles=0 elapsed=2.428ms
INFO [03-01|11:02:53] Successfully sealed new block number=73 hash=4b0335…049ed7
INFO [03-01|11:02:53] mined potential block number=73 hash=4b0335…049ed7
INFO [03-01|11:02:53] Commit new mining work number=74 txs=0 uncles=0 elapsed=602.175μs
true
> demo.print
function()
true
> demo.print.call("hello world")
"hello world"