npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@gregdhill/mock-contract

v3.0.4

Published

Mock smart contracts in a smart way.

Downloads

1

Readme

Ethereum Waffle

CircleCI

@ethereum-waffle/mock-contract

Library for mocking smart contract dependencies during unit testing.

Installation

In the current version of waffle (v2.x.x) you will install this package as a dependency of the main waffle package - ethereum-waffle.

yarn add --dev ethereum-waffle
npm install --save-dev ethereum-waffle

If you want to use this package directly please install it via:

yarn add --dev @ethereum-waffle/mock-contract
npm install --save-dev @ethereum-waffle/mock-contract

Usage

Create an instance of a mock contract providing the ABI/interface of the smart contract you want to mock:

const {deployMockContract} = require('@ethereum-waffle/mock-contract');

...

const mockContract = await deployMockContract(wallet, contractAbi);

Mock contract can now be passed into other contracts by using the address attribute.

Return values for mocked functions can be set using:

await mockContract.mock.<nameOfMethod>.returns(<value>)
await mockContract.mock.<nameOfMethod>.withArgs(<arguments>).returns(<value>)

Methods can also be set up to be reverted using:

await mockContract.mock.<nameOfMethod>.reverts()
await mockContract.mock.<nameOfMethod>.withArgs(<arguments>).reverts()

Sometimes you may have an overloaded function name:

contract OverloadedFunctions is Ownable {
  function burn(uint256 amount) external returns (bool) {
    // ...
  }

  function burn(address user, uint256 amount) external onlyOwner returns (bool) {
    // ...
  }
}

You may choose which function to call by using its signature:

await mockContract.mock['burn(uint256)'].returns(true)
await mockContract.mock['burn(address,uint256)'].withArgs('0x1234...', 1000).reverts()

You may wish to execute another contract through a mock. Given the "AmIRichAlready" code below, you could call constant functions using staticcall:

const contractFactory = new ContractFactory(AmIRichAlready.abi, AmIRichAlready.bytecode, sender);
const amIRich = await contractFactory.deploy()
const mockERC20 = await deployMockContract(sender, IERC20.abi);

let result = await mockERC20.staticcall(amIRich, 'check()')
// you may also just use the function name
result = await mockERC20.staticcall(amIRich, 'check')
expect(result).to.equal(true) // result will be true if you have enough tokens

You may also execute transactions through the mock, using call:

const contractFactory = new ContractFactory(AmIRichAlready.abi, AmIRichAlready.bytecode, sender);
const amIRich = await contractFactory.deploy()
const mockERC20 = await deployMockContract(sender, IERC20.abi);

let result = await mockERC20.call(amIRich, 'setRichness(uint256)', 1000)
// you may also just use the function name
result = await mockERC20.call(amIRich, 'setRichness', 1000)
expect(await amIRich.richness()).to.equal('1000') // richness was updated

Example

The example below illustrates how mock-contract can be used to test the very simple AmIRichAlready contract.

pragma solidity ^0.6.0;

interface IERC20 {
    function balanceOf(address account) external view returns (uint256);
}

contract AmIRichAlready {
    IERC20 private tokenContract;
    uint public richness = 1000000 * 10 ** 18;

    constructor (IERC20 _tokenContract) public {
        tokenContract = _tokenContract;
    }

    function check() public view returns (bool) {
        uint balance = tokenContract.balanceOf(msg.sender);
        return balance > richness;
    }

    function setRichness(uint256 _richness) {
      richness = _richness;
    }
}

We are mostly interested in the tokenContract.balanceOf call. Mock contract will be used to mock exactly this call with values that are significant for the return of the check() method.

const {use, expect} = require('chai');
const {ContractFactory, utils} = require('ethers');
const {MockProvider} = require('@ethereum-waffle/provider');
const {waffleChai} = require('@ethereum-waffle/chai');
const {deployMockContract} = require('@ethereum-waffle/mock-contract');

const IERC20 = require('../build/IERC20');
const AmIRichAlready = require('../build/AmIRichAlready');

use(waffleChai);

describe('Am I Rich Already', () => {
  async function setup() {
    const [sender, receiver] = new MockProvider().getWallets();
    const mockERC20 = await deployMockContract(sender, IERC20.abi);
    const contractFactory = new ContractFactory(AmIRichAlready.abi, AmIRichAlready.bytecode, sender);
    const contract = await contractFactory.deploy(mockERC20.address);
    return {sender, receiver, contract, mockERC20};
  }

  it('returns false if the wallet has less then 1000000 coins', async () => {
    const {contract, mockERC20} = await setup();
    await mockERC20.mock.balanceOf.returns(utils.parseEther('999999'));
    expect(await contract.check()).to.be.equal(false);
  });

  it('returns true if the wallet has at least 1000000 coins', async () => {
    const {contract, mockERC20} = await setup();
    await mockERC20.mock.balanceOf.returns(utils.parseEther('1000001'));
    expect(await contract.check()).to.equal(true);
  });

  it('reverts if the ERC20 reverts', async () => {
    const {contract, mockERC20} = await setup();
    await mockERC20.mock.balanceOf.reverts();
    await expect(contract.check()).to.be.revertedWith('Mock revert');
  });

  it('returns 1000001 coins for my address and 0 otherwise', async () => {
    const {contract, mockERC20, sender, receiver} = await setup();
    await mockERC20.mock.balanceOf.returns('0');
    await mockERC20.mock.balanceOf.withArgs(sender.address).returns(utils.parseEther('1000001'));

    expect(await contract.check()).to.equal(true);
    expect(await contract.connect(receiver.address).check()).to.equal(false);
  });
});

Special thanks

Special thanks to @spherefoundry for creating the original Doppelganger project.