truffle官方demo--Petshop完整实现和交易

1. 环境环境

首先nodejs,npm
安装truffle,ganache

sudo npm install -g truffle
sodu npm install -g ganache-cli

查了下,好像还有可视化的ganache,马上下载尝试


image.png

根据官方网站
下载petshop

mkdir petshop
cd petshop
truffle unbox pet-shop
truffle develop
出现 >
compile
migrate

其中出现warning没关系


image.png

运行看看

npm run dev

就会自动出现petshop


image.png

-- 完--

2. 未完待续

就这么完了吗?分析代码,首先查看contract为空的。。看官网


image.png

原来还有tuturial啊
首先在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;
    }

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

然后在migrations文件夹部署上,新建2_deploy_contracts.js

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

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

这个时候就该打开ganache,

然后运行

truffle compile
truffle migrate
image.png
咦我的eth少了0.06

3. 测试合约请看教程。。

4. 开始写js逻辑了,

找到js文件夹的app.js, 在initWeb3的明显位置添加

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

再在initContract的明显位置添加

$.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();
});
image.png

还有一处要更新,在handleAdopt

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

重新compile和migrate,但碰到错误


image.png

猜想我是重新打开了ganache,于是用

truffle migrate --reset

解决正常


image.png

5. metamask

下面教大家配置metamask
首先下载chrome钱包插件


image.png

对应ganache网址在setting设置


image.png

并import 第一个账号对应的私钥

image.png

就会出现账号和余额

6. 运行

终于到最激动人心的时刻了

npm run dev

在此界面点击adopt


image.png

虽然demo是发送了0 eth,只用了gas (为什么可以自己设)
我们已经成功完成了链上交易


image.png

就在这个基础上继续开发吧!!!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容