以太坊開發測試(7)Truffle MetaCoin 案例JS及部署源碼分析

分析思路即爲從前端到後臺代碼的路線

第一個文件 index.html

<!DOCTYPE html>
<html>
  <head>
    <title>MetaCoin | Truffle Webpack Demo w/ Frontend</title> //標題
  </head>
  <style>    
    input {
      display: block;
      margin-bottom: 12px;
    }
  </style>
  <body>
    <h1>MetaCoin — Example Truffle Dapp</h1>
    <p>You have <strong class="balance">loading...</strong> META</p>  //class 指對應JS文件中的內容

    <h1>Send MetaCoin</h1>

    <label for="amount">Amount:</label>
    <input type="text" id="amount" placeholder="e.g. 95" /> //轉賬數額輸入

    <label for="receiver">To address:</label>   //轉賬地址輸入
    <input
      type="text"
      id="receiver"
      placeholder="e.g. 0x93e66d9baea28c17d9fc393b53e3fbdd76899dae"
    />

    <button onclick="App.sendCoin()">Send MetaCoin</button>  //點擊事件,調用App.sendCoin() 方法

    <p id="status"></p>
    <p>
      <strong>Hint:</strong> open the browser developer console to view any
      errors and warnings.
    </p>
    <script src="index.js"></script>   //相對應的JS文件
  </body>
</html>

對應的第二個文件index.js

import Web3 from "web3";
import metaCoinArtifact from "../../build/contracts/MetaCoin.json";
//連接編譯好的智能合約

const App = {             //const 聲明常量 let 聲明代碼塊中的局部變量
  web3: null,   
  account: null,
  meta: null,

  start: async function() {  //聲明異步函數,async 異步關鍵字,返回一個Promise對象
    const { web3 } = this;   //設定本對象指針

    try {
      // 獲得智能合約實例
      const networkId = await web3.eth.net.getId();   //獲得網絡ID
      const deployedNetwork = metaCoinArtifact.networks[networkId];
      this.meta = new web3.eth.Contract( //設置合約與網絡地址
        metaCoinArtifact.abi,
        deployedNetwork.address,
      );

      // 獲得賬戶,設置當前賬戶爲第一個賬戶
      const accounts = await web3.eth.getAccounts();
      this.account = accounts[0];

      this.refreshBalance();
    } catch (error) {
      console.error("Could not connect to contract or chain.");
    }
  },

  refreshBalance: async function() {   //刷新賬戶餘額
    const { getBalance } = this.meta.methods;  //獲取合約中的返回餘額方法
    const balance = await getBalance(this.account).call(); //調用該方法
     
    const balanceElement = document.getElementsByClassName("balance")[0];
    //獲取頁面名稱變量
    balanceElement.innerHTML = balance; //設置屬性

  },

  sendCoin: async function() {          //轉賬方法,異步方法
    const amount = parseInt(document.getElementById("amount").value);
    //從前端獲取轉賬數額
    const receiver = document.getElementById("receiver").value;
    //從前端獲取轉賬ID
    this.setStatus("Initiating transaction... (please wait)");
     
    const { sendCoin } = this.meta.methods; //設置合約中的方法
    await sendCoin(receiver, amount).send({ from: this.account }); //調用方法等待返回值

    this.setStatus("Transaction complete!"); //更新狀態
    this.refreshBalance();  //刷新賬戶餘額
  },

  setStatus: function(message) {  //設置狀態信息的函數,上文中的更新狀態即爲這個方法
    const status = document.getElementById("status");
    status.innerHTML = message;
  },
};

window.App = App; //窗口設置

window.addEventListener("load", function() {  //設置界面監聽
  if (window.ethereum) {
    // use MetaMask's provider
    App.web3 = new Web3(window.ethereum);
    window.ethereum.enable(); // get permission to access accounts
  } else {
    console.warn(
      "No web3 detected. Falling back to http://127.0.0.1:8545. You should remove this fallback when you deploy live",
    );
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    App.web3 = new Web3( //連接http提供者
      new Web3.providers.HttpProvider("http://127.0.0.1:8545"),
    );
  }
App.start();
});

migrations/ 1_init_migration.js   2_deploy_contracts.js

const Migrations = artifacts.require("Migrations");

module.exports = function(deployer,network,accounts) {
  deployer.deploy(Migrations,{from: accounts[0]});
};
//由第一個賬戶來部署合約

 

const ConvertLib = artifacts.require("ConvertLib");
const MetaCoin = artifacts.require("MetaCoin");

module.exports = function(deployer,network,accounts) {
  deployer.deploy(ConvertLib,{from: accounts[0]});
  deployer.link(ConvertLib, MetaCoin);
  deployer.deploy(MetaCoin,{from:accounts[0]});
};
//設定第一個賬戶來部署合約

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章