Waffle

A estrutura mais avançada para testar contratos inteligentes. Mais doce, mais simples e mais rápido.

Link para Github:

CI

Ethereum Waffle

Links

Filosofia

  • Mais simples : minimalista, poucas dependências.
  • Sweeter : sintaxe agradável, fácil de estender.
  • Mais rápido : Foco forte na velocidade de execução do teste.

Características:

  • Conjunto doce de combinadores de chai, por exemplo:
    • expect(...).to.be.revertedWith('Error message')
    • expect(...).to.emit(contract, 'EventName').withArgs(...))
  • Importar contratos de módulos npm funcionando fora da caixa, por exemplo:
    • import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
  • Fixtures que ajudam a escrever suítes de teste rápidas e fáceis de manter, por exemplo:
    • const {token} = await loadFixture(standardTokenWithBalance);
  • Opções de compilação personalizáveis ​​com solc nativo, solc dockerized e qualquer versão de solc-js carregada remotamente em tempo de compilação
  • Zombar de contratos inteligentes, por exemplo:
    • const mockToken = await deployMockContract(wallet, IERC20.abi);
  • Suporte para configuração baseada em promessa, por exemplo:
    • use o binário solc nativo para compilação rápida em ambiente de CI
    • usar solc-js com base nas versões de contrato detectadas (assíncrono)
  • Suporte para TypeScript
  • Implantação de contrato de tipo seguro e interações com TypeChain
  • Documentação

Documentação

A documentação está disponível aqui .

Instalação:

Para começar a instalar ethereum-wafflecom yarn:

yarn add --dev ethereum-waffle 

Ou se preferir usar npm:

npm install --save-dev ethereum-waffle 

Guia passo a passo

Adicionar dependência externa:

Para adicionar uma biblioteca externa, instale-a usando npm:

npm install @ openzeppelin / contratos -D

ou com fio:

yarn add @ openzeppelin / contratos -D

Observação

Encontre este exemplo examples/basice use-o.

Contrato de exemplo

Abaixo está um exemplo de contrato escrito em Solidity. Coloque-o no contracts/BasicToken.solarquivo do seu projeto:

solidez do pragma ^ 0 . 6 . 0 ;  importar  "@ openzeppelin / contratos / token / ERC20 / ERC20.sol" ;  // Example class - a mock class using delivering from ERC20 contract BasicToken is ERC20 {     constructor(uint256 initialBalance) ERC20("Basic", "BSC") public {         _mint(msg.sender, initialBalance);     } } 

Example test

Below is an example test written for the contract above compiled with Waffle. Place it under test/BasicToken.test.ts file in your project directory:

import {expect, use} from 'chai'; import {Contract} from 'ethers'; import {deployContract, MockProvider, solidity} from 'ethereum-waffle'; import BasicToken from '../build/BasicToken.json';  use(solidity);  describe('BasicToken', () => {   const [wallet, walletTo] = new MockProvider().getWallets();   let token: Contract;    beforeEach(async () => {     token = await deployContract(wallet, BasicToken, [1000]);   });    it('Assigns initial balance', async () => {     expect(await token.balanceOf(wallet.address)).to.equal(1000);   });    it('Transfer adds amount to destination account', async () => {     await token.transfer(walletTo.address, 7);     expect(await token.balanceOf(walletTo.address)).to.equal(7);   });    it('Transfer emits event', async () => {     await expect(token.transfer(walletTo.address, 7))       .to.emit(token, 'Transfer')       .withArgs(wallet.address, walletTo.address, 7);   });    it('Can not transfer above the amount', async () => {     await expect(token.transfer(walletTo.address, 1007)).to.be.reverted;   });    it('Can not transfer from empty account', async () => {     const tokenFromOtherWallet = token.connect(walletTo);     await expect(tokenFromOtherWallet.transfer(wallet.address, 1))       .to.be.reverted;   });    it('Calls totalSupply on BasicToken contract', async () => {     await token.totalSupply();     expect('totalSupply').to.be.calledOnContract(token);   });    it('Calls balanceOf with sender address on BasicToken contract', async () => {     await token.balanceOf(wallet.address);     expect('balanceOf').to.be.calledOnContractWith(token, [wallet.address]);   }); });

Note: You will also need to install following dependencies with to run the example above:

yarn add mocha -D yarn add chai -D

Or with npm:

npm i chai -D npm i mocha -D 

Compiling

To compile your smart contracts run:

npx waffle

To compile using a custom configuration file run:

npx waffle config.json

Example configuration file looks like this (all fields optional):

{   "sourceDirectory": "./custom_contracts",   "outputDirectory": "./custom_build",   "nodeModulesDirectory": "./custom_node_modules" }

To enable generation of typechain artifacts:

{   "typechain": {     "enable": true   } }

Flattener

To flat your smart contracts run:

npx waffle flatten

In configuration file you can add optional field with path to flatten files:

{   "flattenOutputDirectory": "./custom_flatten" }

Running tests

To run the tests run the following command:

npx mocha

Adding an npm script

For convinience, you can add the following to your package.json:

{   ...,   "scripts": {     "test": "waffle && mocha"   } } 

Now you can build and test your contracts with one command:

npm test

Documentation

For detailed feature walkthrough checkout documentation.

Contributing

Contributions are always welcome, no matter how large or small. Before contributing, please read the code of conduct and contribution policy.

Before you issue pull request:

Make sure all tests and linters pass. Make sure you have test coverage for any new features.

Running tests

Note: To make end-to-end test pass, you need to:

  • have Docker installed, up and running
  • have Ethereum stable docker image pulled, if not run docker pull ethereum/solc:stable
  • have native solidity 0.5.* installed

To run tests type:

yarn test

To run linter type:

yarn lint

Building documentation

Install Sphinx to build documentation:

cd docs make html

Before building documentation for the first time you may have to install required python packages:

pip3 install -r docs/requirements.txt

Roadmap

Veja https://github.com/EthWorks/Waffle/issues/155

Licença

Waffle é lançado sob a licença do MIT .