编写测试用例:
放在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());
function testUserCanAdoption() public {
uint returnedId = adoption.adopt(8);
uint expected = 8;
Assert.equal(returnedId,expected,"Adoption of pet Id 8 should be recorded");
}
function testGetAdopterAddressByPetId() public{
address expected = this;
address adopter = adoption.adopters(8);
Assert.equal(adopter,expected,"Owner of pet Id 8 should be recorded");
}
function testGetAdopterAddressByPetIdArray()public{
address expected = this;
address[16] memory adopters = adoption.getAdopters();
Assert.equal(adopters[8],expected,"Owner of pet Id 8 should be recorded");
}
}
在cmd中:
C:\Users\Tai Park\pet-shop>truffle test
Using network 'development'.
Compiling .\contracts\Adoption.sol...
Compiling .\test\TestAdoption.sol...
Compiling truffle/Assert.sol...
Compiling truffle/DeployedAddresses.sol...
TestAdoption
√ testUserCanAdoption (125ms)
√ testGetAdopterAddressByPetId (142ms)
√ testGetAdopterAddressByPetIdArray (89ms)
3 passing (1s)
初始化web环境:
在cmd中:
C:\Users\Tai Park\pet-shop>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (pet-shop) pet-shop
version: (1.0.0)
description:
entry point: (truffle-config.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to C:\Users\Tai Park\pet-shop\package.json:
{
"name": "pet-shop",
"version": "1.0.0",
"description": "",
"main": "truffle-config.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this ok? (yes) yes
C:\Users\Tai Park\pet-shop>npm install lite-server
新建文件bs-config.json告诉server去哪里找文件:
{
"server":{
"baseDir":["./src","./build/contracts"]
}
}
在package.json中的"scripts"下加一行:
"dev":"lite-server",
新建一个文件夹src存放网页源文件
在src下新建index.html,并随便写文字测试
Hello
cmd中:
C:\Users\Tai Park\pet-shop>npm run dev
> pet-shop@1.0.0 dev C:\Users\Tai Park\pet-shop
> 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.1.107:3000
--------------------------------------
UI External: http://192.168.1.107:3001
--------------------------------------
[Browsersync] Serving files from: ./src
[Browsersync] Serving files from: ./build/contracts
[Browsersync] Watching files...
18.08.07 14:34:57 404 GET /favicon.ico
web环境已经搭建好了。
页面编写:
cmd中下载资源:
C:\Users\Tai Park\pet-shop>cd ..
C:\Users\Tai Park>mkdir pet_shop_2
C:\Users\Tai Park>cd pet_shop_2
C:\Users\Tai Park\pet_shop_2>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
把pet_shop_2中的css/fonts/images/js/pets.json拷过来放到src下。
编写index.html:
<<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Pet Shop</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script src="main.js"></script>
</head>
<body>
</body>
</html>>
cmd中:
C:\Users\Tai Park\pet_shop_2>npm run dev
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pete's Pet Shop</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-sm-push-2">
<h1 class="text-center">Pete's Pet Shop</h1>
<hr/>
<br/>
</div>
</div>
<div id="petsRow" class="row">
<!-- PETS LOAD HERE -->
</div>
</div>
<div id="petTemplate" style="display: none;">
<div class="col-sm-6 col-md-4 col-lg-3">
<div class="panel panel-default panel-pet">
<div class="panel-heading">
<h3 class="panel-title">Scrappy</h3>
</div>
<div class="panel-body">
<img alt="140x140" data-src="holder.js/140x140" class="img-rounded img-center" style="width: 100%;" src="https://animalso.com/wp-content/uploads/2017/01/Golden-Retriever_6.jpg" data-holder-rendered="true">
<br/><br/>
<strong>Breed</strong>: <span class="pet-breed">Golden Retriever</span><br/>
<strong>Age</strong>: <span class="pet-age">3</span><br/>
<strong>Location</strong>: <span class="pet-location">Warren, MI</span><br/><br/>
<button class="btn btn-default btn-adopt" type="button" data-id="0">Adopt</button>
</div>
</div>
</div>
</div>
<script src="https://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/web3.min.js"></script>
<script src="js/truffle-contract.js"></script>
<script src="js/app.js"></script>
</body>
</html>
编写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() {
if(typeof web3 !== 'undefined'){
App.web3Provider = web3 = web3.currentProvider;
}else{
App.web3Provider = new Web3.prviders.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);
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 apotionInstance;
App.contracts.Adoption.deployed().then(function(instance){
apotionInstance = instance;
return apotionInstance.getAdopters.call();
}).then(function(adopters){
for(i = 0; i < adopters.length;i++){
if(adopters[i] !== '0x00000000000000000000000000000000'){
$('.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'));
web3.eth.getAccounts(function(error,accounts){
var account = accounts[0];
var apotionInstance;
App.contracts.Adoption.deployed().then(function(instance){
apotionInstance = instance;
return apotionInstance.adopt(petId,{from:account});
}).then(function(result){
return App.markAdopted();
}).catch(function(err){
console.log(err.message);
})
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});
在cmd中启动服务器:
C:\Users\Tai Park\pet_shop_2>npm run dev
MetaMask->Custom RPC->HTTP://127.0.0.1:7545
MetaMask->import accounts->Ganache中Show Keys->粘贴在MeatMask中