truffle官网demo TUTORIALTOKEN

项目地址:https://www.trufflesuite.com/boxes/tutorialtoken

项目结构

truffle官网demo TUTORIALTOKEN

  • package.json配置文件
{
  "#name": "定义项目的名称,版本",
  "name": "tutorialtoken",
  "version": "1.0.0",
  "description": "",
  "main": "truffle-config.js",
  "directories": {
    "test": "test"
  },
  "#scripts": "定义可执行的脚本,在执行项目的时候npm run dev,这个dev取决于配置的这个名字",
  "scripts": {
    "//":"lite-server,可以用来搭建本地server服务器,默认读取bs-config.json文件",
    "dev": "lite-server",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "#lite-server": "lite-server,可以用来搭建本地server服务,默认读取bs-config.json",
    "lite-server": "^2.3.0"
  }
}
  • bs-config.json配置文件
{
  "//":"将端口变为4000",
  "port":"4000",
  "server": {
    "baseDir": ["./src", "./build/contracts"]
  }
}

  • app.js

    //APP就是一个json对象,里面定义所有逻辑和待调用的函数;
    App = {
      //定义了两个变量
      web3Provider: null,//合约要连接的私有链或者公有链的地址
      contracts: {},//合约的实例
    //定义了一个初始化函数
      //  页面生成后执行init对象
      init: function() {
        return App.initWeb3();
      },
    //实例化了web3js 对象
      initWeb3: function() {
        // Initialize web3 and set the provider to the testRPC.
        if (typeof web3 !== 'undefined') {
          //上个语句的意思就是,当前有私有链就返回私有链的信息
          App.web3Provider = web3.currentProvider;//查看当前连接的哪条私有链
        } else {
          // 来手动连接要连接的私有链地址
          App.web3Provider = new Web3.providers.HttpProvider('http://127.0.0.1:9545');
        }
          //创建web3对象,才能调用web3 api
        web3 = new Web3(web3.currentProvider);
        return App.initContract();
      },
    //初始化智能合约
      initContract: function() {
        //获取json格式的文件 缺少TutorialToken.sol
        $.getJSON('TutorialToken.json', function(data) {
          // Get the necessary contract artifact file and instantiate it with truffle-contract.
          var TutorialTokenArtifact = data;
          //获取json文件中的合约名称
          App.contracts.TutorialToken = TruffleContract(TutorialTokenArtifact);
    
          // Set the provider for our contract.
          App.contracts.TutorialToken.setProvider(App.web3Provider);
    
          // Use our contract to retieve and mark the adopted pets.
          return App.getBalances();
        });
    
        return App.bindEvents();
      },
    //绑定前端的事件
      bindEvents: function() {
        $(document).on('click', '#transferButton', App.handleTransfer);
      },
    //实现转账功能
      handleTransfer: function(event) {
        event.preventDefault();
        //获取目标账户和转账金额
        var amount = parseInt($('#TTTransferAmount').val());
        var toAddress = $('#TTTransferAddress').val();
    
        console.log('Transfer ' + amount + ' TT to ' + toAddress);
    
        //存储实例化的合约
        var tutorialTokenInstance;
    
        web3.eth.getAccounts(function(error, accounts) {
          if (error) {
            console.log(error);
          }
          //默认第一个账户
          var account = accounts[0];
    
          //通过合约名词实例化智能合约
          App.contracts.TutorialToken.deployed().then(function(instance) {
            tutorialTokenInstance = instance;
            //补充transfer函数 转账
            return tutorialTokenInstance.transfer(toAddress, amount, {from: account, gas: 100000});
          }).then(function(result) {
            alert('Transfer Successful!');
            return App.getBalances();
          }).catch(function(err) {
            console.log(err.message);
          });
        });
      },
    //查询余额
      getBalances: function() {
        console.log('Getting balances...');
    
        var tutorialTokenInstance;
    
        web3.eth.getAccounts(function(error, accounts) {
          if (error) {
            console.log(error);
          }
    
          var account = accounts[0];
    
          App.contracts.TutorialToken.deployed().then(function(instance) {
            tutorialTokenInstance = instance;
            //补充balanceOf函数 余额查询
            return tutorialTokenInstance.balanceOf(account);
          }).then(function(result) {
            console.info(result);
            balance = result.c[0];
    
            $('#TTBalance').text(balance);
          }).catch(function(err) {
            console.log(err.message);
          });
        });
      }
    
    };
    
    $(function() {
      $(window).load(function() {
        App.init();
      });
    });
    
    
  • OpenZeppelin

C:\Users\28694\Desktop\token\token>cnpm install openzeppelin-solidity

在 /contracts 目录下创建 TutorialToken.sol

pragma solidity ^0.5.0;

import 'openzeppelin-solidity/contracts/token/ERC20/ERC20.sol';

// 使用is 來繼承ERC20合約
contract TutorialToken is ERC20 {

    string public name = 'TutorialToken';
    // 代币符号
    string public symbol = 'TT';
    //代币精度
    uint public decimals = 2;
    // 发行代币的总数量
    uint public INITIAL_SUPPLY = 12000;

    //构造函数
    construct() public {
      _mint(msg.sender,INITIAL_SUPPLY);
    }

    function () {
      totalSupply = INITIAL_SUPPLY;
      balances[msg.sender] = INITIAL_SUPPLY;
    }
}


创建迁移文件 2_initial_migration.js

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

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

部署操作

C:\Users\28694\Desktop\token\token>truffle develop
C:\Users\28694\Desktop\token\token>migrate

报错

truffle(develop)> deploy --reset

Compiling your contracts...
===========================
> Compiling .\contracts\Migrations.sol
> Compiling .\contracts\TutorialToken.sol
> Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol

openzeppelin-solidity/contracts/token/ERC20/ERC20.sol:85:45: ParserError: Expected '{' but got reserved keyword 'override'
    function decimals() public view virtual override returns (uint8) {
                                            ^------^

Compilation failed. See above.

openzeppelin版本问题 重新安装2.0.0版本(未解决)

上一篇:Web3.js查询以太币和代币余额以及转账


下一篇:dapp开发总览