solidityhardhat

Hardhat viem test AbiEncodingLengthMismatchError


I have this function in my smart contract:

function isCategoryValid(bytes32 category) external view returns (bool) {
    return validCategories[category];
}

But when I run this test code:

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

describe("CategoryStorage", function () {
    let CategoryStorage: any, owner: any, nonOwner: any;

    async function deployCategoryStorageFixture() {
        const initialCategories = [stringToHex("InitialCategory", { size: 32 })];
        const CategoryStorage = await hre.viem.deployContract("CategoryStorage", [initialCategories]);
        const [owner, nonOwner] = await hre.viem.getWalletClients();
        return { CategoryStorage, owner, nonOwner };
    }

    // Load the fixture before each test.
    beforeEach(async function () {
        ({ CategoryStorage, owner, nonOwner } = await loadFixture(deployCategoryStorageFixture));
    });

    describe("Deployment", function () {
        it("Should set the right owner", async function () {
            expect(await CategoryStorage.read.owner()).to.equal(getAddress(owner.account.address));
        });

        it("Should initialize with valid categories", async function () {
            const initialCategory = stringToHex("InitialCategory", { size: 32 });
            expect(await CategoryStorage.read.isCategoryValid(initialCategory)).to.be.true;
        });
    });

I get this error:

AbiEncodingLengthMismatchError: ABI encoding params/values length mismatch. Expected length (params): 1 Given length (values): 0

Version: viem@1.18.4 at encodeAbiParameters


Solution

  • you need to pass the parameters within an array. This is a viem requirement for all the contract methods:

    expect(await CategoryStorage.read.isCategoryValid([initialCategory])).to.be.true;