【區塊鏈】Truffle 部署和測試

Truffle 部署和測試


本文主要參考:herehere,由於參考的這篇文章版本有些舊了,因此是根據比較新的版本寫的。javascript

1、合約部署

一、 首先初始化環境php

truffle init

二、開啓testrpcjava

testrpc  //另開窗口

三、部署合約web

a. 編寫合約代碼,保存到contracts/YourContractName.sol文件app

例如:Conference.sol
pragma solidity ^0.4.4;

contract Conference {  // can be killed, so the owner gets sent the money in the end

    address public organizer;
    mapping (address => uint) public registrantsPaid;
    uint public numRegistrants;
    uint public quota;

    event Deposit(address _from, uint _amount); // so you can log the event
    event Refund(address _to, uint _amount); // so you can log the event

    function Conference() {
        organizer = msg.sender;
        quota = 500;
        numRegistrants = 0;
    }

    function buyTicket() payable public {
        if (numRegistrants >= quota) {
            throw; // throw ensures funds will be returned
        }
        registrantsPaid[msg.sender] = msg.value;
        numRegistrants++;
        Deposit(msg.sender, msg.value);
    }

    function changeQuota(uint newquota) public {
        if (msg.sender != organizer) { return; }
        quota = newquota;
    }

    function refundTicket(address recipient, uint amount) public {
        if (msg.sender != organizer) { return; }
        if (registrantsPaid[recipient] == amount) {
            address myAddress = this;
            if (myAddress.balance >= amount) {
                recipient.transfer(amount);
                Refund(recipient, amount);
                registrantsPaid[recipient] = 0;
                numRegistrants--;
            }
        }
        return;
    }

    function destroy() {
        if (msg.sender == organizer) { // without this funds could be locked in the contract forever!
            suicide(organizer);
        }
    }
}

b. 刪除原有的兩個合約文件ide

MetaCoin.sol 和 ConvertLib.sol

注意: Migrations.sol 不要刪除

c. 修改migrations/2_deploy_contracts文件svg

var Conference = artifacts.require("./Conference.sol");

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

d. 編譯post

truffle compile

e. 部署測試

truffle migrate 或 truffle migrate --reset

2、測試

一、刪除test/metacoin.jsui

二、增長conference.js文件

a. 測試初始

var Conference = artifacts.require("./Conference.sol");

contract('Conference', function(accounts) {

  var Quato;  //限制人數爲500
  var NumRegistrants;  //註冊的人數剛開始爲應該爲0
  var Organizer; //組織者地址應該正確
  var organizer_address = accounts[0];


  it("Initial conference settings should match", function() {

    return Conference.deployed().then(function(instance){
        meta = instance;
        return meta.quota.call();
    }).then(function(quota){
        Quato = quota;
        return meta.organizer.call();
    }).then(function(organizer){
        Organizer = organizer;
        return meta.numRegistrants.call();
    }).then(function(numRegistrants){
        NumRegistrants = numRegistrants;

        assert.equal(Quato, 500, "Quota doesn't match!");
        assert.equal(numRegistrants, 0, "Registrants should be zero!");
        assert.equal(Organizer, organizer_address, "Owner doesn't match!");
    });

  });

});
顯示結果:
prodeMacBook-Pro:pc6 pro$ truffle test
Using network 'development'.

Compiling ./contracts/Conference.sol...

Contract: Conference
    ✓ Initial conference settings should match (83ms)

1 passing (107ms)

b.測試交易

//測試交易
  it("Should let you buy a ticket", function() {

      var user_address = accounts[1];
      var ticketPrice = web3.toWei(.05, 'ether');
      var initialBalance;  //用戶初始餘額
      var newBalance;   //用戶購買以後餘額
      var newNumRegistrants;  //買票人數
      var userPaid;  //付款的金額
      var difference;

      return Conference.deployed().then(function(instance){
            meta = instance;
            return meta.getBalance.call(user_address);
      }).then(function(balance){
            initialBalance = balance.toNumber();  //初始金額
            return meta.buyTicket({from: user_address, value: ticketPrice});  //買票操做
      }).then(function(){
            return meta.getBalance.call(user_address);
      }).then(function(balance){
            newBalance = balance.toNumber();  //買票以後餘額
            difference = initialBalance - newBalance;
            return meta.numRegistrants.call();
      }).then(function(numRegistrants){
          newNumRegistrants = numRegistrants;
          return meta.registrantsPaid.call(user_address);
      }).then(function(registrantsPaid){
            userPaid = registrantsPaid.toNumber();

            assert.equal(userPaid, ticketPrice, "Sender's paid but is not listed");
            assert.equal(difference, ticketPrice, "Difference should be what was sent");
            assert.equal(newNumRegistrants, 1, "there should be 1 registrant");
      });
  });
這裏碰到了問題,實際上我獲得的結果是:

prodeMacBook-Pro:pc6 pro$ truffle test
Using network 'development'.

Compiling ./contracts/Conference.sol...

  Contract: Conference
    ✓ Initial conference settings should match (79ms)
    1) Should let you buy a ticket

    Events emitted during test:
    ---------------------------

    Deposit(_from: 0xd19b5f640c058856bb2f2e2f75454afa2173d2f8, _amount: 50000000000000000)

    ---------------------------

  1 passing (240ms)
  1 failing

  1) Contract: Conference Should let you buy a ticket:
     AssertionError: Difference should be what was sent: expected 56320100000002050 to equal '50000000000000000'
      at test/conference.js:62:20
      at process._tickCallback (internal/process/next_tick.js:109:7)
 //測試沒經過。。我也以爲很奇怪。待解決。。。