Truffle

在 Truffle 和 testrpc 上使用 Mocha 進行測試時跳過塊?

  • September 24, 2018

我有一份契約,要求事情只發生在某些區塊號上。我想知道是否有辦法“跳過”一組塊?

要跳過塊,請創建一個簡單的合約,該合約具有需要交易的功能。

pragma solidity ^0.4.0; 
// file: BlockMinder.sol

// used to "waste" blocks for truffle tests
contract BlockMiner {
   uint blocksMined;

   function BlockMiner(){
       blocksMined = 0;
   }

   function mine() {
      blocksMined += 1;
   }
}

部署合約後(例如在 中migrations/2_migrations_contracts.js

然後,您可以像這樣創建一個實用程序 js 模組

// file: blockminer.sol
var BlockMiner = artifacts.require("./BlockMiner.sol");

var instance = {};

/**
* Run through blocks (e.g. so that block number will be greater than target block)
* @param {address} addr, the address of the user who is transacting
* @param {number}  numBlocksToMine - how far to move the block count
* @return Function
*/
instance.mineBlocks = function(addr, numBlocksToMine) {
 return function () {
   return new Promise(function (resolve) {
     BlockMiner.deployed().then(function (blockMiner) {
       var miners = [];
       for (var ii = 0; ii < numBlocksToMine; ii++) {
         miners.push(blockMiner.mine({from: addr}));
       }
       return Promise.all(miners).then(resolve);
     });
   });
 }
};

module.exports = instance;

然後在你的測試中

// file: mytest.js

const blockMiner = require('../testutil/blockminer');
contract('FooBar', function(accounts) {
  var myContract;
  it('foos the bar', function() {
     return MyContract.deployed().then(function(instance) {
        myContract = instance;
        return myContract.doSomething();
        // mine aka "skip" 42 blocks
     }).then(blockMiner.mineBlocks(accounts[0], 42)).then(function() {
        return myContract.doSomethingMuchLater();
     });
  });
});

我使用了as jsonrpc呼叫的evm_mine 方法web3.currentProvider.sendAsync,不需要部署任何額外的合約:

const waitNBlocks = async n => {
 const sendAsync = promisify(web3.currentProvider.sendAsync);
 await Promise.all(
   [...Array(n).keys()].map(i =>
     sendAsync({
       jsonrpc: '2.0',
       method: 'evm_mine',
       id: i
     })
   )
 );
};

引用自:https://ethereum.stackexchange.com/questions/32153