Truffle unbox 实例实现
1.Pet-shop实现
2.下载pet-shop unbox:truffle unbox pet-shop
然后直接运行:npm run dev
然后自动弹出宠物网页:http://localhost:3000/
3.Bootstrap:前端开发框架
4.步骤
- 打开ganache
- 设置metamask网络为私有Private
- 编写智能合约: ①实现领养功能 ②该宠物还没有被其他人领养
- 新建领养合约
上图中的地址就是合约地址。
- 编写部署文件
编译文件,传入数据 truffle compile
添加部署脚本:新建2_adopt_migration.js,复制1_initial_migration.js中的内容至2中,并作改变
做部署:truffle migrate
- 测试
在test文件夹中新建TestAdoption.sol
测试: truffle test
- 实现合约交互逻辑
在app.js中
App = {
web3Provider: null,
contracts: {},
init: function() {
// Load pets.
$.getJSON('../pets.json', function(data) {
var petsRow = $('#petsRow');
var petTemplate = $('#petTemplate');
for (i = 0; i < data.length; i ++) {
petTemplate.find('.panel-title').text(data[i].name);
petTemplate.find('img').attr('src', data[i].picture);
petTemplate.find('.pet-breed').text(data[i].breed);
petTemplate.find('.pet-age').text(data[i].age);
petTemplate.find('.pet-location').text(data[i].location);
petTemplate.find('.btn-adopt').attr('data-id', data[i].id);
petsRow.append(petTemplate.html());
}
});
return App.initWeb3();
},
initWeb3: function() {
// 首先判断当前是否有web3注入
if (typeof web3 != 'undefined') {
App.web3Provider = web3.currentProvider; // 已注入的情况
} else {
App.web3Provider = new Web3.providers.HttpProvider("http://127.0.0.1:7545");
}
web3 = new Web3(App.web3Provider);
return App.initContract();
},
initContract: function() {
$.getJSON('Adoption.json', function(data) {
var AdoptionArtifact = data;
App.contracts.Adoption = TruffleContract(AdoptionArtifact); // adopt合约实例
App.contracts.Adoption.setProvider(App.web3Provider);
return App.markAdopted();
});
return App.bindEvents();
},
bindEvents: function() {
$(document).on('click', '.btn-adopt', App.handleAdopt);
},
// 当宠物领养成功,标记为已领养
markAdopted: function(adopters, account) {
var adoptionInstance;
App.contracts.Adoption.deployed().then(function(instance) {
adoptionInstance = instance;
return adoptionInstance.getAdopters.call();
}).then(function (adopters) {
// 遍历 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);
})
},
// 处理领养的函数
handleAdopt: function(event) {
event.preventDefault();
var petId = parseInt($(event.target).data('id'));
var adoptionInstance;
web3.eth.getAccounts(function (error, accounts) {
if (error) {
console.log(error);
}
var account = accounts[0];
App.contracts.Adoption.deployed().then(function (instance) {
adoptionInstance = instance;
// 执行领养宠物的函数
return adoptionInstance.adopt(petId, {from:account});
}).then(function (result) {
return App.markAdopted(); // 将该宠物标记为已领养
}).catch(function (err) {
console.log(err.message);
})
})
}
};
$(function() {
// 加载
$(window).load(function() {
App.init();
});
});
坑:
pet_shop网站打不开,更换jquery。
在 https://www.bootcdn.cn/jquery/ 中 ,复制1.12.4版本;上面为之前版本,更换为下面的。