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 recent 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 Choice
The first solution is Nomiclabs’ Hardhat-Waffle, which provides an easy way to test and mock smart contracts using Ethers.js v6. Waffle allows you to write tests of the contract’s functionality without even implementing the contract. This approach is great for testing individual features or small contracts.
Here is an example of how to use Nomiclabs/Hardhat-Waffle:
const { ethers } = require('hardhat');
async function testSmartContract() {
const Waffle = await ethers.getContractFactory('MySmartContract');
const MockContract = await Waffle.deploy();
// Test the specific function
const result = await MockContract.myFunction();
expect(result).be.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 their behavior.
Here is an example of how to use defi-wonderland/smock:
const { ethers } = require('hardhat');
const { Smock } = require('@defi-wonderland/smock');
asynchronous function testSmartContract() {
const smock = new Smock({
contractAddress: "0xMySmartContractAddress",
network: 'mainnet', // or 'wasmbs'
gasPrice: 20,
gas limit: 200,000,
});
const contractInstance = await ethers.getContractFactory('MySmartContract').deploy();
const mockContract = await smock.createMock(contractInstance);
// Test a specific function
const result = await mockContract.myFunction();
expect(result).will.true;
}
testSmartContract();
Conclusion
In this article, we explored two ways to simulate smart contracts with Hardhat and Ethers.js v6. While Nomiclabs/Hardhat-Waffle is a popular solution, defi-wonderland/smock provide more advanced features that allow you to control the behavior of your contract.
When choosing a simulation solution, consider the following factors:
- Ease of use: Is it easy to set up and use the simulated solution?
- Customizability: Can you control the behavior of your contract using a mock solution?
- Performance: Does the simulated solution affect performance?
Ultimately, the choice between Nomiclabs/Hardhat-Waffle and Defi-wonderland/Smock depends on your specific needs and preferences.