Skip to content

Instantly share code, notes, and snippets.

@ccolorado
Created March 14, 2019 07:18
Show Gist options
  • Save ccolorado/2b31b6842b3110b1dbc04c90921e9a93 to your computer and use it in GitHub Desktop.
Save ccolorado/2b31b6842b3110b1dbc04c90921e9a93 to your computer and use it in GitHub Desktop.
const pify = require('pify');
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
const ethAsync = pify(web3.eth);
const ethGetBlock = ethAsync.getBlock;
web3.currentProvider.sendAsync = web3.currentProvider.send;
async function advanceBlock () {
console.log("\tadvancing ");
await web3.currentProvider.send({
jsonrpc: '2.0',
method: 'evm_mine',
id: new Date().getTime()
});
console.log("\tadvanced");
}
// Returns the time of the last mined block in seconds
async function latest () {
const block = await ethGetBlock('latest');
return block.timestamp;
}
// Increases ganache time by the passed duration in seconds
// async function increase (duration, web3Replace) {
async function increase (duration) {
if (duration < 0) throw Error(`Cannot increase time by a negative amount (${duration})`);
await web3.currentProvider.send({
jsonrpc: '2.0',
method: 'evm_increaseTime',
params: [duration],
id: Number(Math.random() * 1000).toFixed(0)
})
await advanceBlock() // optional (*)
}
/**
* Beware that due to the need of calling two separate ganache methods and rpc calls overhead
* it's hard to increase time precisely to a target point so design your test to tolerate
* small fluctuations from time to time.
*
* @param target time in seconds
*/
async function increaseTo (target) {
const now = (await latest());
if (target < now) throw Error(`Cannot increase current time (${now}) to a moment in the past (${target})`);
const diff = target - now;
return increase(diff);
}
const duration = {
seconds: function (val) { return val; },
minutes: function (val) { return val * this.seconds(60); },
hours: function (val) { return val * this.minutes(60); },
days: function (val) { return val * this.hours(24); },
weeks: function (val) { return val * this.days(7); },
years: function (val) { return val * this.days(365); },
};
module.exports = {
advanceBlock,
latest,
increase,
increaseTo,
duration,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment