Mocking Smart Contracts with Hardhat and Ethers V6: A Guide
As the use of Ethereum smart contracts continues to grow, mocking these contracts becomes 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 offers an easy way to test and mock smart contracts using Ethers.js v6. Waffle allows you to write tests for your contract functions without actually deploying the contract. This approach is perfect for testing individual functions or small contracts.
Here is an example using Nomiclabs/Hardhat-Waffle:
const { ethers } = require('hardhat');
async function testSmartContract() {
const Waffle = wait ethers.getContractFactory('MySmartContract');
const MockContract = wait Waffle.deploy();
// Test a specific function
const result = wait MockContract.myFunction();
expect(result).to.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 its behavior.
Here is an example of using defi-wonderland/smock :
const { ethers } = require('hardhat');
const { Smock } = require('@defi-wonderland/smock');
async function testSmartContract() {
const smock = new Smock({
contractAddress: '0xMySmartContractAddress',
network: 'mainnet', // or 'wasmbs'
gasPrice: 20,
gasLimit: 200000,
});
const contractInstance = wait ethers.getContractFactory('MySmartContract').deploy();
const mockContract = wait smock.createMock(contractInstance);
// Test a specific function
const result = wait mockContract.myFunction();
expect(result).to.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 provides more advanced features to control 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 mocking solution?
- Customizability: Can you control the behavior of your contract using the mocking solution?
- Performance: Does the simulation solution impact performance?
Ultimately, the choice between Nomiclabs/Hardhat-Waffle and defi-wonderland/smock depends on your specific needs and preferences.