Hardhat viem common patterns in testing

Hardhat viem common patterns in testing


hardhat solidity blockchain testing

Here I am sharing snippets that have been very helpful to me while testing smart contracts with hardhat-viem. I found it more counter-intuitive that ethers and I am pointing out some of viem particularities.

Common imports

import {loadFixture} from "@nomicfoundation/hardhat-toolbox-viem/network-helpers";
import {expect} from "chai";
import hre from "hardhat";

Deploying a contract

const deploy = async (): Promise<DeployResult> => {
    const [owner, addr1, addr2] = await hre.viem.getWalletClients();
    const hardhatToken = await hre.viem.deployContract("Token");
    return {hardhatToken, owner, addr1, addr2};
}

Getting information about account

Pay attention to read and .account.

const {hardhatToken, owner} = await loadFixture(deploy);
console.log(owner.account.address)
const ownerBalance = await hardhatToken.read.balanceOf([owner.account.address]);

Calling view functions

Again, we need read.

const maxSupply = await hardhatToken.read.maxSupply();

Calling a payable function with a custom address

expect(hardhatToken.write.transfer([owner.account.address, 10],
    {account: addr1.account.address})).to.be.rejectedWith("not enough tokens");

Comments

© 2024 Vassilis Papapanagiotou