使用truffle在本地geth上部署MetaCoin合約
博主環境:已經安裝[truffle][6]與[geth][6],[mist][6]錢包。
一:下載MetaCoin到本地
- 1 mkdir demo //創建一個demo目錄
- 2 cd demo //進入目錄
- 3 truffle unbox webpack //在demo目錄下載解壓webpack模板
truffle提供了很多項目模板,可以快速搭建一個去中心化應用的代碼骨架。Truffle 的盒子Boxs裝有很多非常實用的項目樣板,可以讓你忽略一些環境配置問題,從而可以集中與開發你自己的DApp的業務唯一性。除此之外,Truffle Boxes能夠容納其他有用的組件、Solidity合約或者庫,前後端視圖等等。所有這些都是一個完整的實例Dapp程序。都可以下載下來逐一研究,尋找適合自己業務模型的組件。有興趣可以訪問http://truffleframework.com/boxes/。
二:運行在geth上
- 1修改truffle.js //配置文件
module.exports = {
networks: {
development: {
host: '127.0.0.1',
port: 8545,
network_id: '*' // Match any network id
}
}
}
port改爲自己的geth啓動時的port參數,若啓動時沒寫則默認爲8545。
- 2 truffle compile //編譯智能合約
- 3 運行geth
- 4 在geth中解鎖主賬戶,因爲下一步部署合約需要使用主賬戶
personal.unlockAccount('0x9fcE7F757600F054E45E99494b1793bF52686151', '123456')
- 5 truffle migrate //部署智能合約 在truffle2中使用truffle deploy
注意部署時使用miner.start()打開geth的挖礦,在geth上合約的部署都需要區塊確認,否者無法部署成功
三 :檢驗成果
一在錢包上使用合約
- 1 truffle console //打開truffle控制檯
- 2 MetaCoin.address //顯示合約地址
- 3 JSON.stringify(MetaCoin.abi) //返回合約 ABI。ABI 基本上就是對合約的描述。它包含了一個函數、變量和其他因素的列表。
- 4 打開以太坊錢包
點擊進入CONTRACTS
點擊WATCH-CONTRACT
然後複製之前部署的合約的地址和 ABI,點擊ok,打開geth挖礦
看見合約已經顯示了
就可以使用合約了
二跑在遊覽器中
- 1 打開app.js文件
window.addEventListener('load', function() {
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
console.warn("Using web3 detected from external source. If you find that your accounts don't appear or you have 0 MetaCoin, ensure you've configured that source properly. If using MetaMask, see the following link. Feel free to delete this warning. :) http://truffleframework.com/tutorials/truffle-and-metamask")
// Use Mist/MetaMask's provider
window.web3 = new Web3(web3.currentProvider);
} else {
console.warn("No web3 detected. Falling back to http://127.0.0.1:9545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask");
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
window.web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:8545"));
}
App.start();
});
找到這段代碼,改成自己的端口地址如127.0.0.1:9545改爲127.0.0.1:8545,這樣前端纔可以訪問本地geth。
- 2 npm run dev//啓動項目
啓動成功就可以訪問localhost:8080,使用合約了