在Spectrum测试链用Truffle启动第一个宠物商店Dapp

在光谱链上实现一个Dapp,就是合约部署完之后(有一个我们可以直接与他交互的后端),然后做这个应用层的代码和后端的交互,给DApp加上前端数据交互、读取的界面。

本例以truffle 官方的宠物店demo为例实现光谱链上运行。

开发流程:
1,首先准备并部署开发环境
2,其次编写并部署智能合约
3,最后测试合约并创建交互

开发环境准备

OS:本地环境Mac
开发环境:node.js, npm (node version, v9.11.1 npm version v5.6.0)
编译部署环境:truffle (version 4.1.5, solidity 0.4.21)
光谱测试链:smc (version 0.5.1)

安装开发环境:

npm install -g truffle

安装光谱测试链本地节点:

git clone https://github.com/SmartMeshFoundation/Spectrum.git
make all

启动节点:

./smc --testnet --port 30308 --rpc --rpccorsdomain "*" --rpcaddr "0.0.0.0" --rpcapi db,eth,net,web3,personal,admin,miner,txpool --ws --wsapi admin,eth,mine,debug,personal,txpool,web3,net --wsorigins="*" --wsaddr="0.0.0.0" --datadir /Users/a212/Desktop/Spectrum/build/bin/datadir --rpcport 18545 console

从Truffle box创建项目

ben:Desktop a212$ mkdir petShop
ben:Desktop a212$ cd petShop/
ben:petShop a212$ truffle unbox pet-shop
Downloading...
Unpacking...
Setting up...
Unbox successful. Sweet!

Commands:

  Compile:        truffle compile
  Migrate:        truffle migrate
  Test contracts: truffle test
  Run dev server: npm run dev
ben:petShop a212$ ls
LICENSE         contracts       package.json
box-img-lg.png      migrations      src
box-img-sm.png      node_modules        test
bs-config.json      package-lock.json   truffle.js

truffle框架目录介绍:

contracts/ : 智能合约文件存在这里,后缀.sol (solidity)
migrations/ : 部署脚本
test/ : 测试脚本
truffle.js :truffle的配置文件

修改truffle.js配置文件:

光谱链的端口是18545.

module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  // to customize your Truffle configuration!
  networks: {
    development: {
        host:"127.0.0.1",
        port:18545,
        network_id:"*",
                gas:2000000,
    }
  }
};

遇到的问题:

1,Error: authentication needed: password or unlock
2,Error: Could not find artifacts for MyDapp from any sources

编写智能合约

在 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;
   }

   //retrieve the adopters
   function getAdopters() public view returns (address[16]) {
     return adopters;
   }
}

编译部署合约

确保安装好测试链运行,并且开启另外一个console。
编译合约

 truffle compile
Compiling ./contracts/Adoption.sol...
Compiling ./contracts/Migrations.sol...
Writing artifacts to ./build/contracts

部署合约

1,在 migratios/ 目录内创建新文件 2_deploy_contracts.js 内容如下:

var Adoption = artifacts.require("Adoption");

module.exports = function(deployer) {
   deployer.deploy(Adoption);
};


2,truffle migrate
Using network 'development'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
  ... 0xef22f2f0353a5cabe49fa7a7476cde27e67c49ec7467a9083172f678706637d2
  Migrations: 0x0a78600a15663629b6a70cf5844d92155a239604
Saving successful migration to network...
  ... 0x9e5a22772939ad111bfbee556440db677c3c90c28ddb61862145a7939f39e687
Saving artifacts...
Running migration: 2_deploy_migration.js

测试链节点打包:


INFO [10-18|11:54:43] Submitted contract creation fullhash=0xef22f2f0353a5cabe49fa7a7476cde27e67c49ec7467a9083172f678706637d2 contract=0x0a78600a15663629B6A70cF5844D92155a239604


查看测试链的区块浏览器:
https://chain.smartmesh.io/tx.html?hash=0x70d24956b7627b98415762a2d02c4d71715c244f57838b6c95467e9815b6ed16

测试智能合约

智能合约可以也可以用测试类来进行断言(assert)验证。例如在 test/ 目录内创建新文件 TestAdoption.sol 内容如下:

pragma solidity ^0.4.17;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/Adoption.sol";

contract TestAdoption {
   Adoption adoption = Adoption(DeployedAddresses.Adoption());

   //test adopt() function
   function testUserCanAdoptPet() public {
     uint returnedId = adoption.adopt(8);

     uint expected = 8;

     Assert.equal(returnedId, expected, "Adoption of Pet ID 8 should be recorded.");
   }

   //test retrieve of a single pet owner
   function testGetAdopterAddressByPetId() public {
     //expected owner is this contract
     address expected = this;
     address adopter = adoption.adopters(8);
     Assert.equal(adopter, expected, "owner of pet id 8 should be recorded.");
   }

   //test retrive of all pet owners
   function testGetAdopterAddressByPetIdInArray() public {
     //expected owner is this contract
     address expected = this;
     address[16] memory adopters = adoption.getAdopters();

     Assert.equal(adopters[8], expected, "owner of pet id 8 should be recorded.");
   }
}
truffle test
Using network 'development'.

Compiling ./contracts/Adoption.sol...
Compiling ./test/TestAdoption.sol...
Compiling truffle/Assert.sol...
Compiling truffle/DeployedAddresses.sol...

上面Assert.sol里面有警告,忽略掉。

前端界面与智能合约的交互

用户界面(UI)是前端工作,这里用的javascript。主要文件是app.js,存在目录 /src/js/app.js 中。其实就是web3.js通过RPC与智能合约交互,文件内容如下:

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() {

  /*
     * 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.providers.HttpProvider('http://localhost:7545');
}
web3 = new Web3(App.web3Provider);

   return App.initContract();
 },

 initContract: function() {

  /*
     * 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();
});

   return App.bindEvents();
 },

 bindEvents: function() {
   $(document).on('click', '.btn-adopt', App.handleAdopt);
 },

  /*
     * Replace me...
     */

 markAdopted: function(adopters, account) {
   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: 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;

   // 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);
 });
});
 }

};

$(function() {
 $(window).load(function() {
   App.init();
 });
});

安装配置 lite-server

在解开的目录内,有 bs-config.jscon 和 package.json 两个配置文件,不必要修改。(这里定义了lite server,一会儿浏览器访问dapp用)

命令行启动lite-server:
命令:
npm run dev

npm run dev

> pet-shop@1.0.0 dev /Users/a212/Desktop/petShop
> lite-server

** browser-sync config **
{ injectChanges: false,
  files: [ './**/*.{html,htm,css,js}' ],
  watchOptions: { ignored: 'node_modules' },
  server:
   { baseDir: [ './src', './build/contracts' ],
     middleware: [ [Function], [Function] ] } }
[Browsersync] Access URLs:
 --------------------------------------
       Local: http://localhost:3000
    External: http://192.168.0.171:3000
 --------------------------------------
          UI: http://localhost:3001
 UI External: http://localhost:3001
 --------------------------------------
[Browsersync] Serving files from: ./src
[Browsersync] Serving files from: ./build/contracts
[Browsersync] Watching files...
18.10.18 15:08:26 200 GET /index.html
18.10.18 15:08:26 200 GET /css/bootstrap.min.css
18.10.18 15:08:26 200 GET /js/app.js
18.10.18 15:08:26 200 GET /js/bootstrap.min.js
18.10.18 15:08:27 200 GET /js/web3.min.js
18.10.18 15:08:27 200 GET /js/truffle-contract.js
18.10.18 15:08:33 404 GET /favicon.ico
18.10.18 15:09:58 200 GET /index.html

自动打开宠物店: http://localhost:3000

屏幕快照 2018-10-18 下午4.57.18.png

安装配置MetaMask

与Dapp互动的最容易的方式是通过 MetaMask,Spectrum目前与MetaMask兼容。
(地址:https://metamask.io/

1、在浏览器内安装MetaMask
2、装好后,以Chrome浏览器插件形式存在
3、同意,接受条款
4、如下图,点击"Import Existing DEN"

屏幕快照 2018-10-19 上午9.43.48.png
屏幕快照 2018-10-19 上午9.44.13.png
屏幕快照 2018-10-19 上午9.45.02.png

发送交易:


屏幕快照 2018-10-19 上午9.48.48.png
屏幕快照 2018-10-19 上午9.48.59.png

区块浏览器:
https://chain.smartmesh.io/tx.html?hash=0x39521ea0b445403cf59142c1b7c3b10b3baa04ae20603c5c24a098edd4041732

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容