部署宠物商店到Ganache

    在truffle官网有个 pet-shop宠物商店案例,该案例已经搭建了React部分,我们只需写智能合约和配置环境就行了,具体如下。

1、搭建环境

  • 下载并安装Node(JavaScript运行环境)
  • 用命令安装Truffle(智能合约编译与部署工具)
npm install truffle -g
  • 下载并安装 Ganache(轻量级的以太坊私有链测试节点)

2、下载pet-shop源码

3、新建一个领用宠物的智能合约

    在pet-shop-box\contracts目录下,创建一个合约文件名称为Adoption.sol
//Adoption.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.5.0;

contract Adoption {
    
    
  address[16] public adopters; //address of adopters
  
  //func adopt
  function adopt(uint petId) public returns (uint) {
    
    
	require(petId >= 0 && petId <= 15);
	
	adopters[petId] = msg.sender;
	return petId;
  }
  
  //return adopters
  function getAdopters() public view returns (address[16] memory) {
    
    
	return adopters;
  }
  
}

4、新建一个部署Adoption.sol合约的*.js脚本

    在pet-shop-box\migrations目录下,创建一个名称为2_deploy_Adoption.js文件
//2_deploy_Adoption.js

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

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

5、安装依赖包

    用管理员权限打开CMD,进入pet-shop-box所在的目录,输入如下命令:

npm install

6、配置truffle-config.js里的Ganache地址和端口

  • 先启动Ganache,点击齿轮按钮,进入Ganache的设置界面
  • 找到SERVER栏,如图(1)所示:

图(1) 配置truffle-config.js里的development参数

    将Ganache里的Server页面Host和port参数,拷贝到truffle-config.js的development{ }对应的字段里。

7、修改pet-shop-box\src相关脚本

    7.1 修改pet-shop-box\src\js\App.js,主要是修改initWeb3 function()、initContract functioin()、markAdopted fuction()、handleAdopt funtion(),分别是初始化web3、实例化合约和处理领养,将这4个函数里{}的代码先清空,后填入相关的业务逻辑代码。

    a)在App.js里,填上initWeb3 function()的业务逻辑代码
//initWeb3 function()函数

  initWeb3: async function() {
    
    
    // Modern dapp browsers...
    if (window.ethereum) {
    
    
      App.web3Provider = window.ethereum;
      try {
    
    
        // Request account access
        await window.ethereum.enable();
      } catch (error) {
    
    
        // User denied account access...
        console.error("User denied account access")
      }
    }
    // Legacy dapp browsers...
    else if (window.web3) {
    
    
      App.web3Provider = window.web3.currentProvider;
    }
    // If no injected web3 instance is detected, fall back to Ganache
    else {
    
    
      App.web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');
    }
    web3 = new Web3(App.web3Provider);

    return App.initContract();
  }

    b)在App.js里,填上initContract function()的业务逻辑代码
//initContract function()函数

  initContract: function() {
    
    
    $.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();
  },

    c) 在App.js里,填上markAdopted function()的业务逻辑代码
//markAdopted function()函数

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

    d) 在App.js里,填上handleAdopt function()的业务逻辑代码
//handleAdopt function()函数

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

    7.2 在pet-shop-box\src目录下,添加一个jquery.min.js文件
jquery.min.js v1.12.4 提取码:eqe5

    7.3 在pet-shop-box\src\index.html里修改jquery.min.js的路径,如图(2)所示:


图(2) 修改jquery.min.js路径

8、编译工程,并部署到Ganache

    在CMD黑框框里,切换到pet-shop-box目录,,依次输入如下命令:

truffle console
compile
migrate

    如图(3)所示:


图(3) 编译和部署工程

9、用MetaMask连接Ganache测试节点

    点击MetaMask插件 --> LocalHost 8545 --> 输入Ganache里的MNEMONIC密语 -->恢复即可,如图(4)所示:


图(4)用Ganache里的MNEMNOIC密语,登录MetaMask

10、启动pet-shop-box工程

    回到CMD黑框框,按Ctrl+C两次,退出development模式,输入命令:

npm run dev

    会弹出一个宠物商店的网页界面,然后选中一个宠物,点击下面的[Adopt]按钮,连上MetaMask确认一下,即可领养成功。


图(5)点击[Adopt] 即可领养宠物

11、参考文章

    pet-shop官网

猜你喜欢

转载自blog.csdn.net/sanqima/article/details/109274438