以太坊(8)truffle ganache dapp 宠物店(pet-shot)--mac

本章内容:通过truffle ganache实现dapp应用——宠物店;

                     官网的操作步骤:http://truffleframework.com/tutorials/pet-shop

准备条件:

     1. truffle

     2. ganache

     3.  MetaMask  

       4. lite-server ( 前面我没有介绍,可以百度下了解下)

    .... 其他的基础服务我就不再一一解释安装可以看前面的章节;

操作步骤:

    1.  准备pet-shot

            mkdir dapp

            truffle unbox pet-shop

   完成后可以看到下面的文件:


    2. 编写代码(不熟悉第二部的可以看上一章节)

        2.1 编写 Adoption.sol

pragma solidity ^0.4.17;

contract Adoption {
  address[16] public adopters;  // 保存领养者的地址
  /**func: 领养宠物 para: 领养宠物ID */
  function adopt(uint petId) public returns (uint) {  
    require(petId >= 0 && petId <= 15);  // 确保id在数组长度内
    adopters[petId] = msg.sender;        // 保存调用这地址 
    return petId; //返回当前宠物ID

  }
  // 返回领养者
  function getAdopters() public view returns (address[16]) {
    return adopters;
  }

}


2.2 migrations添加 2_deploy_contracts.js

  

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

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

3. 启动ganache(这是使用ganache提供的测试链)

   3.1 配置truffle.js 连接ganache链

module.exports = {

  // See <http://truffleframework.com/docs/advanced/configuration>

  // for more about customizing your Truffle configuration!

  networks: {

    development: {

      host: "127.0.0.1",

      port: 7545,

      network_id: 5777 // Match any network id

    }

  }

};


4. 编译、部署、测试 


4.1 truffle compile

4.2 truffle migrate

4.3 truffle test


5. 创建用户接口和智能合约交互

    我们已经编写和部署及测试好了我们的合约,接下我们为合约编写UI,让合约真正可以用起来,修改src/js/app.js;

    5.1  修改 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);
 
 
5.2 修改 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();
});

return App.bindEvents();


5.3 修改 markAdopted 函数,替换注释:

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

5.4 修改 handleAdopt 函数,替换注释:

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

6. 安装 MetaMask

与Dapp互动的最容易的方式是通过 MetaMask

(地址:https://metamask.io/)

  • 1、在浏览器内安装MetaMask

  • 2、装好后,以Chrome浏览器插件形式存在

  • 3、同意,接受条款

  • 4、如下图,点击"Import Existing DEN" 

image

  • 5、返回 ganache 的主界面,在 Accounts 下有一行12个单词的助记词,如下图

image

  • 6、复制助记词,粘贴到 MetaMask 界面中的 Wallet Seed 文本框中

  • 7、设置一个密码,点击 OK

  • 8、点击 MetaMask 左上角的 Main Network ,点击 Custom RPC

  • 9、在 New RPC URL 中输入 “http://127.0.0.1:7545”

  • 10、返回 MetaMask 主界面,可以看到账户信息

上面的第六步碰到第二个坑,这里的助记词一定用你的 ganache 私链上的,否则 MetaMask 钱包无法链接到本地的私链,因此无法显示余额

7. 安装 lite-server

  npm install --save-dev lite-server


8. 启动

   npm run dev


如果看到下面,恭喜你成功的了解了整个开发流程:




8. 现在领养一直宠物看看,当我们点击Adopt时,MetaMask会提示我们交易的确认,如图:


确认后:

然后再去ganache确认,你能看到区块的信息,到这里是不是很爽:




好了,本章到此结束,下章见;

猜你喜欢

转载自blog.csdn.net/weixin_41806245/article/details/80271310