以太坊开发测试(7)Truffle MetaCoin 案例JS及部署源码分析

本文详细解析了MetaCoin DApp的前端HTML、CSS和JavaScript代码,以及后端智能合约的交互流程。从index.html的布局到index.js的业务逻辑,再到智能合约的部署和调用,全面展示了DApp的开发过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分析思路即为从前端到后台代码的路线

第一个文件 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]});
};
//设定第一个账户来部署合约

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值