Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor build assert #5856

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 32 additions & 21 deletions packages/hardhat-chai-matchers/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,36 +19,47 @@ export type Ssfi = (...args: any[]) => any;
* the best way to use this value, so this needs some trial-and-error. Use the
* existing matchers for a reference of something that works well enough.
*/
export function buildAssert(negated: boolean, ssfi: Ssfi) {

type Message = string | (() => string);

function evalMessage(message?: Message): string {
if (message === undefined) {
throw new Error(
"Assertion doesn't have an error message. Please open an issue to report this."
);
}

return typeof message === "function" ? message() : message;
}

function buildNegated(ssfi: Ssfi) {
return function (
condition: boolean,
messageFalse?: string | (() => string),
messageTrue?: string | (() => string)
_messageFalse?: Message,
messageTrue?: Message
) {
if (!negated && !condition) {
if (messageFalse === undefined) {
throw new Error(
"Assertion doesn't have an error message. Please open an issue to report this."
);
}

const message =
typeof messageFalse === "function" ? messageFalse() : messageFalse;
if (condition) {
const message = evalMessage(messageTrue);
throw new AssertionError(message, undefined, ssfi);
}
};
}

if (negated && condition) {
if (messageTrue === undefined) {
throw new Error(
"Assertion doesn't have an error message. Please open an issue to report this."
);
}

const message =
typeof messageTrue === "function" ? messageTrue() : messageTrue;
function buildNormal(ssfi: Ssfi) {
return function (
condition: boolean,
messageFalse?: Message,
_messageTrue?: Message
) {
if (!condition) {
const message = evalMessage(messageFalse);
throw new AssertionError(message, undefined, ssfi);
}
};
}

export function buildAssert(negated: boolean, ssfi: Ssfi) {
return negated ? buildNegated(ssfi) : buildNormal(ssfi);
}

export type AssertWithSsfi = ReturnType<typeof buildAssert>;