hardhat-test-utils
TypeScript icon, indicating that this package has built-in type declarations

0.1.1 • Public • Published

hardhat-test-utils 🛠

npm version Node.js CI

Handy utilities for testing contracts in Hardhat projects.

What

This plugin provides a set of various utility functions for testing solidity smart contracts that in a Hardhat project.

Check Usage or API section for more details.

Installation

Install with:

npm:

npm install --save-dev hardhat-test-utils hardhat ethers @nomiclabs/hardhat-ethers

or, yarn:

yarn add -D hardhat-test-utils hardhat ethers @nomiclabs/hardhat-ethers

Import the plugin in your hardhat.config.js:

require('hardhat-test-utils');

Or if you are using TypeScript, in your hardhat.config.ts:

import 'hardhat-test-utils';

Required plugins

Tasks

This plugin creates no additional tasks.

Environment extensions

This plugin adds testUtils object to Hardhat Runtime Environment. This object exposes following properties to manipulate corresponding aspects:

See API.

Usage

There are no additional steps you need to take for this plugin to work.

Install it and access testUtils through the Hardhat Runtime Environment anywhere you need it (tasks, scripts, tests, etc). For example:

const { testUtils } = require('hardhat');

const { time, address, constants } = testUtils;

describe('my tests', function () {
  it('simulates passing of time', async function () {
    const oneHourInSeconds = time.duration.hours(1);
    await time.increase(oneHourInSeconds);
  });

  it('sets the balance of an address', async function () {
    const userAddr = '0x....';
    const newBalance = constants.WEI_PER_ETHER; // 1 ether
    await address.setBalance(userAddr, newBalance);
  });
});

API

The testUtils objects exposes following properties with methods:

block 🧱

Exposes methods to manipulate blocks.

const { block } = testUtils;

block.getAutomine()

Returns true if automatic mining is enabled, and false otherwise. See Mining Modes to learn more.

Params

None

Returns

<Promise<boolean>>: true if automatic mining is enabled, and false otherwise.


block.setAutomine(enabled: boolean)

Sets automatic mining mode. See Mining Modes to learn more.

Params
  • enabled: boolean: true to enable automatic mining, false to disable it.
Returns

<Promise<boolean>>: Result of the rpc call.


block.setIntervalMine(interval: number | BigNumber)

Enables (with a numeric argument greater than 0) or disables (with a numeric argument equal to 0), the automatic mining of blocks at a regular interval of milliseconds, each of which will include all pending transactions. See also Mining Modes.

Params
  • interval: number | BigNumber: Interval in milliseconds.
Returns

<Promise<boolean>>: Result of the rpc call.


block.latest()

Returns the latest block information. This is same as calling provider.getBlock('latest') with ethers.

Params

None

Returns

<Promise<Block>>: Latest block information.


block.latestNumber()

Returns the latest block number. This is same as calling provider.getBlockNumber() with ethers.

Params

None

Returns

<Promise<number>>: Latest block number.


block.advance(n: number | BigNumber, interval: number | BigNumber)

Forces n number of blocks to be mined, incrementing the block height by n.

Params
  • n: number | BigNumber: Number of blocks to mine. Defaults to 1.
  • interval: number | BigNumber: Interval between the timestamps of each block, in seconds. Defaults to 1.
Returns

<Promise<boolean>>: Result of the rpc call.

NOTE: This method can mine any number of blocks at once, in constant time. It exhibits the same performance no matter how many blocks are mined.


block.advanceTo(target: number | BigNumber, interval: number | BigNumber)

Forces blocks to be mined until the target height` is reached.

Params
  • target: number | BigNumber: Target block height.
  • interval: number | BigNumber: Interval between the timestamps of each block, in seconds. Defaults to 1.
Returns

<Promise<boolean>>: Result of the rpc call.



time

Simulates passing of time.

const { time } = testUtils;

time.latest()

Gets the latest block timestamp.

Params

None

Returns

<Promise<number>>: Latest block timestamp.


time.increase(duration: number | BigNumber)

Increases blockchain's time by duration seconds and mines a new block.

Params
  • duration: number | BigNumber: Number of seconds to increase the time by.
Returns

<Promise<number>>: Total time adjustment, in seconds.


time.increaseTo(target: number | BigNumber)

Same as time.increase(), but takes the exact timestamp that you want in the next block, and mines that block.

Params
  • target: number | BigNumber: Target timestamp for the newly mined block.
Returns

<Promise<number>>: Total time adjustment, in seconds.


time.duration.<unit>(value: number | BigNumber)

An set of duration object methods to convert time units to seconds. For example:

time.duration.minutes(1); // 60
time.duration.hours(1); // 3600
time.duration.days(1); // 86400
time.duration.weeks(1); // 604800
time.duration.years(1); // 31536000

Available units are minutes, hours, days, weeks, years.

Params
  • value: number | BigNumber: Value in a time unit to convert to number of seconds.
Returns

<Promise<number>>: Number of seconds.



address 📃

Manipulate addresses.

const { address } = testUtils;

address.isValid(addr: string)

Returns true if addr is valid ethereum address, false otherwise.

Params
  • addr: string: address to check
Returns

boolean: true if addr is valid ethereum address, false otherwise.


address.balance(addr: string)

Returns balance of given address in wei unit.

Params
  • addr: string: address to fetch balance of.
Returns

<Promise<BigNumber>>: balance of given address in wei.


address.balanceEth(addr: string)

Returns balance of given address in eth unit.

Params
  • addr: string: address to fetch balance of.

Returns

<Promise<BigNumber>>: balance of given address in eth.


address.setBalance(addr: string, balance: number | BigNumber)

Modify the balance of given address.

Params
  • addr: string: address to modify balance of.
  • balance: number | BigNumber: new balance of given address.
Returns

<Promise<boolean>>: result of the rpc call.


address.impersonate(addr: string)

Impersonate as specific account and contract addresses and returns the corresponding ethers Signer. See hardhat_impersonateAccount

Params
  • addr: string: address to impersonate.
Returns

<Promise<Signer>>: Signer corresponding to impersonated account.


address.stopImpersonating(addr: string)

Stops impersonating an account after having previously used address.impersonate().

Params
  • addr: string: address to stop impersonating.
Returns

<Promise<boolean>>: result of the rpc call.



network ⛓️

Blockchain network utilities.

const { network } = testUtils;

network.snapshot()

Takes snapshot of current network state.

Params

None

Returns

<Promise<string>>: Snapshot id


network.revert(snapshotId: string)

Reverts the state of network to a previous snapshot.

Params
  • snapshotId: string: Id of snapshot to revert to.
Returns

<Promise<boolean>>: Result of the rpc call.



abi 🔡

Abi encoding utilities.

const { abi } = testUtils;

abi.encodeFunctionSignature(func: string)

Outputs the function selector of a function.

Params
  • func: string: Function name with parameter types. E.g. "transfer(address,uint256)"
Returns

string: Function selector.


abi.encodeFunctionCall(func: string, args: any[])

Outputs the encoded function call.

Params
  • func: string: Function name with parameter types. E.g. "transfer(address,uint256)"
  • args: any[]: Function arguments. E.g. ["0xd55..64b", "10000000"]
Returns

string: Abi encoded function call.



constants 🔩

Some useful constants.

const { constants } = testUtils;

constants.ZERO_ADDRESS: string

The zero ethereum address - 0x0000000000000000000000000000000000000000


constants.ZERO_BYTES32: string

The zero 32 bytes array - 0x0000000000000000000000000000000000000000000000000000000000000000


constants.MAX_UINT256: BigNumber

The BigNumber value representing the maximum uint256 value.


constants.MAX_INT256: BigNumber

The BigNumber value representing the maximum int256 value.


constants.MIN_INT256: BigNumber

The BigNumber value representing the minimum int256 value.


constants.WEI_PER_ETHER: BigNumber

The BigNumber value representing 1000000000000000000, which is the number of wei per ether.



BN 1️⃣

Shorthand for ethers BigNumber object.

Package Sidebar

Install

npm i hardhat-test-utils

Weekly Downloads

10

Version

0.1.1

License

MIT

Unpacked Size

45.6 kB

Total Files

59

Last publish

Collaborators

  • thenvn