API Reference

This documentation is a work in progress: if in doubt, head over to the tests directory to see examples of how each helper can be used.

All returned numbers are of type BN.

balance

Helpers to inspect Ether balances of a specific account.

All of these functions return BN instances, with balances in 'wei' by default.

current

async function balance.current(account, unit = 'wei')

Returns the current balance of an account.

const balance = await balance.current(account)
// same as new BN(web3.eth.getBalance(account))

const balanceEth = await balance.current(account, 'ether')
// same as new BN(web3.utils.fromWei(await web3.eth.getBalance(account), 'ether'))

tracker

async function balance.tracker(account, unit = 'wei')

Creates an instance of a balance tracker, which lets you keep track of the changes in an account’s Ether balance.

const tracker = await balance.tracker(account)

tracker.get

async function tracker.get(unit = tracker.unit)

Returns the current balance of an account.

const tracker = await balance.tracker(account) // instantiation
const currentBalance = await tracker.get() // returns the current balance of account

tracker.delta

async function tracker.delta(unit = tracker.unit)

Returns the change in the balance since the last time it was queried (with either get, delta, or deltaWithFees).

const tracker = await balance.tracker(receiver, 'ether')
send.ether(sender, receiver, ether('10'))
(await tracker.delta()).should.be.bignumber.equal('10');
(await tracker.delta()).should.be.bignumber.equal('0');

Or using get():

const tracker = await balance.tracker(account) // instantiation
const currentBalance = await tracker.get() // returns the current balance of account
(await tracker.delta()).should.be.bignumber.equal('0');

A tracker can also return all balances and deltas in a specific unit:

const tracker = await balance.tracker(account, 'gwei');
const balanceGwei = tracker.get(); // in gigawei
const balanceEther = tracker.get('ether'); // in ether

tracker.deltaWithFees

async function tracker.deltaWithFees(unit = tracker.unit)

Returns an object containing both the change in the balance since the last time it was queried (with either get, delta, or deltaWithFees), as well as the gas fees paid during this time.

const tracker = await balance.tracker(account, 'gwei');
...
const { delta, fees } = await tracker.deltaWithFees();

BN

A bn.js object. Use new BN(number) to create BN instances.

constants

A collection of useful constants.

ZERO_ADDRESS

The initial value of an address type variable, i.e., address(0) in Solidity.

ZERO_BYTES32

The initial value of a bytes32 type variable, i.e., bytes32(0x00) in Solidity.

MAX_UINT256

The maximum unsigned integer 2\^256 - 1 represented in BN.

MAX_INT256

The maximum signed integer 2\^255 - 1 represented in BN.

MIN_INT256

The minimum signed integer -2\^255 represented in BN.

ether

Converts a value in Ether to wei.

expectEvent

function expectEvent(receipt, eventName, eventArgs = {})

Asserts that the logs in receipt contain an event with name eventName and arguments that match those specified in eventArgs. receipt should be an object returned by either a web3 Contract or a truffle-contract call.

const web3Receipt = await MyWeb3Contract.methods.foo('bar').send();
expectEvent(web3Receipt, 'Foo', { value: 'bar' });

const truffleReceipt = await MyTruffleContract.foo('bar');
expectEvent(truffleReceipt, 'Foo', { value: 'bar' });

Note that it’s possible to leave some or all event arguments unspecified: expectEvent will only check the arguments that are provided and ignore the rest.

const receipt = await MyWeb3Contract.methods.foo('bar').send();

// Both of these assertions will pass
expectEvent(receipt, 'Foo', { value: 'bar' });
expectEvent(receipt, 'Foo');

inTransaction

async function expectEvent.inTransaction(txHash, emitter, eventName, eventArgs = {})

Same as expectEvent, but for events emitted in an arbitrary transaction (of hash txHash), by an arbitrary contract (emitter, the contract instance), even if it was indirectly called (i.e. if it was called by another smart contract and not an externally owned account).

Note: emitter must be the deployed contract instance emitting the expected event.

// With web3 contracts
const contract = await MyContract.deploy().send();
const { transactionHash } = await contract.methods.foo('bar').send();
await expectEvent.inTransaction(transactionHash, contract, 'Foo', { value: 'bar' });

// With truffle contracts
const contract = await MyContract.new();
const { txHash } = await contract.foo('bar');
await expectEvent.inTransaction(txHash, contract, 'Foo', { value: 'bar' });

inConstruction

async function expectEvent.inConstruction(emitter, eventName, eventArgs = {})

Same as inTransaction, but for events emitted during the construction of emitter. Note that this is currently only supported for truffle contracts.

notEmitted

In order to test that an event was not emitted there is expectEvent.notEmitted. There are several variants that follow the API of previously mentioned functions:

  • expectEvent.notEmitted(receipt, eventName) similar to expectEvent()

  • expectEvent.notEmitted.inTransaction(txHash, emitter, eventName) similar to expectEvent.inTransaction()

  • expectEvent.notEmitted.inConstruction(emitter, eventName) similar to expectEvent.inConstruction()

expectRevert

async function expectRevert(promise, message)

Helpers for transaction failure (similar to chai’s throw): asserts that promise was rejected due to a reverted transaction.

It will also check that the revert reason includes message. Use expectRevert.unspecified when the revert reason is unknown.

For example, given the following contract:

contract Owned {
    address private _owner;

    constructor () {
        _owner = msg.sender;
    }

    function doOwnerOperation() public view {
        require(msg.sender == _owner, "Unauthorized");
        ....
    }
}

The require statement in the doOwnerOperation function can be tested as follows:

const { expectRevert } = require('@openzeppelin/test-helpers');

const Owned = artifacts.require('Owned');

contract('Owned', ([owner, other]) => {
  beforeEach(async function () {
    this.owned = Owned.new({ from: owner });
  });

  describe('doOwnerOperation', function() {
    it('Fails when called by a non-owner account', async function () {
      await expectRevert(
        this.owned.doOwnerOperation({ from: other }),
        "Unauthorized"
      );
    });
  });
  ...

unspecified

async function expectRevert.unspecified(promise)

Like expectRevert, asserts that promise was rejected due to a reverted transaction caused by a require or revert statement, but doesn’t check the revert reason.

assertion

async function expectRevert.assertion(promise)

Asserts that promise was rejected due to a reverted transaction caused by an assert statement or an invalid opcode.

outOfGas

async function expectRevert.outOfGas(promise)

Asserts that promise was rejected due to a transaction running out of gas.

makeInterfaceId

ERC165

function makeInterfaceId.ERC165(interfaces = [])

Calculates the ERC165 interface ID of a contract, given a series of function signatures.

ERC1820

function makeInterfaceId.ERC1820(name)

Calculates the ERC1820 interface hash of a contract, given its name.

send

ether

async function send.ether(from, to, value)

Sends value Ether from from to to.

transaction

async function send.transaction(target, name, argsTypes, argsValues, opts = {})

Sends a transaction to contract target, calling method name with argValues, which are of type argTypes (as per the method’s signature).

singletons

ERC1820Registry

async function singletons.ERC1820Registry(funder)

Returns an instance of an ERC1820Registry deployed as per the specification (i.e. the registry is located at the canonical address). This can be called multiple times to retrieve the same instance.

time

advanceBlock

async function time.advanceBlock()

Forces a block to be mined, incrementing the block height.

advanceBlockTo

async function time.advanceBlockTo(target)

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

Note: Using this function to advance too many blocks can really slow down your tests. Keep its use to a minimum.

latest

async function time.latest()

Returns the timestamp of the latest mined block. Should be coupled with advanceBlock to retrieve the current blockchain time.

latestBlock

async function time.latestBlock()

Returns the latest mined block number.

increase

async function time.increase(duration)

Increases the time of the blockchain by duration (in seconds), and mines a new block with that timestamp.

increaseTo

async function time.increaseTo(target)

Same as increase, but a target time is specified instead of a duration.

duration

function time.duration()

Helpers to convert different time units to seconds. Available helpers are: seconds, minutes, hours, days, weeks and years.

await time.increase(time.duration.years(2));

snapshot

async function snapshot()

Returns a snapshot object with the 'restore' function, which reverts blockchain to the captured state.

const snapshotA = await snapshot()
// ...
await snapshotA.restore()