区块链 | 通过 Truffle示例项目pet-shop实现智能合约与前端页面交互



目录


说明

  • Win10Pro_1809
  • 项目路径不要有中文.
  • 命令输入使用的是git bash推荐 ,代码编辑器用的是VS Code推荐.
  • 官方教程
    PetShop

1. 环境搭建

1. Node.js(自带npm和node的安装)

2. Git

3. Ganache

  • 快速搭建私有链环境

4. 谷歌浏览器

5. node_moudules

  • truffle
    npm install -g truffle
    testrpc -version

  • solc
    npm install -g solc


2. 使用Truffle Box创建Truffle项目

mkdir demo
cd demo
truffle unbox pet-shop


3. 写智能合约

进入contracts文件夹,并新建Adoption.sol

pragma solidity ^0.4.24;

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] memory) {
        return adopters;
    }
}

注意:

  • contracts中Migrations.sol的Solc版本需要和你的合约一致.

4. 编译智能合约

  • 编辑truffle-config.js,主要是添加编译器的solc版本
  compilers: {
    solc: {
      version: "0.4.25"
    }
  }
};
  • 编译合约
    truffle compile

5. 部署智能合约

  • 进入migrations文件夹,新建2_deploy_contracts.js
var Adoption = artifacts.require("Adoption");

module.exports = function(deployer) {
  deployer.deploy(Adoption);
};
  • 打开运行Ganache,选择QUICKSTART

  • 部署合约
    truffle migrate


6. 测试智能合约

  • 进入test文件夹,新建TestAdoption.sol
pragma solidity ^0.4.24;

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

contract TestAdoption {
     // The address of the adoption contract to be tested
     Adoption adoption = Adoption(DeployedAddresses.Adoption());

     // The id of the pet that will be used for testing
     uint expectedPetId = 8;

     //The expected owner of adopted pet is this contract
     address expectedAdopter = address(this);

     // Testing the adopt() function
     //测试adopt()函数
     function testUserCanAdoptPet() public {
          uint returnedId = adoption.adopt(expectedPetId);
          Assert.equal(returnedId, expectedPetId, "Adoption of the expected pet should match what is returned.");
    }

     // Testing retrieval of a single pet's owner
     //测试单个宠物主人的检索
     function testGetAdopterAddressByPetId() public {
          address adopter = adoption.adopters(expectedPetId);
          Assert.equal(adopter, expectedAdopter, "Owner of the expected pet should be this contract");
    }

     // Testing retrieval of all pet owners
     //测试所有宠物主人的检索
     function testGetAdopterAddressByPetIdInArray() public {
          // Store adopters in memory rather than contract's storage
          address[16] memory adopters = adoption.getAdopters();
          Assert.equal(adopters[expectedPetId], expectedAdopter, "Owner of the expected pet should be this contract");
    }
}
  • 运行测试
    truffle test

7. 创建用户界面以与智能合约进行交互

提示:

  • 前端代码在src文件夹中.
  • 编辑src/js中的app.js即替换对应功能的代码内容
  • initWeb3实例化web3
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:7545');
    }
    web3 = new Web3(App.web3Provider);
    return App.initContract();
  },
  • initContract实例化合同
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();
  },
  • markAdopted获取被采用的宠物并更新UI
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处理adopt()函数
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);
       });
   });
  }

8. 安装并配置MetaMask

  • 下载MetaMask的谷歌插件
下载方式 网址
官方地址 https://metamask.io/
云盘分享 https://pan.baidu.com/s/11-zbNit4JMTGfNsZqJhqBwwucz
  • 安装和配置MetaMask

  • Metamask配置界面
    地址:chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/home.html#

提示:

  • 地址直接复制到浏览器地址栏打开,直接打开无效.

http://127.0.0.1:7545

提示:

  • 参考教程

9. 安装和配置lite-server

  • 编辑bs-config.json
{
  "server": {
    "baseDir": ["./src", "./build/contracts"]
  }
}

10. 使用Dapp

npm run dev

  • 允许连接
  • Dapp前端页面
  • 演示

更新中......


你可能感兴趣的:(区块链 | 通过 Truffle示例项目pet-shop实现智能合约与前端页面交互)