區塊鏈開發(六)以太坊系統下truffle構建智慧合約
阿新 • • 發佈:2019-01-10
truffle環境安裝
針對truffle 環境安裝這裡不多敘述,可以搜一下…
初始化
開啟終端建立一個目錄
mkdir test
cd test
truffle init
會生成檔案
新建合約檔案
然後可以用vscode開啟test目錄
新建一個合約
pragma solidity ^0.4.23;
contract Say {
string private content;
function set(string _msg) public {
content=_msg;
}
function say() constant public returns(string ){
return content;
}
}
增加合約部署檔案
在目錄migrations新建2_deploy_contracts.js
var Say = artifacts.require("./Say.sol");
module.exports = function(deployer) {
deployer.deploy(Say);
};
編譯合約
執行命令
truffle compile
部署合約到區塊鏈上
修改目錄下的檔案truffle.js
如下(host和port要根據自己的配置來定)
module .exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
networks:{
development:{
host:"localhost",
port:8545,
network_id:"*",
gas:3000000
}
}
};
在部署之前先解鎖賬號 ,並啟動挖礦
personal.unlockAccount(user1)
miner.start()
然後執行truffle migrate 部署合約
這樣合約就部署成功了,但是怎麼呼叫呢?下面會講到
合約呼叫
配置引數引數位於truffle中的build/contracts目錄下的Say.json檔案中
可以開啟檔案查詢到
配置abi引數
var abi=[
{
"constant": false,
"inputs": [
{
"name": "_msg",
"type": "string"
}
],
"name": "set",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "say",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
]
配置addr引數
var addr="0x60823932b688af82c81a082f2292e95f879a0cb0"
然後進行呼叫即可
var adoption = web3.eth.contract(abi).at(addr)
console.log("獲取account[0]"+web3.eth.accounts[0]);
adoption.set.sendTransaction("I'm here!!!", {from:web3.eth.accounts[0]})
var str= adoption.say();
console.log("獲取成功"+str);
列印的日誌:
獲取成功I'm here!!!
到此呼叫智慧合約就ok了!!!