Simulating Smart Contracts with Hardhat and Ethers v6: A Guide
As the use of Ethereum smart contracts continues to grow, simulating these contracts becomes increasingly important. With the latest releases of Hardhat (version 4) and Ethers.js v6, it is now possible to simulate smart contracts using two popular solutions. In this article, we will discuss both options and provide a step-by-step guide on how to use them.
Nomiclabs/Hardhat-Waffle: Popular Variation
The first solution is Hardhat-Waffle by Nomiclabs, which provides a simple way to test and simulate smart contracts using Ethers.js v6. Waffle allows you to write tests for your contract functions without deploying the contract. This approach is ideal for testing individual functions or small contracts.
Here is an example using Nomiclabs/Hardhat-Waffle:
const {ethers} = require('helmet');
async function testSmartContract() {
const Waffle = await ethers.getContractFactory('MySmartContract');
const MockContract = await Waffle.deploy();
// Testing a certain function
const result = await MockContract.myFunction();
await (result).to.true;
}
testSmartContract();
defi-wonderland/smock – more advanced version
The second solution is defi-wonderland/smock, which provides a more advanced way of mocking 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 using defi-wonderland/smock:
const {ethers} = require('helmet');
const { Bata } = require('@defi-wonderland/bata');
async function testSmartContract() {
const bata = new bata({
contractAddress: '0xMySmartContractAddress',
network: 'mainnet', // or 'wasmbs'
gasPrice: 20,
gasLimit: 200000,
});
const contractInstance = await ethers.getContractFactory('MySmartContract').deploy();
const mockContract = await smock.createMock(contractInstance);
// Testing a certain function
const result = await mockContract.myFunction();
expect (result).to.true;
}
testSmartContract();
Conclusion
In this article, we looked at two ways to create smart contract mockups using 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.
Consider the following factors when choosing a mockup solution:
- Ease of use: How easy is the mockup solution to set up and use?
- Customization: Can you control the behavior of your contract with a mockup solution?
- Performance: Does the mockup solution affect performance?
Ultimately, the choice between Nomiclabs/Hardhat-Waffle and defi-wonderland/smock depends on your specific needs and preferences.