您的位置:首页 > 其它

区块链(2)以太坊开发框架Truffle教程(Windows)

2018-02-11 18:03 453 查看
上一篇博客介绍了如何搭建一个私有链的以太坊开发环境,并部署一个简单“hello world”智能合约到区块链上,详情请前往区块链开发环境搭建

本文进一步介绍区块链的一个主流开发框架Truffle

环境搭建

使用 Truffle需要三个东西,分别如下

Nodejs :是一个基于google浏览器
Chrome
里面的
JavaScript
引擎(V8)的一个平台,可以很容易的构建快速而具有扩展性的网络程序。

Truffle :以太坊开发框架

Ganache CLI:是在本地使用内存模拟的一个以太坊环境,其基于
Node.js
,以前叫TestRPC在开发过程中使用。

Node 安装

前往
Node.js
官方网站下载相应的版本,一路next安装。安装完成后打开命令行窗口,输入
node –v
来验证是否安装成功。输入
npm –version
来确认node 包管理工具安装成功。npm 是
node package manager
的简称

Truffle 安装

Truffle使用npm来安装,如果
node
是使用installer安装的,系统应该已经将环境变量配置好了,所以在任何路径下都可以使用
npm
,如果发现不能使用则需要到相应的路径下去执行命令。

在命令行中输入
npm –g install truffle
回车。

Ganache CLI 安装

Ganache CLI的安装仍然使用npm,在命令行中输入
npm install -g ganache-cli
回车

完成以上三步则可以开始使用Truffle

接下来通过官方的一个示例来展示Truffle的具体开发流程

项目背景

一所狗狗收容所想利用区块链来跟踪被收养的狗狗

使用Truffle Box 创建一个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


至此,我们已经成功将智能合约部署到了测试用的区块链中,接下来就是测试区块链的正确性,以及与其交互的工作了。

测试智能合约

待续

创建UI界面与智能合约交互

本文以
web
的方式与智能合约交互,就是我们要创建一个网页,用来与区块链上的智能合约交互。

web3.js 是以太坊提供的一个
Javascript
库,它封装了以太坊的
JSON RP
e2bc
C 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

在浏览器中使用
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
保存

使用dapp

启动本地server

导航到truffle 根目录下面,在cmd窗口中输入
npm run dev
,本地dev server 将会启动,并使用默认浏览器打开我们的dapp。



在其中一只要领养的宠物下面点击
Adopt
按钮。

MetaMask会弹出要求你同意此次交易,点击
Submit
同意此次交易。

你会看到下面的按钮变成了
Success
,而且不可点击了,因为此宠物已经被领养了。如果按钮没有变化,就主动刷新一下网页。

在MetaMask上面你可以看到此次交易。

至此,我们就完整的建立了自己的第一个
DAPP
了,我对web开发不是很熟悉,有机会还是要写一篇使用手机APP作为UI来与区块链交互的文章。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息