区块链(1)开发环境搭建及Hello World合约展示
区块链(2)以太坊开发框架Truffle教程(Windows)
区块链(3):在以太坊私有链建立节点集群并发生交易
上一篇博客介绍了如何搭建一个私有链的以太坊开发环境,并部署一个简单“hello world”智能合约到区块链上,详情请前往区块链开发环境搭建。
本文进一步介绍区块链的一个主流开发框架Truffle
使用 Truffle需要三个东西,分别如下
Chrome里面的JavaScript引擎(V8)的一个平台,可以很容易的构建快速而具有扩展性的网络程序。Node.js,以前叫TestRPC在开发过程中使用。前往Node.js官方网站下载相应的版本,一路next安装。安装完成后打开命令行窗口,输入node –v 来验证是否安装成功。输入npm –version 来确认node 包管理工具安装成功。npm 是node package manager的简称
Truffle使用npm来安装,如果node是使用installer安装的,系统应该已经将环境变量配置好了,所以在任何路径下都可以使用npm,如果发现不能使用则需要到相应的路径下去执行命令。
在命令行中输入npm –g install truffle 回车。
Ganache CLI的安装仍然使用npm,在命令行中输入npm install -g ganache-cli 回车
完成以上三步则可以开始使用Truffle了
接下来通过官方的一个示例来展示Truffle的具体开发流程
项目背景
一所狗狗收容所想利用区块链来跟踪被收养的狗狗
Truffle Box 可以理解为Truffle 的项目模板
使用在命令行窗口新建文件夹pet-shop-tutorial并导航至其中
mkdir pet-shop-tutorial
cd pet-shop-tutorial
在命令行窗口中使用命令 truffle unbox pet-shop 来创建项目模板 pet-shop。
命令完成后就会在pet-shop-tutorial文件夹下面生成项目文件,如下图所示
contracts/:存放智能合约文件。
migrations/:存放部署智能合约相关的文件。
test/:智能合约测试文件,测试文件可以使用JavaScript或者Solidity编写。
truffle.js:Truffle的配置文件。如果你使用Windows的cmd命令行的话,需要将文件名改为truffle-config.js之类的。
在 contracts/目录下新建文件Adoption.sol。
pragma solidity ^0.4.17;//告诉编译器使用大于0.4.17小于0.5版本的solidity语言
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;
}
}
由于名称冲突,如果你使用的是
CMD命令行,则需要将根目录下的truffle.js文件重命名为truffle-config.js
truffle-config.js文件的内容为
module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// for more about customizing your Truffle configuration!
networks: {
development: {
host: "127.0.0.1",
port: 8545,
network_id: "*" // Match any network id
}
}
};
在命令行中输入truffle compile 如果出现类似于下面的结果,说明编译成功了。
Compiling ./contracts/Migrations.sol...
Compiling ./contracts/Adoption.sol...
Writing artifacts to ./build/contracts
编译成功后,你会在项目的根目录下面发现多了一个build文件夹,里面存放的是智能合约编译后的结果。
我们已经成功编译了我们的项目,现在需要将其部署到区块链中。
要将智能合约部署到区块链中去,自然需要一条区块链了。我们使用Truffle内置的Truffle Dev即可。
导航到truffle-config.js所在目录,在cmd窗口中输入truffle dev,启动一条区块链,默认会生成10个账户,每个账户里有100个以太 坊。默认监听localhost:9545
(我们也可以使用Ganache CLI。 在命令行中输入ganache-cli
启动一条区块链,默认会生成10个账户,每个账户里有100个以太坊。默认监听localhost:8545)
在/migrations目录下新建一个文件2_deploy_contracts.js
var Adoption = artifacts.require("Adoption");
module.exports = function(deployer) {
deployer.deploy(Adoption);
};在命令行中输入truffle migrate,如果发现如下输出,则表示部署成功
Using network 'development'.
Running migration: 1_initial_migration.js Deploying Migrations...
...
0xcc1a5aea7c0a8257ba3ae366b83af2d257d73a5772e84393b0576065bf24aedf
Migrations: 0x8cdaf0cd259887258bc13a92c0a6da92698644c0 Saving
successful migration to network... ...
0xd7bc86d31bee32fa3988f1c1eabce403a1b5d570340a3a9cdba53a472ee8c956
Saving artifacts... Running migration: 2_deploy_contracts.js
Deploying Adoption... ...
0x43b6a6888c90c38568d4f9ea494b9e2a22f55e506a8197938fb1bb6e5eaa5d34
Adoption: 0x345ca3e014aaf5dca488057592ee47305d9b3e10 Saving
successful migration to network... ...
0xf36163615f41ef7ed8f4a8f192149a0bf633fe1a2398ce001bf44c43dc7bdda0
至此,我们已经成功将智能合约部署到了测试用的区块链中,接下来就是测试区块链的正确性,以及与其交互的工作了。
待续
本文以web的方式与智能合约交互,就是我们要创建一个网页,用来与区块链上的智能合约交互。
web3.js 是以太坊提供的一个
Javascript库,它封装了以太坊的JSON RPC API,提供了一系列与区块链交互的Javascript对象和函数,包括查看网络状态,查看本地账户、查看交易和区块、发送交易、编译/部署智能合约、调用智能合约等,其中最重要的就是与智能合约交互的API。
进入/src/js目录下,修改app.js文件如下
1.安装web3
将函数initWeb3里面的注释Replace me...替换为如下代码
```
// 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 = new
Web3(App.web3Provider);
```
2.安装合约
将函数initContract里面的注释Replace me...替换为如下代码
$.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(); });
3.领养宠物
将函数markAdopted里面的注释Replace me...替换为如下代码
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);
});
将函数handleAdopt里面的注释Replace me...替换为如下代码
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;
// Execute adopt as a transaction by sending account
return adoptionInstance.adopt(petId, {from: account});
}).then(function(result) {
return App.markAdopted();
}).catch(function(err) {
console.log(err.message);
});
});
经过以上步骤,我们的第一个DApp就开发完成了,是时候展示一下成果了。
在浏览器中使用
dapp最简单的方式就安装一个叫MetaMask的插件,其支持Chrome与Firefox。
Chrome中安装MetaMask 插件在MetaMask主页中点击Import Existing DEN
4.在Wallet Seed的输入框中输入
candy maple cake sugar pudding cream honey rich smooth crumble sweet treat
输入密码,确认即可。
5.将MetaMask 连接到我们使用Truffle Dev创建的区块链上去。点击MetaMask 左上角的下三角箭头,打开选择项,选择* Custom RPC*
后输入http://127.0.0.1:9545保存
启动本地server
导航到truffle 根目录下面,在cmd窗口中输入npm run dev,本地dev server 将会启动,并使用默认浏览器打开我们的dapp。
在其中一只要领养的宠物下面点击Adopt按钮。
MetaMask会弹出要求你同意此次交易,点击Submit同意此次交易。
你会看到下面的按钮变成了Success,而且不可点击了,因为此宠物已经被领养了。如果按钮没有变化,就主动刷新一下网页。
在MetaMask上面你可以看到此次交易。
至此,我们就完整的建立了自己的第一个DAPP了,我对web开发不是很熟悉,有机会还是要写一篇使用手机APP作为UI来与区块链交互的文章。