1. 環(huán)境環(huán)境
首先nodejs,npm
安裝truffle,ganache
sudo npm install -g truffle
sodu npm install -g ganache-cli
查了下,好像還有可視化的ganache,馬上下載嘗試

image.png
根據官方網站
下載petshop
mkdir petshop
cd petshop
truffle unbox pet-shop
truffle develop
出現(xiàn) >
compile
migrate
其中出現(xiàn)warning沒關系

image.png
運行看看
npm run dev
就會自動出現(xiàn)petshop

image.png
-- 完--
2. 未完待續(xù)
就這么完了嗎?分析代碼,首先查看contract為空的。??垂倬W

image.png
原來還有tuturial啊
首先在contracts文件夾內新建Adoption.sol
pragma solidity ^0.4.17;
contract Adoption {
address[16] public adopters;
// Adopting a pet
function adopt(uint petId) public returns (uint) {
require(petId >= 0 && petId <= 15);
adopters[petId] = msg.sender;
return petId;
}
// Retrieving the adopters
function getAdopters() public view returns (address[16]) {
return adopters;
}
}
然后在migrations文件夾部署上,新建2_deploy_contracts.js
var Adoption = artifacts.require("Adoption");
module.exports = function(deployer) {
deployer.deploy(Adoption);
};
這個時候就該打開ganache,
然后運行
truffle compile
truffle migrate

image.png

咦我的eth少了0.06
3. 測試合約請看教程。。
4. 開始寫js邏輯了,
找到js文件夾的app.js, 在initWeb3的明顯位置添加
// Is there an injected web3 instance?
if (typeof web3 !== 'undefined') {
App.web3Provider = web3.currentProvider;
} else {
// If no injected web3 instance is detected, fall back to Ganache
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}
web3 = new Web3(App.web3Provider);
再在initContract的明顯位置添加
$.getJSON('Adoption.json', function(data) {
// Get the necessary contract artifact file and instantiate it with truffle-contract
var AdoptionArtifact = data;
App.contracts.Adoption = TruffleContract(AdoptionArtifact);
// Set the provider for our contract
App.contracts.Adoption.setProvider(App.web3Provider);
// Use our contract to retrieve and mark the adopted pets
return App.markAdopted();
});

image.png
還有一處要更新,在handleAdopt
var adoptionInstance;
App.contracts.Adoption.deployed().then(function(instance) {
adoptionInstance = instance;
return adoptionInstance.getAdopters.call();
}).then(function(adopters) {
for (i = 0; i < adopters.length; i++) {
if (adopters[i] !== '0x0000000000000000000000000000000000000000') {
$('.panel-pet').eq(i).find('button').text('Success').attr('disabled', true);
}
}
}).catch(function(err) {
console.log(err.message);
});
重新compile和migrate,但碰到錯誤

image.png
猜想我是重新打開了ganache,于是用
truffle migrate --reset
解決正常

image.png
5. metamask
下面教大家配置metamask
首先下載chrome錢包插件

image.png
對應ganache網址在setting設置

image.png

image.png
就會出現(xiàn)賬號和余額
6. 運行
終于到最激動人心的時刻了
npm run dev
在此界面點擊adopt

image.png
雖然demo是發(fā)送了0 eth,只用了gas (為什么可以自己設)
我們已經成功完成了鏈上交易

image.png
就在這個基礎上繼續(xù)開發(fā)吧!??!
完
