Mocking Smart Contracts with Hardhat and Ethers V6: A Guide
As the use of Ethereum smart contracts continues to grow, mocking these contracts is becoming increasingly important. With the latest releases of Hardhat (version 4) and Ethers.js v6, it is now possible to mock smart contracts using two popular solutions. In this article, we will explore both options and provide a step-by-step guide on how to use them.
Nomiclabs/Hardhat-Waffle: A Popular Option
The first solution is Hardhat-Waffle from Nomiclabs, which provides a simple way to test and mock smart contracts using Ethers.js v6. Waffle allows you to write tests for the functions of your contract without actually implementing the contract. This approach is perfect for testing individual functions or small contracts.
Here is an example of using Nomiclabs/Hardhat-Waffle:
const { ethers } = require('hardhat');
asynchronous function testSmartContract() {
const Waffle = await ethers.getContractFactory('MySmartContract');
const MockContract = await Waffle.deploy();
// Test a given function
const result = await MockContract.myFunction();
await(result).true;
}
testSmartContract();
defi-wonderland/smock: a more advanced option
The second solution is defi-wonderland/smock, which provides a more advanced way to mock smart contracts using Ethers.js v6. Smock allows you to create mock instances of your contract and control its behavior.
Here is an example of using defi-wonderland/smock:
const { ethers } = require('helmet');
const { Smock } = require('@defi-wonderland/smock');
asynchronous function testSmartContract() {
const smock = new smock({
contractAddress: "0xMySmartContractAddress",
network: "mainnet", // or "wasmbs"
Gas price: 20,
Gas limit: 200000,
});
const contractInstance = await ethers.getContractFactory('MySmartContract').deploy();
const mockContract = await smock.createMock(contractInstance);
// Test a specific function
const result = await mockContract.myFunction();
await(result).be.true;
}
testSmartContract();
Conclusion
In this article, we explored two ways to mock smart contracts with Hardhat and Ethers.js v6. While Nomiclabs/Hardhat-Waffle is a popular solution, defi-wonderland/smock offers more advanced features for controlling the behavior of your contract.
When choosing a mocking solution, consider the following factors:
- Ease of use: How easy is it to set up and use the mock solution?
- Customization: Can you control the behavior of your contract using the mock solution?
- Performance: Does the mock solution impact performance?
Ultimately, the choice between Nomiclabs/Hardhat-Waffle and defi-wonderland/smock depends on your specific needs and preferences.