github地址
官网教学:https://www.trufflesuite.com/tutorial
教程内容
本教程将带您完成构建您的第一个 Dapp
宠物店的收养跟踪系统
适用人群
具有以太坊和智能合约基础知识、具有一些简答的 HTML 和 JavaScript 知识但不熟悉 dapp 的人。
简单了解truffle是什么东西
Truffle 是世界一流的开发环境
为以太坊的测试框架和资产管道,致力于使以太坊开发者的生活更容易。
由Consensys公司开发和维护
特点
内置智能合约编译、链接、开发和二进制管理。快速开发的自动化合约测试脚本、可扩展性部署和迁移框架。用于部署到任意数量的公网和私网的网络管理基于EthPM和NPM,并使用ERC190标准进行包管理为合约通信提供交互式控制台为紧密集成提供可配置的构建管道在Truffle的环境中执行外部的运行脚本
准备工作
(npm是Node 自带)
(http://truffleframework.com/ganache)
注意:如果您在没有图形界面的环境中进行开发,您也可以使用Truffle内置的个人区块链Truffle Develop来代替Ganache。您将需要更改一些设置(例如区块链运行的端口)以适应 Truffle Develop 的教程。
Ganache是什么
它是一个以太坊的个人开发环境,你可以在上面部署合约、开发程序和进行测试。
停止开发了
后续步骤:1.迁移路径:将与HardHat合作提供描述从Truffle到HardHat的迁移过程的文档;2.产品支持:未来90天内,将通过Zendesk、Truffle GitHub、Ganache GitHub和Consensys Discord提供Truffle和Ganache的支持;3.代码库的未来:从2023年12月20日起,Truffle和Ganache代码库将作为公共存档可供使用,这为开发人员迁移到HardHat和其他解决方案提供了约90天的时间。
Consensys建议在3个月的弃用期内停止使用Truffle和Ganache,以确保正在使用的工具得到积极维护并更新依赖项。此外,Consensys称Truffle的工程和产品团队已在内部转向MetaMask和Infura中以开发人员为中心的产品,他们将继续致力于支持Web3构建器。
虽然不更新了,但是我们依然可以在区块链学习的道路上使用truffle来明细一些开发过程。
正式开始
一旦我们安装了这些,我们只需要一个命令来安装 Truffle:
先用cmd打开命令,输入:
npm install -g truffle
检查
truffle version
使用 Truffle Box 创建 Truffle 项目
首先创建一个目录名字叫pet-shop-tutorial
cd进入文件
mkdir pet-shop-tutorial
cd pet-shop-tutorial
下载
下载项目pet-shop
也可在github下载
truffle unbox pet-shop
目录结构
默认的 Truffle 目录结构
包含我们智能合约的Solidity源文件。
编写智能合约Adoption.sol
pragma solidity ^0.5.0;
contract Adoption {
//声明了一个可以存储最多16个以太坊地址的数组,这个数组是公开的
//adopters 收养者
address[16] public adopters;
// 收养宠物函数
function adopt(uint petId) public returns (uint) {
//确保
require(petId >= 0 && petId <= 15);
//msg.sender 是一个全局变量,在Solidity中用于指代当前调用智能合约的地址
adopters[petId] = msg.sender;
return petId;
}
// 检索采用者 view不会修改合约的状态免费查看 返回整个数组
function getAdopters() public view returns (address[16] memory) {
return adopters;
}
}
分析两个功能
收养宠物 |
检索采用者 |
adopt |
getAdopters |
|
|
汇编
truffle compile
已经成功编译了合约,是时候将它们迁移到区块链了
2_deploy_contracts.js
在目录中创建一个名为的新文件migrations/
。- 将以下内容添加到
2_deploy_contracts.js
文件中:
var Adoption = artifacts.require("Adoption");
module.exports = function(deployer) {
deployer.deploy(Adoption);
};
- 回到我们的终端,将合约迁移到区块链。
truffle migrate
应该看到类似于以下内容的输出:
创建与智能合约交互的用户界面
Truffle Box中包含pet-shop
应用程序前端的代码。该代码存在于src/
目录中。
前端不使用构建系统(webpack、grunt 等)以尽可能容易上手。应用程序的结构已经存在;我们将填写以太坊特有的功能。这样,您就可以将这些知识应用到您自己的前端开发中。
/src/js/app.js
在文本编辑器中打开。
App = {
web3Provider: null,
contracts: {},
init: async 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 await App.initWeb3();
},
//初始化web3
initWeb3: async function () {
// 我们检查是否使用现代 dapp 浏览器或更新版本的MetaMask(其中ethereum将提供程序注入到window对象中)
if (window.ethereum) {
App.web3Provider = window.ethereum;
try {
// 请求帐户访问
await window.ethereum.enable();
} catch (error) {
// 用户拒绝帐户访问
console.error("User denied account access")
}
}
// 旧版dapp浏览器
else if (window.web3) {
App.web3Provider = window.web3.currentProvider;
}
// 如果未检测到注入的web3实例,则返回Ganache(就我们测试用的)
else {
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}
web3 = new Web3(App.web3Provider);
return App.initContract();
},
//实例化合约
initContract: function () {
$.getJSON('Adoption.json', function (data) {
// 获取必要的合约工件文件,并使用@truffle/contract进行实例化
var AdoptionArtifact = data;
App.contracts.Adoption = TruffleContract(AdoptionArtifact);
// 为我们的合同设置提供商
App.contracts.Adoption.setProvider(App.web3Provider);
// 使用我们的合同取回并标记收养的宠物
return App.markAdopted();
});
return App.bindEvents();
},
bindEvents: function () {
$(document).on('click', '.btn-adopt', App.handleAdopt);
},
//领养宠物并更新 UI
markAdopted: function () {
//收养实例
var adoptionInstance;
App.contracts.Adoption.deployed().then(function (instance) {
adoptionInstance = instance;
//使用call()允许我们从区块链读取数据,而无需发送完整的交易,这意味着我们不必花费任何以太币。
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);
});
},
//处理领养()函数
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();
});
});
在浏览器中与 dapp 交互
准备好ganache和metamask
手动添加网路http://127.0.0.1:7545
启动本地网络服务器:
npm run dev