引言: 網(wǎng)上看了不少以太坊智能合約的翻譯文章, 理論解釋還可以,實操方面有些啰嗦,不適合重復(fù)練習(xí);最近自己創(chuàng)業(yè)的公司停擺,有點時間,有點興趣,碼點筆記以備忘.
一,前提
- 理解以太坊基礎(chǔ)理論,略懂js開發(fā)
- 本人實驗環(huán)境如下
os | node.js | solc | testrpc | web3 |
---|---|---|---|---|
linux mint 18 | v7.2 | v0.4.6 | v3.0.2 | 0.17.0-alpha |
二,合約開發(fā)部署 -- HelloWorld.sol
pragma solidity ^0.4.2;
contract HelloWorld {
function greet(string a) returns(string b){
return a;
}
}
打開一個終端term1,啟動 testrpc;另開一個終端 term2,執(zhí)行 node腳本:
Web3 = require('web3')
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
fs = require('fs')
fileName = "HelloWorld.sol"
compiled_contract1 = web3.eth.compile.solidity(fs.readFileSync(fileName,'utf-8'))
console.log('1,編譯完成')
//構(gòu)造合約js對象
constract_object = web3.eth.contract(compiled_contract1.info.abiDefinition);
console.log('2,構(gòu)造對象完成')
//部署合約
deployed_contract = constract_object.new({from: web3.eth.accounts[0], data:"0x"+compiled_contract1.code,gas:120000})
console.log('3,部署合約完成')
//創(chuàng)建者自身訪問合約
setTimeout(function() {//repl環(huán)境下不需要setTimeout
deployed_contract.greet.call('liunix')
console.log(deployed_contract.address) //記住輸出,下面會用到這個地址
}, 1000);
三,合約訪問
網(wǎng)上幾千字文章代碼核心部分就是以上,但其他節(jié)點如何訪問合約并無介紹,如下
新開一個終端 term3
//命令行編譯輸出abi
solc --abi HelloWorld.sol | sed -n '4p' >> HelloWorld.abi
node //以下為nodejs腳本
Web3 = require('web3')
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
fs = require('fs')
helloworld_abi = eval(fs.readFileSync('HelloWorld.abi'))
contract_object = web3.eth.contract(helloworld_abi);
//下行,右側(cè)參數(shù)為上面輸出的地址
var contract_from_address = constract_object.at(deployed_contract.address);//替換
contract_from_address.greet.call('hello world')
問題處理:
1.cb not defined ---根據(jù)異常,在指定目錄中創(chuàng)建npm moudle的link就好
2.out of gas --- 指定gas數(shù)量,如代碼中
結(jié)束及其他:
以太坊合約開發(fā)現(xiàn)在門檻已經(jīng)較低,前端程序員都可以勝任,但水也很深,遇到復(fù)雜毛病,還期望你是一位老司機